<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <math.h>
#include <algorithm>
#include <memory>
#include <new>
#include <utility>

#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"

using tensorflow::gtl::ArraySlice;

namespace xla {
namespace {

class MultiOutputFusionTest : public HloTestBase {
 public:
  ErrorSpec error_spec_{0.0001, 1e-2};

 protected:
  MultiOutputFusionTest() {}
  void RunTest2D(bool manual_fusion, int64 size) {
    auto builder = HloComputation::Builder(TestName());
    auto hlo_module = CreateNewModule();

    const Shape elem_shape0 = ShapeUtil::MakeShape(F32, {});
    const Shape elem_shape2 = ShapeUtil::MakeShape(F32, {size, size});

    auto const0 = builder.AddInstruction(
        HloInstruction::CreateConstant(Literal::CreateR0<float>(8.0f)));
    auto param0 = builder.AddInstruction(
        HloInstruction::CreateParameter(0, elem_shape0, "0"));

    auto add1 = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape0, HloOpcode::kAdd, param0, const0));

    HloInstruction* broadcast = builder.AddInstruction(
        HloInstruction::CreateBroadcast(elem_shape2, add1, {0, 1}));

    auto param1 = builder.AddInstruction(
        HloInstruction::CreateParameter(1, elem_shape2, "1"));

    HloInstruction* add2 = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape2, HloOpcode::kAdd, broadcast, param1));
    HloInstruction* sub = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape2, HloOpcode::kSubtract, param1, broadcast));
    HloInstruction* dot = builder.AddInstruction(
        HloInstruction::CreateBinary(elem_shape2, HloOpcode::kDot, sub, add2));
    auto computation = hlo_module->AddEntryComputation(builder.Build(dot));

    if (manual_fusion) {
      auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(
          ArraySlice<HloInstruction*>({sub, add2}, 0, 2)));
      computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 0));
      computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 1));
      CHECK_NE(
          computation->CreateFusionInstruction(
              {tuple, sub, add2, broadcast}, HloInstruction::FusionKind::kLoop),
          nullptr);
    }

    Literal input;
    input.PopulateWithValue<float>(2.5f, {size, size});
    auto p1 = TransferToDevice(input);
    auto p0 = TransferToDevice(*Literal::CreateR0<float>(-9.0f));

    Literal expect;
    expect.PopulateWithValue<float>(size * 1.5f * 3.5f, {size, size});
    auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});
    LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);
  }

  void RunTest1D(bool manual_fusion, int size) {
    auto builder = HloComputation::Builder(TestName());
    auto hlo_module = CreateNewModule();

    const Shape elem_shape_F32 = ShapeUtil::MakeShape(F32, {size});
    const Shape elem_shape_U8 = ShapeUtil::MakeShape(F64, {size});
    auto param0 = builder.AddInstruction(
        HloInstruction::CreateParameter(0, elem_shape_F32, "0"));
    auto param1 = builder.AddInstruction(
        HloInstruction::CreateParameter(1, elem_shape_U8, "1"));

    HloInstruction* param0_U8 = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_U8, param0));
    HloInstruction* param1_F32 = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_F32, param1));
    HloInstruction* add = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape_F32, HloOpcode::kAdd, param0, param1_F32));
    HloInstruction* sub_U8 =
        builder.AddInstruction(HloInstruction::CreateBinary(
            elem_shape_U8, HloOpcode::kSubtract, param0_U8, param1));
    HloInstruction* sub = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_F32, sub_U8));

    HloInstruction* reshape =
        builder.AddInstruction(HloInstruction::CreateReshape(
            ShapeUtil::MakeShape(F32, {size, 1}), add));
    HloInstruction* dot = builder.AddInstruction(HloInstruction::CreateBinary(
        ShapeUtil::MakeShape(F32, {}), HloOpcode::kDot, sub, reshape));
    auto computation = hlo_module->AddEntryComputation(builder.Build(dot));

    if (manual_fusion) {
      auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(
          ArraySlice<HloInstruction*>({sub_U8, add}, 0, 2)));

      computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape_U8, tuple, 0));
      computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape_F32, tuple, 1));
      CHECK_NE(computation->CreateFusionInstruction(
                   {tuple, sub_U8, add, param0_U8, param1_F32},
                   HloInstruction::FusionKind::kLoop),
               nullptr);
    }

    Literal input0, input1;
    input0.PopulateWithValue<float>(2.5f, {size});
    input1.PopulateWithValue<double>(1, {size});
    auto p0 = TransferToDevice(input0);
    auto p1 = TransferToDevice(input1);

    Literal expect = *Literal::CreateR0<float>(size * 1.5f * 3.5f);
    auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});
    LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);
  }
};

XLA_TEST_F(MultiOutputFusionTest, 2DNofusion) { RunTest2D(false, 5); }
XLA_TEST_F(MultiOutputFusionTest, 2DFusion) { RunTest2D(true, 5); }
XLA_TEST_F(MultiOutputFusionTest, 2DFusionSize129) { RunTest2D(true, 129); }
XLA_TEST_F(MultiOutputFusionTest, DiffentTypesNoFusion) { RunTest1D(false, 8); }
XLA_TEST_F(MultiOutputFusionTest, DiffentTypesFusion) { RunTest1D(true, 8); }

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }

  return RUN_ALL_TESTS();
}
<commit_msg>Fix multioutput fusion test case.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <math.h>
#include <algorithm>
#include <memory>
#include <new>
#include <utility>

#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"

using tensorflow::gtl::ArraySlice;

namespace xla {
namespace {

class MultiOutputFusionTest : public HloTestBase {
 public:
  ErrorSpec error_spec_{0.0001, 1e-2};

 protected:
  MultiOutputFusionTest() {}
  void RunTest2D(bool manual_fusion, int64 size) {
    auto builder = HloComputation::Builder(TestName());
    auto hlo_module = CreateNewModule();

    const Shape elem_shape0 = ShapeUtil::MakeShape(F32, {});
    const Shape elem_shape2 = ShapeUtil::MakeShape(F32, {size, size});

    auto const0 = builder.AddInstruction(
        HloInstruction::CreateConstant(Literal::CreateR0<float>(8.0f)));
    auto param0 = builder.AddInstruction(
        HloInstruction::CreateParameter(0, elem_shape0, "0"));

    auto add1 = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape0, HloOpcode::kAdd, param0, const0));

    HloInstruction* broadcast = builder.AddInstruction(
        HloInstruction::CreateBroadcast(elem_shape2, add1, {0, 1}));

    auto param1 = builder.AddInstruction(
        HloInstruction::CreateParameter(1, elem_shape2, "1"));

    HloInstruction* add2 = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape2, HloOpcode::kAdd, broadcast, param1));
    HloInstruction* sub = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape2, HloOpcode::kSubtract, param1, broadcast));
    HloInstruction* dot = builder.AddInstruction(
        HloInstruction::CreateBinary(elem_shape2, HloOpcode::kDot, sub, add2));
    auto computation = hlo_module->AddEntryComputation(builder.Build(dot));

    if (manual_fusion) {
      auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(
          ArraySlice<HloInstruction*>({sub, add2}, 0, 2)));
      auto gte0 = computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 0));
      auto gte1 = computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 1));
      TF_CHECK_OK(dot->ReplaceOperandWith(0, gte0));
      TF_CHECK_OK(dot->ReplaceOperandWith(1, gte1));

      CHECK_NE(
          computation->CreateFusionInstruction(
              {tuple, sub, add2, broadcast}, HloInstruction::FusionKind::kLoop),
          nullptr);
    }

    Literal input;
    input.PopulateWithValue<float>(2.5f, {size, size});
    auto p1 = TransferToDevice(input);
    auto p0 = TransferToDevice(*Literal::CreateR0<float>(-9.0f));

    Literal expect;
    expect.PopulateWithValue<float>(size * 1.5f * 3.5f, {size, size});
    auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});
    LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);
  }

  void RunTest1D(bool manual_fusion, int size) {
    auto builder = HloComputation::Builder(TestName());
    auto hlo_module = CreateNewModule();

    const Shape elem_shape_F32 = ShapeUtil::MakeShape(F32, {size});
    const Shape elem_shape_U8 = ShapeUtil::MakeShape(F64, {size});
    auto param0 = builder.AddInstruction(
        HloInstruction::CreateParameter(0, elem_shape_F32, "0"));
    auto param1 = builder.AddInstruction(
        HloInstruction::CreateParameter(1, elem_shape_U8, "1"));

    HloInstruction* param0_U8 = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_U8, param0));
    HloInstruction* param1_F32 = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_F32, param1));
    HloInstruction* add = builder.AddInstruction(HloInstruction::CreateBinary(
        elem_shape_F32, HloOpcode::kAdd, param0, param1_F32));
    HloInstruction* sub_U8 =
        builder.AddInstruction(HloInstruction::CreateBinary(
            elem_shape_U8, HloOpcode::kSubtract, param0_U8, param1));
    HloInstruction* sub = builder.AddInstruction(
        HloInstruction::CreateConvert(elem_shape_F32, sub_U8));

    HloInstruction* reshape =
        builder.AddInstruction(HloInstruction::CreateReshape(
            ShapeUtil::MakeShape(F32, {size, 1}), add));
    HloInstruction* dot = builder.AddInstruction(HloInstruction::CreateBinary(
        ShapeUtil::MakeShape(F32, {}), HloOpcode::kDot, sub, reshape));
    auto computation = hlo_module->AddEntryComputation(builder.Build(dot));

    if (manual_fusion) {
      auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(
          ArraySlice<HloInstruction*>({sub_U8, add}, 0, 2)));

      auto gte0 = computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape_U8, tuple, 0));
      auto gte1 = computation->AddInstruction(
          HloInstruction::CreateGetTupleElement(elem_shape_F32, tuple, 1));
      TF_CHECK_OK(sub->ReplaceOperandWith(0, gte0));
      TF_CHECK_OK(reshape->ReplaceOperandWith(0, gte1));

      CHECK_NE(computation->CreateFusionInstruction(
                   {tuple, sub_U8, add, param0_U8, param1_F32},
                   HloInstruction::FusionKind::kLoop),
               nullptr);
    }

    Literal input0, input1;
    input0.PopulateWithValue<float>(2.5f, {size});
    input1.PopulateWithValue<double>(1, {size});
    auto p0 = TransferToDevice(input0);
    auto p1 = TransferToDevice(input1);

    Literal expect = *Literal::CreateR0<float>(size * 1.5f * 3.5f);
    auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});
    LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);
  }
};

XLA_TEST_F(MultiOutputFusionTest, 2DNofusion) { RunTest2D(false, 5); }
XLA_TEST_F(MultiOutputFusionTest, 2DFusion) { RunTest2D(true, 5); }
XLA_TEST_F(MultiOutputFusionTest, 2DFusionSize129) { RunTest2D(true, 129); }
XLA_TEST_F(MultiOutputFusionTest, DiffentTypesNoFusion) { RunTest1D(false, 8); }
XLA_TEST_F(MultiOutputFusionTest, DiffentTypesFusion) { RunTest1D(true, 8); }

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>//
// Copyright Renga Software LLC, 2016. All rights reserved.
//
// Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// Renga Software LLC  DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//

#include "stdafx.h"
#include "PropertyViewBuilder.h"
#include "GuidUtils.h"

#include <Renga/QuantityIds.h>

PropertyViewBuilder::PropertyViewBuilder(PropertyManagers* pPropertyManagers,
                                         Renga::IApplicationPtr pApplication,
                                         Renga::IModelObjectPtr pModelObject) :
  m_pApplication(pApplication),
  m_pPropertyManagers(pPropertyManagers),
  m_pModelObject(pModelObject)
{
}

void PropertyViewBuilder::createIntegratedParameters(PropertyList& propertyList)
{
  auto& mngr = m_pPropertyManagers->m_default;

  mngr.addValue(propertyList, QApplication::translate("me_mo", "name"), QString::fromWCharArray(m_pModelObject->GetName()));

  Renga::ILevelObjectPtr pLevelObject;
  m_pModelObject->QueryInterface(&pLevelObject);
  if (pLevelObject)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "offset"), pLevelObject->GetOffset());

  Renga::IObjectWithMarkPtr pObjectWithMark;
  m_pModelObject->QueryInterface(&pObjectWithMark);
  if (pObjectWithMark)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "mark"), QString::fromWCharArray(pObjectWithMark->GetMark()));

  Renga::IObjectWithMaterialPtr pObjectWithMaterial;
  m_pModelObject->QueryInterface(&pObjectWithMaterial);
  if (pObjectWithMaterial)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "material"), getMaterialName(pObjectWithMaterial->GetMaterialId()));

  Renga::IObjectWithLayeredMaterialPtr pObjectWithLayeredMaterial;
  m_pModelObject->QueryInterface(&pObjectWithLayeredMaterial);
  if (pObjectWithLayeredMaterial)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "material"), getLayeredMaterialName(pObjectWithLayeredMaterial->GetLayeredMaterialId()));
}

void PropertyViewBuilder::createParameters(PropertyList& propertyList)
{
  // block signals before filling properties
  auto& mngr = m_pPropertyManagers->m_parameters;
  mngr.blockSignals(true);

  auto pParameters = m_pModelObject->GetParameters();
  auto pIds = pParameters->GetIds();
  for (int i = 0; i < pIds->Count; ++i)
  {
    const auto id = pIds->Get(i);

    auto pParameter = pParameters->Get(id);
    auto pDefinition = pParameter->Definition;

    QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());

    switch (pDefinition->GetParameterType())
    {
    case Renga::ParameterType::ParameterType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      break;
    case Renga::ParameterType::ParameterType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      break;
    }

    QtProperty* pQtProperty(nullptr);
    if (pParameter->HasValue())
    {
      switch (pParameter->GetValueType())
      {
      case Renga::ParameterValueType::ParameterValueType_Bool:
        pQtProperty = mngr.addValue(propertyList, name, pParameter->GetBoolValue());
        break;
      case Renga::ParameterValueType::ParameterValueType_Int:
        pQtProperty = mngr.addValue(propertyList, name, pParameter->GetIntValue());
        break;
      case Renga::ParameterValueType::ParameterValueType_Double:
        pQtProperty = mngr.addValue(propertyList, name, pParameter->GetDoubleValue());
        break;
      case Renga::ParameterValueType::ParameterValueType_String:
        pQtProperty = mngr.addValue(propertyList, name, QString::fromWCharArray(pParameter->GetStringValue()));
        break;
      }
    }
    else
    {
      pQtProperty = mngr.addValue(propertyList, name, "");
      pQtProperty->setEnabled(false);
    }

    if (pQtProperty)
    {
      pQtProperty->setModified(true);

      const auto parameterIdString = QString::fromStdString((GuidToString(id)));
      pQtProperty->setData(parameterIdString);
    }
  }

  // unblock signals
  mngr.blockSignals(false);
}

void PropertyViewBuilder::createQuantities(PropertyList& propertyList)
{
  using namespace Renga;

  auto pQuantities = m_pModelObject->GetQuantities();

  PropertyList result;

  auto& mngr = m_pPropertyManagers->m_default;

  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallWidth"), pQuantities->Get(QuantityIds::OverallWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallHeight"), pQuantities->Get(QuantityIds::OverallHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallLength"), pQuantities->Get(QuantityIds::OverallLength));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "thickness"), pQuantities->Get(QuantityIds::NominalThickness));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "length"), pQuantities->Get(QuantityIds::NominalLength));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "width"), pQuantities->Get(QuantityIds::NominalWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "height"), pQuantities->Get(QuantityIds::NominalHeight));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "perimeter"), pQuantities->Get(QuantityIds::Perimeter));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "volume"), pQuantities->Get(QuantityIds::Volume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netVolume"), pQuantities->Get(QuantityIds::NetVolume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "mass"), pQuantities->Get(QuantityIds::NetMass));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionOverallWidth"), pQuantities->Get(QuantityIds::CrossSectionOverallWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionOverallHeight"), pQuantities->Get(QuantityIds::CrossSectionOverallHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionArea"), pQuantities->Get(QuantityIds::CrossSectionArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceArea"), pQuantities->Get(QuantityIds::InnerSurfaceArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceInternalArea"), pQuantities->Get(QuantityIds::InnerSurfaceInternalArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceExternalArea"), pQuantities->Get(QuantityIds::InnerSurfaceExternalArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "outerSurfaceArea"), pQuantities->Get(QuantityIds::OuterSurfaceArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "area"), pQuantities->Get(QuantityIds::Area));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netArea"), pQuantities->Get(QuantityIds::NetArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netFloorArea"), pQuantities->Get(QuantityIds::NetFloorArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netFootprintArea"), pQuantities->Get(QuantityIds::NetFootprintArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netSideArea"), pQuantities->Get(QuantityIds::NetSideArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "totalSurfaceArea"), pQuantities->Get(QuantityIds::TotalSurfaceArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossVolume"), pQuantities->Get(Renga::QuantityIds::GrossVolume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossFloorArea"), pQuantities->Get(Renga::QuantityIds::GrossFloorArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossPerimeter"), pQuantities->Get(Renga::QuantityIds::GrossPerimeter));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "numberOfRiser"), pQuantities->Get(QuantityIds::NumberOfRiser));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "numberOfTreads"), pQuantities->Get(QuantityIds::NumberOfTreads));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "riserHeight"), pQuantities->Get(QuantityIds::RiserHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "treadLength"), pQuantities->Get(QuantityIds::TreadLength));

  mngr.addValue(propertyList, QApplication::translate("me_reinforcement", "totalRebarLength"), pQuantities->Get(QuantityIds::TotalRebarLength));
  mngr.addValue(propertyList, QApplication::translate("me_reinforcement", "totalRebarMass"), pQuantities->Get(QuantityIds::TotalRebarMass));
}

PropertyList PropertyViewBuilder::createProperties()
{
  PropertyList pResult;

  auto pProject = m_pApplication->GetProject();
  auto pPropertyManager = pProject->GetPropertyManager();

  // block signals before filling properties
  auto& mngr = m_pPropertyManagers->m_properties;
  mngr.blockSignals(true);

  // check all attributes
  for (int i = 0; i < pPropertyManager->GetPropertyCount(); ++i)
  {
    auto propertyId = pPropertyManager->GetPropertyId(i);

    // check if objectType has attribute
    if (!pPropertyManager->IsPropertyAssignedToType(propertyId, m_pModelObject->GetObjectType()))
      continue;

    auto pProperties = m_pModelObject->GetProperties();
    auto pProperty = pProperties->Get(propertyId);

    if (!pProperty)
      continue;

    auto propertyDescription = pPropertyManager->GetPropertyDescription(propertyId);
    if (propertyDescription.Type == Renga::PropertyType::PropertyType_Undefined)
      continue;

    const auto attributeName = QString::fromWCharArray(propertyDescription.Name);
    const auto propertyIdString = QString::fromStdString((GuidToString(propertyId)));

    QtProperty* pQtProperty(nullptr);
    switch (propertyDescription.Type)
    {
    case Renga::PropertyType::PropertyType_Double:
      pQtProperty = mngr.addValue(pResult, attributeName, pProperty->GetDoubleValue());
      break;
    case Renga::PropertyType::PropertyType_String:
      pQtProperty = mngr.addValue(pResult, attributeName, QString::fromWCharArray(pProperty->GetStringValue()));
      break;
    default:
      assert(false);
    }
    pQtProperty->setModified(true);
    pQtProperty->setData(propertyIdString);
  }

  // unblock signals
  mngr.blockSignals(false);

  return pResult;
}

QString PropertyViewBuilder::getMaterialName(const int& materialId)
{
  auto pProject = m_pApplication->GetProject();
  auto pMaterialManager = pProject->GetMaterialManager();
  auto pMaterial = pMaterialManager->GetMaterial(materialId);
  if (!pMaterial)
    return QString();

  return QString::fromWCharArray(pMaterial->GetName());
}

QString PropertyViewBuilder::getLayeredMaterialName(const int& layeredMaterialId)
{
  auto pProject = m_pApplication->GetProject();
  auto pLayeredMaterialManager = pProject->GetLayeredMaterialManager();
  auto pLayeredMaterial = pLayeredMaterialManager->GetLayeredMaterial(layeredMaterialId);
  if (!pLayeredMaterial)
    return QString();

  return QString::fromWCharArray(pLayeredMaterial->GetName());
}
<commit_msg>Fix for model object parameters with no value<commit_after>//
// Copyright Renga Software LLC, 2016. All rights reserved.
//
// Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// Renga Software LLC  DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//

#include "stdafx.h"
#include "PropertyViewBuilder.h"
#include "GuidUtils.h"

#include <Renga/QuantityIds.h>

PropertyViewBuilder::PropertyViewBuilder(PropertyManagers* pPropertyManagers,
                                         Renga::IApplicationPtr pApplication,
                                         Renga::IModelObjectPtr pModelObject) :
  m_pApplication(pApplication),
  m_pPropertyManagers(pPropertyManagers),
  m_pModelObject(pModelObject)
{
}

void PropertyViewBuilder::createIntegratedParameters(PropertyList& propertyList)
{
  auto& mngr = m_pPropertyManagers->m_default;

  mngr.addValue(propertyList, QApplication::translate("me_mo", "name"), QString::fromWCharArray(m_pModelObject->GetName()));

  Renga::ILevelObjectPtr pLevelObject;
  m_pModelObject->QueryInterface(&pLevelObject);
  if (pLevelObject)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "offset"), pLevelObject->GetOffset());

  Renga::IObjectWithMarkPtr pObjectWithMark;
  m_pModelObject->QueryInterface(&pObjectWithMark);
  if (pObjectWithMark)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "mark"), QString::fromWCharArray(pObjectWithMark->GetMark()));

  Renga::IObjectWithMaterialPtr pObjectWithMaterial;
  m_pModelObject->QueryInterface(&pObjectWithMaterial);
  if (pObjectWithMaterial)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "material"), getMaterialName(pObjectWithMaterial->GetMaterialId()));

  Renga::IObjectWithLayeredMaterialPtr pObjectWithLayeredMaterial;
  m_pModelObject->QueryInterface(&pObjectWithLayeredMaterial);
  if (pObjectWithLayeredMaterial)
    mngr.addValue(propertyList, QApplication::translate("me_mo", "material"), getLayeredMaterialName(pObjectWithLayeredMaterial->GetLayeredMaterialId()));
}

void PropertyViewBuilder::createParameters(PropertyList& propertyList)
{
  // block signals before filling properties
  auto& mngr = m_pPropertyManagers->m_parameters;
  mngr.blockSignals(true);

  auto pParameters = m_pModelObject->GetParameters();
  auto pIds = pParameters->GetIds();
  for (int i = 0; i < pIds->Count; ++i)
  {
    const auto id = pIds->Get(i);

    auto pParameter = pParameters->Get(id);
    auto pDefinition = pParameter->Definition;

    QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());

    switch (pDefinition->GetParameterType())
    {
    case Renga::ParameterType::ParameterType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      break;
    case Renga::ParameterType::ParameterType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      break;
    }

    QtProperty* pQtProperty(nullptr);
    switch (pParameter->GetValueType())
    {
    case Renga::ParameterValueType::ParameterValueType_Bool:
      pQtProperty = mngr.addValue(propertyList, name, pParameter->GetBoolValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_Int:
      pQtProperty = mngr.addValue(propertyList, name, pParameter->GetIntValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_Double:
      pQtProperty = mngr.addValue(propertyList, name, pParameter->GetDoubleValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_String:
      pQtProperty = mngr.addValue(propertyList, name, QString::fromWCharArray(pParameter->GetStringValue()));
      break;
    }

    if (pQtProperty)
    {
      if (!pParameter->HasValue())
        pQtProperty->setEnabled(false);

      pQtProperty->setModified(true);

      const auto parameterIdString = QString::fromStdString((GuidToString(id)));
      pQtProperty->setData(parameterIdString);
    }
  }

  // unblock signals
  mngr.blockSignals(false);
}

void PropertyViewBuilder::createQuantities(PropertyList& propertyList)
{
  using namespace Renga;

  auto pQuantities = m_pModelObject->GetQuantities();

  PropertyList result;

  auto& mngr = m_pPropertyManagers->m_default;

  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallWidth"), pQuantities->Get(QuantityIds::OverallWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallHeight"), pQuantities->Get(QuantityIds::OverallHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "overallLength"), pQuantities->Get(QuantityIds::OverallLength));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "thickness"), pQuantities->Get(QuantityIds::NominalThickness));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "length"), pQuantities->Get(QuantityIds::NominalLength));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "width"), pQuantities->Get(QuantityIds::NominalWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "height"), pQuantities->Get(QuantityIds::NominalHeight));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "perimeter"), pQuantities->Get(QuantityIds::Perimeter));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "volume"), pQuantities->Get(QuantityIds::Volume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netVolume"), pQuantities->Get(QuantityIds::NetVolume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "mass"), pQuantities->Get(QuantityIds::NetMass));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionOverallWidth"), pQuantities->Get(QuantityIds::CrossSectionOverallWidth));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionOverallHeight"), pQuantities->Get(QuantityIds::CrossSectionOverallHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "crossSectionArea"), pQuantities->Get(QuantityIds::CrossSectionArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceArea"), pQuantities->Get(QuantityIds::InnerSurfaceArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceInternalArea"), pQuantities->Get(QuantityIds::InnerSurfaceInternalArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "innerSurfaceExternalArea"), pQuantities->Get(QuantityIds::InnerSurfaceExternalArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "outerSurfaceArea"), pQuantities->Get(QuantityIds::OuterSurfaceArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "area"), pQuantities->Get(QuantityIds::Area));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netArea"), pQuantities->Get(QuantityIds::NetArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netFloorArea"), pQuantities->Get(QuantityIds::NetFloorArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netFootprintArea"), pQuantities->Get(QuantityIds::NetFootprintArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "netSideArea"), pQuantities->Get(QuantityIds::NetSideArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "totalSurfaceArea"), pQuantities->Get(QuantityIds::TotalSurfaceArea));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossVolume"), pQuantities->Get(Renga::QuantityIds::GrossVolume));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossFloorArea"), pQuantities->Get(Renga::QuantityIds::GrossFloorArea));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "grossPerimeter"), pQuantities->Get(Renga::QuantityIds::GrossPerimeter));

  mngr.addValue(propertyList, QApplication::translate("me_mo", "numberOfRiser"), pQuantities->Get(QuantityIds::NumberOfRiser));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "numberOfTreads"), pQuantities->Get(QuantityIds::NumberOfTreads));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "riserHeight"), pQuantities->Get(QuantityIds::RiserHeight));
  mngr.addValue(propertyList, QApplication::translate("me_mo", "treadLength"), pQuantities->Get(QuantityIds::TreadLength));

  mngr.addValue(propertyList, QApplication::translate("me_reinforcement", "totalRebarLength"), pQuantities->Get(QuantityIds::TotalRebarLength));
  mngr.addValue(propertyList, QApplication::translate("me_reinforcement", "totalRebarMass"), pQuantities->Get(QuantityIds::TotalRebarMass));
}

PropertyList PropertyViewBuilder::createProperties()
{
  PropertyList pResult;

  auto pProject = m_pApplication->GetProject();
  auto pPropertyManager = pProject->GetPropertyManager();

  // block signals before filling properties
  auto& mngr = m_pPropertyManagers->m_properties;
  mngr.blockSignals(true);

  // check all attributes
  for (int i = 0; i < pPropertyManager->GetPropertyCount(); ++i)
  {
    auto propertyId = pPropertyManager->GetPropertyId(i);

    // check if objectType has attribute
    if (!pPropertyManager->IsPropertyAssignedToType(propertyId, m_pModelObject->GetObjectType()))
      continue;

    auto pProperties = m_pModelObject->GetProperties();
    auto pProperty = pProperties->Get(propertyId);

    if (!pProperty)
      continue;

    auto propertyDescription = pPropertyManager->GetPropertyDescription(propertyId);
    if (propertyDescription.Type == Renga::PropertyType::PropertyType_Undefined)
      continue;

    const auto attributeName = QString::fromWCharArray(propertyDescription.Name);
    const auto propertyIdString = QString::fromStdString((GuidToString(propertyId)));

    QtProperty* pQtProperty(nullptr);
    switch (propertyDescription.Type)
    {
    case Renga::PropertyType::PropertyType_Double:
      pQtProperty = mngr.addValue(pResult, attributeName, pProperty->GetDoubleValue());
      break;
    case Renga::PropertyType::PropertyType_String:
      pQtProperty = mngr.addValue(pResult, attributeName, QString::fromWCharArray(pProperty->GetStringValue()));
      break;
    default:
      assert(false);
    }
    pQtProperty->setModified(true);
    pQtProperty->setData(propertyIdString);
  }

  // unblock signals
  mngr.blockSignals(false);

  return pResult;
}

QString PropertyViewBuilder::getMaterialName(const int& materialId)
{
  auto pProject = m_pApplication->GetProject();
  auto pMaterialManager = pProject->GetMaterialManager();
  auto pMaterial = pMaterialManager->GetMaterial(materialId);
  if (!pMaterial)
    return QString();

  return QString::fromWCharArray(pMaterial->GetName());
}

QString PropertyViewBuilder::getLayeredMaterialName(const int& layeredMaterialId)
{
  auto pProject = m_pApplication->GetProject();
  auto pLayeredMaterialManager = pProject->GetLayeredMaterialManager();
  auto pLayeredMaterial = pLayeredMaterialManager->GetLayeredMaterial(layeredMaterialId);
  if (!pLayeredMaterial)
    return QString();

  return QString::fromWCharArray(pLayeredMaterial->GetName());
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

// AliFlowEventCuts:
// An event cut class for the flow framework
//
// origin: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)

#include <limits.h>
#include <float.h>
#include "TMath.h"
#include "TNamed.h"
#include "AliVVertex.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliCentrality.h"
#include "AliESDVZERO.h"
#include "AliMultiplicity.h"
#include "AliMCEvent.h"
#include "AliFlowEventCuts.h"
#include "AliFlowTrackCuts.h"
#include "AliTriggerAnalysis.h"

ClassImp(AliFlowEventCuts)

//-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts():
  TNamed(),
  fCutNumberOfTracks(kFALSE),
  fNumberOfTracksMax(INT_MAX),
  fNumberOfTracksMin(INT_MIN),
  fCutRefMult(kFALSE),
  fRefMultMethod(kTPConly),
  fRefMultMax(INT_MAX),
  fRefMultMin(INT_MIN),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(kFALSE),
  fPrimaryVertexXmax(INT_MAX),
  fPrimaryVertexXmin(INT_MIN),
  fCutPrimaryVertexY(kFALSE),
  fPrimaryVertexYmax(INT_MAX),
  fPrimaryVertexYmin(INT_MIN),
  fCutPrimaryVertexZ(kFALSE),
  fPrimaryVertexZmax(INT_MAX),
  fPrimaryVertexZmin(INT_MIN),
  fCutNContributors(kFALSE),
  fNContributorsMax(INT_MAX),
  fNContributorsMin(INT_MIN),
  fCutMeanPt(kFALSE),
  fMeanPtMax(-DBL_MAX),
  fMeanPtMin(DBL_MAX),
  fCutSPDvertexerAnomaly(kFALSE),
  fCutCentralityPercentile(kFALSE),
  fCentralityPercentileMethod(kTPConly),
  fCentralityPercentileMax(100.),
  fCentralityPercentileMin(0.),
  fCutZDCtiming(kFALSE),
  fTrigAna()
{
  //constructor
}

//-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts(const char* name, const char* title):
  TNamed(name, title),
  fCutNumberOfTracks(kFALSE),
  fNumberOfTracksMax(INT_MAX),
  fNumberOfTracksMin(INT_MIN),
  fCutRefMult(kFALSE),
  fRefMultMethod(kTPConly),
  fRefMultMax(INT_MAX),
  fRefMultMin(INT_MIN),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(kFALSE),
  fPrimaryVertexXmax(INT_MAX),
  fPrimaryVertexXmin(INT_MIN),
  fCutPrimaryVertexY(kFALSE),
  fPrimaryVertexYmax(INT_MAX),
  fPrimaryVertexYmin(INT_MIN),
  fCutPrimaryVertexZ(kFALSE),
  fPrimaryVertexZmax(INT_MAX),
  fPrimaryVertexZmin(INT_MIN),
  fCutNContributors(kFALSE),
  fNContributorsMax(INT_MAX),
  fNContributorsMin(INT_MIN),
  fCutMeanPt(kFALSE),
  fMeanPtMax(-DBL_MAX),
  fMeanPtMin(DBL_MAX),
  fCutSPDvertexerAnomaly(kTRUE),
  fCutCentralityPercentile(kFALSE),
  fCentralityPercentileMethod(kTPConly),
  fCentralityPercentileMax(100.),
  fCentralityPercentileMin(0.),
  fCutZDCtiming(kFALSE),
  fTrigAna()
{
  //constructor
}

////-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts(const AliFlowEventCuts& that):
  TNamed(that),
  fCutNumberOfTracks(that.fCutNumberOfTracks),
  fNumberOfTracksMax(that.fNumberOfTracksMax),
  fNumberOfTracksMin(that.fNumberOfTracksMin),
  fCutRefMult(that.fCutRefMult),
  fRefMultMethod(that.fRefMultMethod),
  fRefMultMax(that.fRefMultMax),
  fRefMultMin(that.fRefMultMin),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(that.fCutPrimaryVertexX),
  fPrimaryVertexXmax(that.fPrimaryVertexXmax),
  fPrimaryVertexXmin(that.fPrimaryVertexXmin),
  fCutPrimaryVertexY(that.fCutPrimaryVertexX),
  fPrimaryVertexYmax(that.fPrimaryVertexYmax),
  fPrimaryVertexYmin(that.fPrimaryVertexYmin),
  fCutPrimaryVertexZ(that.fCutPrimaryVertexX),
  fPrimaryVertexZmax(that.fPrimaryVertexZmax),
  fPrimaryVertexZmin(that.fPrimaryVertexZmin),
  fCutNContributors(that.fCutNContributors),
  fNContributorsMax(that.fNContributorsMax),
  fNContributorsMin(that.fNContributorsMin),
  fCutMeanPt(that.fCutMeanPt),
  fMeanPtMax(that.fMeanPtMax),
  fMeanPtMin(that.fMeanPtMin),
  fCutSPDvertexerAnomaly(that.fCutSPDvertexerAnomaly),
  fCutCentralityPercentile(that.fCutCentralityPercentile),
  fCentralityPercentileMethod(that.fCentralityPercentileMethod),
  fCentralityPercentileMax(that.fCentralityPercentileMax),
  fCentralityPercentileMin(that.fCentralityPercentileMin),
  fCutZDCtiming(that.fCutZDCtiming),
  fTrigAna()
{
  //copy constructor
  if (that.fRefMultCuts)
    fRefMultCuts = new AliFlowTrackCuts(*(that.fRefMultCuts));
  if (that.fMeanPtCuts)
    fMeanPtCuts = new AliFlowTrackCuts(*(that.fMeanPtCuts));
}

////-----------------------------------------------------------------------
AliFlowEventCuts::~AliFlowEventCuts()
{
  //dtor
  delete fMeanPtCuts;
  delete fRefMultCuts;
}

////-----------------------------------------------------------------------
AliFlowEventCuts& AliFlowEventCuts::operator=(const AliFlowEventCuts& that)
{
  //assignment
  fCutNumberOfTracks=that.fCutNumberOfTracks;
  fNumberOfTracksMax=that.fNumberOfTracksMax;
  fNumberOfTracksMin=that.fNumberOfTracksMin;
  fCutRefMult=that.fCutRefMult;
  fRefMultMethod=that.fRefMultMethod;
  fRefMultMax=that.fRefMultMax;
  fRefMultMin=that.fRefMultMin;
  if (that.fRefMultCuts) *fRefMultCuts=*(that.fRefMultCuts);
  if (that.fMeanPtCuts) *fMeanPtCuts=*(that.fMeanPtCuts);
  fCutPrimaryVertexX=that.fCutPrimaryVertexX;
  fPrimaryVertexXmin=that.fPrimaryVertexXmin;
  fPrimaryVertexXmax=that.fPrimaryVertexXmax;
  fPrimaryVertexYmin=that.fPrimaryVertexYmin;
  fPrimaryVertexYmax=that.fPrimaryVertexYmax;
  fPrimaryVertexZmin=that.fPrimaryVertexZmin;
  fPrimaryVertexZmax=that.fPrimaryVertexZmax;
  fCutNContributors=that.fCutNContributors;
  fNContributorsMax=that.fNContributorsMax;
  fNContributorsMin=that.fNContributorsMin;
  fCutMeanPt=that.fCutMeanPt;
  fMeanPtMax=that.fMeanPtMax;
  fMeanPtMin=that.fMeanPtMin;
  fCutSPDvertexerAnomaly=that.fCutSPDvertexerAnomaly;
  fCutCentralityPercentile=that.fCutCentralityPercentile;
  fCentralityPercentileMethod=that.fCentralityPercentileMethod;
  fCentralityPercentileMax=that.fCentralityPercentileMax;
  fCentralityPercentileMin=that.fCentralityPercentileMin;
  return *this;
}

//-----------------------------------------------------------------------
Bool_t AliFlowEventCuts::IsSelected(TObject* obj)
{
  //check cuts
  AliVEvent* vevent = dynamic_cast<AliVEvent*>(obj);
  if (vevent) return PassesCuts(vevent);
  return kFALSE;  //when passed wrong type of object
}
//-----------------------------------------------------------------------
Bool_t AliFlowEventCuts::PassesCuts(AliVEvent *event)
{
  ///check if event passes cuts
  AliESDEvent* esdevent = dynamic_cast<AliESDEvent*>(event);
  if (fCutCentralityPercentile&&esdevent)
  {
    AliCentrality* centr = esdevent->GetCentrality();
    if (!centr->IsEventInCentralityClass( fCentralityPercentileMin,
                                          fCentralityPercentileMax,
                                          CentrMethName(fCentralityPercentileMethod) ))
    {
      return kFALSE;
    }
  }
  if (fCutSPDvertexerAnomaly&&esdevent)
  {
    const AliESDVertex* sdpvertex = esdevent->GetPrimaryVertexSPD();
    if (sdpvertex->GetNContributors()<1) return kFALSE;
    if (sdpvertex->GetDispersion()>0.04) return kFALSE;
    if (sdpvertex->GetZRes()>0.25) return kFALSE;
    const AliESDVertex* tpcvertex = esdevent->GetPrimaryVertexTPC();
    if (tpcvertex->GetNContributors()<1) return kFALSE;
    const AliMultiplicity* tracklets = esdevent->GetMultiplicity();
    if (tpcvertex->GetNContributors()<(-10.0+0.25*tracklets->GetNumberOfITSClusters(0)))
    {
      return kFALSE;
    }
  }
  if (fCutZDCtiming&&esdevent)
  {
    if (!fTrigAna.ZDCTimeTrigger(esdevent))
    {
      return kFALSE;
    }
  }
  if(fCutNumberOfTracks) {if ( event->GetNumberOfTracks() < fNumberOfTracksMin ||
                               event->GetNumberOfTracks() >= fNumberOfTracksMax ) return kFALSE;}
  if(fCutRefMult&&esdevent)
  {
    //reference multiplicity still to be defined
    Double_t refMult = RefMult(event);
    if (refMult < fRefMultMin || refMult >= fRefMultMax )
    {
      return kFALSE;
    }
  }
  const AliVVertex* pvtx=event->GetPrimaryVertex();
  Double_t pvtxx = pvtx->GetX();
  Double_t pvtxy = pvtx->GetY();
  Double_t pvtxz = pvtx->GetZ();
  Int_t ncontrib = pvtx->GetNContributors();
  if (fCutNContributors)
  {
    if (ncontrib < fNContributorsMin || ncontrib >= fNContributorsMax)
      return kFALSE;
  }
  if (fCutPrimaryVertexX)
  {
    if (pvtxx < fPrimaryVertexXmin || pvtxx >= fPrimaryVertexXmax)
      return kFALSE;
  }
  if (fCutPrimaryVertexY)
  {
    if (pvtxy < fPrimaryVertexYmin || pvtxy >= fPrimaryVertexYmax)
      return kFALSE;
  }
  if (fCutPrimaryVertexZ)
  {
    if (pvtxz < fPrimaryVertexZmin || pvtxz >= fPrimaryVertexZmax)
      return kFALSE;
  }
  if (fCutMeanPt)
  {
    Float_t meanpt=0.0;
    Int_t ntracks=event->GetNumberOfTracks();
    Int_t nselected=0;
    for (Int_t i=0; i<ntracks; i++)
    {
      AliVParticle* track = event->GetTrack(i);
      if (!track) continue;
      Bool_t pass=kTRUE;
      if (fMeanPtCuts) pass=fMeanPtCuts->IsSelected(track);
      if (pass)
      {
        meanpt += track->Pt();
        nselected++;
      }
    }
    meanpt=meanpt/nselected;
    if (meanpt<fMeanPtMin || meanpt >= fMeanPtMax) return kFALSE;
  }
  return kTRUE;
}

//-----------------------------------------------------------------------
const char* AliFlowEventCuts::CentrMethName(refMultMethod method) const
{
  //get the string for refmultmethod, for use with AliCentrality in
  //the cut on centrality percentile
  switch (method)
  {
    case kSPDtracklets:
      return "TKL";
    case kSPD1clusters:
      return "CL1";
    case kTPConly:
      return "TRK";
    case kV0:
      return "V0M";
    default:
      return "";
  }
}
//-----------------------------------------------------------------------
AliFlowEventCuts* AliFlowEventCuts::StandardCuts()
{
  //make a set of standard event cuts, caller becomes owner
  AliFlowEventCuts* cuts = new AliFlowEventCuts();
  return cuts;
}

//-----------------------------------------------------------------------
Int_t AliFlowEventCuts::RefMult(AliVEvent* event)
{
  //calculate the reference multiplicity, if all fails return 0
  AliESDVZERO* vzero = NULL;
  AliESDEvent* esdevent = dynamic_cast<AliESDEvent*>(event);

  if (fRefMultMethod==kTPConly && !fRefMultCuts)
  {
    fRefMultCuts = AliFlowTrackCuts::GetStandardTPCOnlyTrackCuts();
    fRefMultCuts->SetEtaRange(-0.8,0.8);
    fRefMultCuts->SetPtMin(0.15);
  }
  else if (fRefMultMethod==kSPDtracklets && !fRefMultCuts)
  {
    fRefMultCuts = new AliFlowTrackCuts("tracklet refmult cuts");
    fRefMultCuts->SetParamType(AliFlowTrackCuts::kESD_SPDtracklet);
    fRefMultCuts->SetEtaRange(-0.8,0.8);
  }
  else if (fRefMultMethod==kV0)
  {
    if (!esdevent) return 0;
    vzero=esdevent->GetVZEROData();
    if (!vzero) return 0;
    return TMath::Nint(vzero->GetMTotV0A()+vzero->GetMTotV0C());
  }
  else if (fRefMultMethod==kSPD1clusters)
  {
    if (!esdevent) return 0;
    const AliMultiplicity* mult = esdevent->GetMultiplicity();
    if (!mult) return 0;
    return mult->GetNumberOfITSClusters(1);
  }

  Int_t refmult=0;
  fRefMultCuts->SetEvent(event);
  for (Int_t i=0; i<fRefMultCuts->GetNumberOfInputObjects(); i++)
  {
    if (fRefMultCuts->IsSelected(fRefMultCuts->GetInputObject(i),i))
      refmult++;
  }
  return refmult;
}
<commit_msg>disable francesco's cut by default<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

// AliFlowEventCuts:
// An event cut class for the flow framework
//
// origin: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)

#include <limits.h>
#include <float.h>
#include "TMath.h"
#include "TNamed.h"
#include "AliVVertex.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliCentrality.h"
#include "AliESDVZERO.h"
#include "AliMultiplicity.h"
#include "AliMCEvent.h"
#include "AliFlowEventCuts.h"
#include "AliFlowTrackCuts.h"
#include "AliTriggerAnalysis.h"

ClassImp(AliFlowEventCuts)

//-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts():
  TNamed(),
  fCutNumberOfTracks(kFALSE),
  fNumberOfTracksMax(INT_MAX),
  fNumberOfTracksMin(INT_MIN),
  fCutRefMult(kFALSE),
  fRefMultMethod(kTPConly),
  fRefMultMax(INT_MAX),
  fRefMultMin(INT_MIN),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(kFALSE),
  fPrimaryVertexXmax(INT_MAX),
  fPrimaryVertexXmin(INT_MIN),
  fCutPrimaryVertexY(kFALSE),
  fPrimaryVertexYmax(INT_MAX),
  fPrimaryVertexYmin(INT_MIN),
  fCutPrimaryVertexZ(kFALSE),
  fPrimaryVertexZmax(INT_MAX),
  fPrimaryVertexZmin(INT_MIN),
  fCutNContributors(kFALSE),
  fNContributorsMax(INT_MAX),
  fNContributorsMin(INT_MIN),
  fCutMeanPt(kFALSE),
  fMeanPtMax(-DBL_MAX),
  fMeanPtMin(DBL_MAX),
  fCutSPDvertexerAnomaly(kFALSE),
  fCutCentralityPercentile(kFALSE),
  fCentralityPercentileMethod(kTPConly),
  fCentralityPercentileMax(100.),
  fCentralityPercentileMin(0.),
  fCutZDCtiming(kFALSE),
  fTrigAna()
{
  //constructor
}

//-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts(const char* name, const char* title):
  TNamed(name, title),
  fCutNumberOfTracks(kFALSE),
  fNumberOfTracksMax(INT_MAX),
  fNumberOfTracksMin(INT_MIN),
  fCutRefMult(kFALSE),
  fRefMultMethod(kTPConly),
  fRefMultMax(INT_MAX),
  fRefMultMin(INT_MIN),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(kFALSE),
  fPrimaryVertexXmax(INT_MAX),
  fPrimaryVertexXmin(INT_MIN),
  fCutPrimaryVertexY(kFALSE),
  fPrimaryVertexYmax(INT_MAX),
  fPrimaryVertexYmin(INT_MIN),
  fCutPrimaryVertexZ(kFALSE),
  fPrimaryVertexZmax(INT_MAX),
  fPrimaryVertexZmin(INT_MIN),
  fCutNContributors(kFALSE),
  fNContributorsMax(INT_MAX),
  fNContributorsMin(INT_MIN),
  fCutMeanPt(kFALSE),
  fMeanPtMax(-DBL_MAX),
  fMeanPtMin(DBL_MAX),
  fCutSPDvertexerAnomaly(kFALSE),
  fCutCentralityPercentile(kFALSE),
  fCentralityPercentileMethod(kTPConly),
  fCentralityPercentileMax(100.),
  fCentralityPercentileMin(0.),
  fCutZDCtiming(kFALSE),
  fTrigAna()
{
  //constructor
}

////-----------------------------------------------------------------------
AliFlowEventCuts::AliFlowEventCuts(const AliFlowEventCuts& that):
  TNamed(that),
  fCutNumberOfTracks(that.fCutNumberOfTracks),
  fNumberOfTracksMax(that.fNumberOfTracksMax),
  fNumberOfTracksMin(that.fNumberOfTracksMin),
  fCutRefMult(that.fCutRefMult),
  fRefMultMethod(that.fRefMultMethod),
  fRefMultMax(that.fRefMultMax),
  fRefMultMin(that.fRefMultMin),
  fRefMultCuts(NULL),
  fMeanPtCuts(NULL),
  fCutPrimaryVertexX(that.fCutPrimaryVertexX),
  fPrimaryVertexXmax(that.fPrimaryVertexXmax),
  fPrimaryVertexXmin(that.fPrimaryVertexXmin),
  fCutPrimaryVertexY(that.fCutPrimaryVertexX),
  fPrimaryVertexYmax(that.fPrimaryVertexYmax),
  fPrimaryVertexYmin(that.fPrimaryVertexYmin),
  fCutPrimaryVertexZ(that.fCutPrimaryVertexX),
  fPrimaryVertexZmax(that.fPrimaryVertexZmax),
  fPrimaryVertexZmin(that.fPrimaryVertexZmin),
  fCutNContributors(that.fCutNContributors),
  fNContributorsMax(that.fNContributorsMax),
  fNContributorsMin(that.fNContributorsMin),
  fCutMeanPt(that.fCutMeanPt),
  fMeanPtMax(that.fMeanPtMax),
  fMeanPtMin(that.fMeanPtMin),
  fCutSPDvertexerAnomaly(that.fCutSPDvertexerAnomaly),
  fCutCentralityPercentile(that.fCutCentralityPercentile),
  fCentralityPercentileMethod(that.fCentralityPercentileMethod),
  fCentralityPercentileMax(that.fCentralityPercentileMax),
  fCentralityPercentileMin(that.fCentralityPercentileMin),
  fCutZDCtiming(that.fCutZDCtiming),
  fTrigAna()
{
  //copy constructor
  if (that.fRefMultCuts)
    fRefMultCuts = new AliFlowTrackCuts(*(that.fRefMultCuts));
  if (that.fMeanPtCuts)
    fMeanPtCuts = new AliFlowTrackCuts(*(that.fMeanPtCuts));
}

////-----------------------------------------------------------------------
AliFlowEventCuts::~AliFlowEventCuts()
{
  //dtor
  delete fMeanPtCuts;
  delete fRefMultCuts;
}

////-----------------------------------------------------------------------
AliFlowEventCuts& AliFlowEventCuts::operator=(const AliFlowEventCuts& that)
{
  //assignment
  fCutNumberOfTracks=that.fCutNumberOfTracks;
  fNumberOfTracksMax=that.fNumberOfTracksMax;
  fNumberOfTracksMin=that.fNumberOfTracksMin;
  fCutRefMult=that.fCutRefMult;
  fRefMultMethod=that.fRefMultMethod;
  fRefMultMax=that.fRefMultMax;
  fRefMultMin=that.fRefMultMin;
  if (that.fRefMultCuts) *fRefMultCuts=*(that.fRefMultCuts);
  if (that.fMeanPtCuts) *fMeanPtCuts=*(that.fMeanPtCuts);
  fCutPrimaryVertexX=that.fCutPrimaryVertexX;
  fPrimaryVertexXmin=that.fPrimaryVertexXmin;
  fPrimaryVertexXmax=that.fPrimaryVertexXmax;
  fPrimaryVertexYmin=that.fPrimaryVertexYmin;
  fPrimaryVertexYmax=that.fPrimaryVertexYmax;
  fPrimaryVertexZmin=that.fPrimaryVertexZmin;
  fPrimaryVertexZmax=that.fPrimaryVertexZmax;
  fCutNContributors=that.fCutNContributors;
  fNContributorsMax=that.fNContributorsMax;
  fNContributorsMin=that.fNContributorsMin;
  fCutMeanPt=that.fCutMeanPt;
  fMeanPtMax=that.fMeanPtMax;
  fMeanPtMin=that.fMeanPtMin;
  fCutSPDvertexerAnomaly=that.fCutSPDvertexerAnomaly;
  fCutCentralityPercentile=that.fCutCentralityPercentile;
  fCentralityPercentileMethod=that.fCentralityPercentileMethod;
  fCentralityPercentileMax=that.fCentralityPercentileMax;
  fCentralityPercentileMin=that.fCentralityPercentileMin;
  return *this;
}

//-----------------------------------------------------------------------
Bool_t AliFlowEventCuts::IsSelected(TObject* obj)
{
  //check cuts
  AliVEvent* vevent = dynamic_cast<AliVEvent*>(obj);
  if (vevent) return PassesCuts(vevent);
  return kFALSE;  //when passed wrong type of object
}
//-----------------------------------------------------------------------
Bool_t AliFlowEventCuts::PassesCuts(AliVEvent *event)
{
  ///check if event passes cuts
  AliESDEvent* esdevent = dynamic_cast<AliESDEvent*>(event);
  if (fCutCentralityPercentile&&esdevent)
  {
    AliCentrality* centr = esdevent->GetCentrality();
    if (!centr->IsEventInCentralityClass( fCentralityPercentileMin,
                                          fCentralityPercentileMax,
                                          CentrMethName(fCentralityPercentileMethod) ))
    {
      return kFALSE;
    }
  }
  if (fCutSPDvertexerAnomaly&&esdevent)
  {
    const AliESDVertex* sdpvertex = esdevent->GetPrimaryVertexSPD();
    if (sdpvertex->GetNContributors()<1) return kFALSE;
    if (sdpvertex->GetDispersion()>0.04) return kFALSE;
    if (sdpvertex->GetZRes()>0.25) return kFALSE;
    const AliESDVertex* tpcvertex = esdevent->GetPrimaryVertexTPC();
    if (tpcvertex->GetNContributors()<1) return kFALSE;
    const AliMultiplicity* tracklets = esdevent->GetMultiplicity();
    if (tpcvertex->GetNContributors()<(-10.0+0.25*tracklets->GetNumberOfITSClusters(0)))
    {
      return kFALSE;
    }
  }
  if (fCutZDCtiming&&esdevent)
  {
    if (!fTrigAna.ZDCTimeTrigger(esdevent))
    {
      return kFALSE;
    }
  }
  if(fCutNumberOfTracks) {if ( event->GetNumberOfTracks() < fNumberOfTracksMin ||
                               event->GetNumberOfTracks() >= fNumberOfTracksMax ) return kFALSE;}
  if(fCutRefMult&&esdevent)
  {
    //reference multiplicity still to be defined
    Double_t refMult = RefMult(event);
    if (refMult < fRefMultMin || refMult >= fRefMultMax )
    {
      return kFALSE;
    }
  }
  const AliVVertex* pvtx=event->GetPrimaryVertex();
  Double_t pvtxx = pvtx->GetX();
  Double_t pvtxy = pvtx->GetY();
  Double_t pvtxz = pvtx->GetZ();
  Int_t ncontrib = pvtx->GetNContributors();
  if (fCutNContributors)
  {
    if (ncontrib < fNContributorsMin || ncontrib >= fNContributorsMax)
      return kFALSE;
  }
  if (fCutPrimaryVertexX)
  {
    if (pvtxx < fPrimaryVertexXmin || pvtxx >= fPrimaryVertexXmax)
      return kFALSE;
  }
  if (fCutPrimaryVertexY)
  {
    if (pvtxy < fPrimaryVertexYmin || pvtxy >= fPrimaryVertexYmax)
      return kFALSE;
  }
  if (fCutPrimaryVertexZ)
  {
    if (pvtxz < fPrimaryVertexZmin || pvtxz >= fPrimaryVertexZmax)
      return kFALSE;
  }
  if (fCutMeanPt)
  {
    Float_t meanpt=0.0;
    Int_t ntracks=event->GetNumberOfTracks();
    Int_t nselected=0;
    for (Int_t i=0; i<ntracks; i++)
    {
      AliVParticle* track = event->GetTrack(i);
      if (!track) continue;
      Bool_t pass=kTRUE;
      if (fMeanPtCuts) pass=fMeanPtCuts->IsSelected(track);
      if (pass)
      {
        meanpt += track->Pt();
        nselected++;
      }
    }
    meanpt=meanpt/nselected;
    if (meanpt<fMeanPtMin || meanpt >= fMeanPtMax) return kFALSE;
  }
  return kTRUE;
}

//-----------------------------------------------------------------------
const char* AliFlowEventCuts::CentrMethName(refMultMethod method) const
{
  //get the string for refmultmethod, for use with AliCentrality in
  //the cut on centrality percentile
  switch (method)
  {
    case kSPDtracklets:
      return "TKL";
    case kSPD1clusters:
      return "CL1";
    case kTPConly:
      return "TRK";
    case kV0:
      return "V0M";
    default:
      return "";
  }
}
//-----------------------------------------------------------------------
AliFlowEventCuts* AliFlowEventCuts::StandardCuts()
{
  //make a set of standard event cuts, caller becomes owner
  AliFlowEventCuts* cuts = new AliFlowEventCuts();
  return cuts;
}

//-----------------------------------------------------------------------
Int_t AliFlowEventCuts::RefMult(AliVEvent* event)
{
  //calculate the reference multiplicity, if all fails return 0
  AliESDVZERO* vzero = NULL;
  AliESDEvent* esdevent = dynamic_cast<AliESDEvent*>(event);

  if (fRefMultMethod==kTPConly && !fRefMultCuts)
  {
    fRefMultCuts = AliFlowTrackCuts::GetStandardTPCOnlyTrackCuts();
    fRefMultCuts->SetEtaRange(-0.8,0.8);
    fRefMultCuts->SetPtMin(0.15);
  }
  else if (fRefMultMethod==kSPDtracklets && !fRefMultCuts)
  {
    fRefMultCuts = new AliFlowTrackCuts("tracklet refmult cuts");
    fRefMultCuts->SetParamType(AliFlowTrackCuts::kESD_SPDtracklet);
    fRefMultCuts->SetEtaRange(-0.8,0.8);
  }
  else if (fRefMultMethod==kV0)
  {
    if (!esdevent) return 0;
    vzero=esdevent->GetVZEROData();
    if (!vzero) return 0;
    return TMath::Nint(vzero->GetMTotV0A()+vzero->GetMTotV0C());
  }
  else if (fRefMultMethod==kSPD1clusters)
  {
    if (!esdevent) return 0;
    const AliMultiplicity* mult = esdevent->GetMultiplicity();
    if (!mult) return 0;
    return mult->GetNumberOfITSClusters(1);
  }

  Int_t refmult=0;
  fRefMultCuts->SetEvent(event);
  for (Int_t i=0; i<fRefMultCuts->GetNumberOfInputObjects(); i++)
  {
    if (fRefMultCuts->IsSelected(fRefMultCuts->GetInputObject(i),i))
      refmult++;
  }
  return refmult;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkPrincipalAxesResampler.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

/*--------------------------------------------------------------------------
This command line program reads an image file, finds its principal
axes, and resamples the image into principal axes coordinates.  It
takes two arguments: the names of the input and output image files.
The image dimensions are fixed at 192 slices by 256 rows by 256
columns and the data format is fixed at bigendian 16-bit unsigned
integer.  (But see below for hooks to change these parameters.)
---------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>

#include "itkAffineTransform.h"
#include "itkByteSwapper.h"
#include "itkImage.h"
#include "itkImageMomentsCalculator.h"
#include "itkResampleImageFilter.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkLinearInterpolateImageFunction.h"

enum {NDimensions = 3};

typedef unsigned short                      PixelType;
typedef itk::Image<PixelType, NDimensions>  ImageType;
typedef ImageType::RegionType               ImageRegionType;
typedef ImageType::SizeType                 ImageSizeType;
typedef ImageType::AffineTransformType      AffineTransformType;

typedef itk::Index<NDimensions>                    ImageIndexType;
typedef itk::SimpleImageRegionIterator<ImageType>  ImageIteratorType;
typedef itk::ImageMomentsCalculator<ImageType>  ImageMomentsCalculatorType;
typedef itk::LinearInterpolateImageFunction<ImageType>  InterpolatorType;
typedef itk::Point<double, NDimensions>            PointType;

int
main(int argc, char *argv[])
{
    /* Set image and other parameters */
    long ImageWidth     = 256;
    long ImageHeight    = 256;
    long NumberOfSlices = 192;
    int bigend  = 1;             // Bigendian data in external files?
    int verbose = 1;             // Show intermediate results?

    /* Get input and output file names from the command line */
    if (argc < 2)
        {
            fprintf(stderr, "You must give input and output file names\n");
            exit(EXIT_FAILURE);
        }
    char *filename1 = argv[1];
    char *filename2 = argv[2];

    /* Open image file */
    /* FIXME: Translate into C++ */
    FILE *infile = fopen(filename1, "rb");
    if (infile == 0)
        {
            fprintf(stderr, "Unable to open input file\n");
            exit(EXIT_FAILURE);
        }

    /* Allocate an image object to store the input file in */
    ImageIndexType base = {{0,0,0}};
    ImageSizeType  size = {{ImageWidth, ImageHeight, NumberOfSlices}};
    double spacing[3] = {1.0, 1.0, 1.0};      // Pixel size
    double origin [3] = {0.0, 0.0, 0.0};      // Location of (0,0,0) pixel
    ImageType::Pointer image = ImageType::New();
    ImageRegionType region;
    region.SetIndex(base);
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetBufferedRegion(region);
    image->SetRequestedRegion(region);
    image->Allocate();
    image->SetOrigin(origin);
    image->SetSpacing(spacing);

    /* Read the image file into an itkImage object */
    /* FIXME: Find or write Insightful tools for this */
    std::cout << "Reading image file." << std::endl;
    ImageIndexType index;        // Index to current pixel
    unsigned long point[3];      // Location of current pixel
    PixelType *buff = new PixelType[ImageWidth];  // Input/output buffer
    PixelType maxval = 0;        // Maximum pixel value in image
    size_t count;
    for (long slice = 0; slice < NumberOfSlices; slice++) {
        point[2] = slice;
        for (long row = 0; row < ImageHeight; row++) {
            point[1] = row;
            count = fread(buff, sizeof(PixelType), ImageWidth, infile);
            if (count != (size_t)ImageWidth) {
                fprintf(stderr, "Error reading input file\n");
                exit(EXIT_FAILURE);
            }
            if (bigend)
                itk::ByteSwapper<PixelType>::SwapRangeBE(buff, ImageWidth);
            else
                itk::ByteSwapper<PixelType>::SwapRangeLE(buff, ImageWidth);
            for (long col = 0; col < ImageWidth; col++) {
                point[0] = col;
                index.SetIndex(point);
                image->SetPixel(index, buff[col]);
                if (buff[col] > maxval)
                    maxval = buff[col];
            }
        }
    }

    /* Print the maximum pixel value found.  (This is useful for detecting
       all-zero images, which confuse the moments calculation.) */
    std::cout << "   Max pixel value: " << maxval << std::endl;

    /* Close the input file */
    fclose(infile);

    /* Compute principal moments and axes */
    std::cout << "Computing moments and transformation." << std::endl;
    ImageMomentsCalculatorType moments(image);
    double ctm = moments.GetTotalMass();
    itk::Vector<double,3>
        ccg = moments.GetCenterOfGravity();
    itk::Vector<double,3>
        cpm = moments.GetPrincipalMoments();
    itk::Matrix<double,3,3>
        cpa = moments.GetPrincipalAxes();

    /* Report moments information to the user */
    if (verbose) {
        std::cout << "\nTotal mass = "        << ctm << std::endl;
        std::cout << "\nCenter of gravity = " << ccg << std::endl;
        std::cout << "\nPrincipal moments = " << cpm << std::endl;
        std::cout << "\nPrincipal axes = \n";
        std::cout << cpa << "\n";
    }

    /* Compute the transform from principal axes to original axes */
    double pi = 3.14159265359;
    AffineTransformType::Pointer trans = AffineTransformType::New();
    itk::Vector<double,3> center;
    center[0] = -ImageWidth / 2.0;
    center[1] = -ImageHeight / 2.0;
    center[2] = -NumberOfSlices / 2.0;
    trans->Translate(center);
    trans->Rotate(1, 0, pi/2.0);   // Rotate into radiological orientation
    trans->Rotate(2, 0, -pi/2.0);
    AffineTransformType::Pointer pa2phys =
        moments.GetPrincipalAxesToPhysicalAxesTransform();
    if (verbose) {
        std::cout << "Principal axes to physical axes transform" << std::endl;
        pa2phys->Print( std::cout );
    }
    trans->Compose(pa2phys);
    trans->Compose(image->GetPhysicalToIndexTransform());
    if (verbose) {
        std::cout << "Backprojection transform:" << std::endl;
        trans->Print( std::cout );
    }

    /* Create and initialize the interpolator */
    InterpolatorType::Pointer interp = InterpolatorType::New();
    interp->SetInputImage(image);

    /* Resample image in principal axes coordinates */
    std::cout << "Resampling the image" << std::endl;
    itk::ResampleImageFilter< ImageType, ImageType >::Pointer resample;
    resample = itk::ResampleImageFilter< ImageType, ImageType >::New();
    resample->SetInput(image);
    resample->SetSize(size);
    resample->SetTransform(trans);
    resample->SetInterpolator(interp);

    // Run the resampling filter
    resample->Update();

    // Extract the output image
   ImageType::Pointer resamp = resample->GetOutput();

    /* Open the output file */
    /* FIXME: Translate into C++ */
    std::cout << "Writing the output file" << std::endl;
    FILE *outfile = fopen(filename2, "wb");
    if (outfile == 0)
        {
            fprintf(stderr, "Unable to open output file\n");
            exit(EXIT_FAILURE);
        }

    /* Write resampled image to a file */
    for (long slice = 0; slice < NumberOfSlices; slice++) {
        point[2] = slice;
        for (long row = 0; row < ImageHeight; row++) {
            point[1] = row;
            for (long col = 0; col < ImageWidth; col++) {
                point[0] = col;
                index.SetIndex(point);
                buff[col] = resamp->GetPixel(index);
            }
            if (bigend)
                itk::ByteSwapper<PixelType>::SwapRangeBE(buff, ImageWidth);
            else
                itk::ByteSwapper<PixelType>::SwapRangeLE(buff, ImageWidth);
            count = fwrite(buff, 2, ImageWidth, outfile);
            if (count != (size_t)ImageWidth) {
                fprintf(stderr, "Error writing output file\n");
                exit(EXIT_FAILURE); }
        }
    }
    fclose(outfile);

    delete [] buff;
    return 0;
}
<commit_msg>ENH: index value type.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkPrincipalAxesResampler.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

/*--------------------------------------------------------------------------
This command line program reads an image file, finds its principal
axes, and resamples the image into principal axes coordinates.  It
takes two arguments: the names of the input and output image files.
The image dimensions are fixed at 192 slices by 256 rows by 256
columns and the data format is fixed at bigendian 16-bit unsigned
integer.  (But see below for hooks to change these parameters.)
---------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>

#include "itkAffineTransform.h"
#include "itkByteSwapper.h"
#include "itkImage.h"
#include "itkImageMomentsCalculator.h"
#include "itkResampleImageFilter.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkLinearInterpolateImageFunction.h"

enum {NDimensions = 3};

typedef unsigned short                      PixelType;
typedef itk::Image<PixelType, NDimensions>  ImageType;
typedef ImageType::IndexValueType           ImageIndexValueType;
typedef ImageType::RegionType               ImageRegionType;
typedef ImageType::SizeType                 ImageSizeType;
typedef ImageType::AffineTransformType      AffineTransformType;

typedef itk::Index<NDimensions>                    ImageIndexType;
typedef itk::SimpleImageRegionIterator<ImageType>  ImageIteratorType;
typedef itk::ImageMomentsCalculator<ImageType>  ImageMomentsCalculatorType;
typedef itk::LinearInterpolateImageFunction<ImageType>  InterpolatorType;
typedef itk::Point<double, NDimensions>            PointType;

int
main(int argc, char *argv[])
{
    /* Set image and other parameters */
    long ImageWidth     = 256;
    long ImageHeight    = 256;
    long NumberOfSlices = 192;
    int bigend  = 1;             // Bigendian data in external files?
    int verbose = 1;             // Show intermediate results?

    /* Get input and output file names from the command line */
    if (argc < 2)
        {
            fprintf(stderr, "You must give input and output file names\n");
            exit(EXIT_FAILURE);
        }
    char *filename1 = argv[1];
    char *filename2 = argv[2];

    /* Open image file */
    /* FIXME: Translate into C++ */
    FILE *infile = fopen(filename1, "rb");
    if (infile == 0)
        {
            fprintf(stderr, "Unable to open input file\n");
            exit(EXIT_FAILURE);
        }

    /* Allocate an image object to store the input file in */
    ImageIndexType base = {{0,0,0}};
    ImageSizeType  size = {{ImageWidth, ImageHeight, NumberOfSlices}};
    double spacing[3] = {1.0, 1.0, 1.0};      // Pixel size
    double origin [3] = {0.0, 0.0, 0.0};      // Location of (0,0,0) pixel
    ImageType::Pointer image = ImageType::New();
    ImageRegionType region;
    region.SetIndex(base);
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetBufferedRegion(region);
    image->SetRequestedRegion(region);
    image->Allocate();
    image->SetOrigin(origin);
    image->SetSpacing(spacing);

    /* Read the image file into an itkImage object */
    /* FIXME: Find or write Insightful tools for this */
    std::cout << "Reading image file." << std::endl;
    ImageIndexType index;        // Index to current pixel
    ImageIndexValueType point[3];      // Location of current pixel
    PixelType *buff = new PixelType[ImageWidth];  // Input/output buffer
    PixelType maxval = 0;        // Maximum pixel value in image
    size_t count;
    for (long slice = 0; slice < NumberOfSlices; slice++) {
        point[2] = slice;
        for (long row = 0; row < ImageHeight; row++) {
            point[1] = row;
            count = fread(buff, sizeof(PixelType), ImageWidth, infile);
            if (count != (size_t)ImageWidth) {
                fprintf(stderr, "Error reading input file\n");
                exit(EXIT_FAILURE);
            }
            if (bigend)
                itk::ByteSwapper<PixelType>::SwapRangeBE(buff, ImageWidth);
            else
                itk::ByteSwapper<PixelType>::SwapRangeLE(buff, ImageWidth);
            for (long col = 0; col < ImageWidth; col++) {
                point[0] = col;
                index.SetIndex(point);
                image->SetPixel(index, buff[col]);
                if (buff[col] > maxval)
                    maxval = buff[col];
            }
        }
    }

    /* Print the maximum pixel value found.  (This is useful for detecting
       all-zero images, which confuse the moments calculation.) */
    std::cout << "   Max pixel value: " << maxval << std::endl;

    /* Close the input file */
    fclose(infile);

    /* Compute principal moments and axes */
    std::cout << "Computing moments and transformation." << std::endl;
    ImageMomentsCalculatorType moments(image);
    double ctm = moments.GetTotalMass();
    itk::Vector<double,3>
        ccg = moments.GetCenterOfGravity();
    itk::Vector<double,3>
        cpm = moments.GetPrincipalMoments();
    itk::Matrix<double,3,3>
        cpa = moments.GetPrincipalAxes();

    /* Report moments information to the user */
    if (verbose) {
        std::cout << "\nTotal mass = "        << ctm << std::endl;
        std::cout << "\nCenter of gravity = " << ccg << std::endl;
        std::cout << "\nPrincipal moments = " << cpm << std::endl;
        std::cout << "\nPrincipal axes = \n";
        std::cout << cpa << "\n";
    }

    /* Compute the transform from principal axes to original axes */
    double pi = 3.14159265359;
    AffineTransformType::Pointer trans = AffineTransformType::New();
    itk::Vector<double,3> center;
    center[0] = -ImageWidth / 2.0;
    center[1] = -ImageHeight / 2.0;
    center[2] = -NumberOfSlices / 2.0;
    trans->Translate(center);
    trans->Rotate(1, 0, pi/2.0);   // Rotate into radiological orientation
    trans->Rotate(2, 0, -pi/2.0);
    AffineTransformType::Pointer pa2phys =
        moments.GetPrincipalAxesToPhysicalAxesTransform();
    if (verbose) {
        std::cout << "Principal axes to physical axes transform" << std::endl;
        pa2phys->Print( std::cout );
    }
    trans->Compose(pa2phys);
    trans->Compose(image->GetPhysicalToIndexTransform());
    if (verbose) {
        std::cout << "Backprojection transform:" << std::endl;
        trans->Print( std::cout );
    }

    /* Create and initialize the interpolator */
    InterpolatorType::Pointer interp = InterpolatorType::New();
    interp->SetInputImage(image);

    /* Resample image in principal axes coordinates */
    std::cout << "Resampling the image" << std::endl;
    itk::ResampleImageFilter< ImageType, ImageType >::Pointer resample;
    resample = itk::ResampleImageFilter< ImageType, ImageType >::New();
    resample->SetInput(image);
    resample->SetSize(size);
    resample->SetTransform(trans);
    resample->SetInterpolator(interp);

    // Run the resampling filter
    resample->Update();

    // Extract the output image
   ImageType::Pointer resamp = resample->GetOutput();

    /* Open the output file */
    /* FIXME: Translate into C++ */
    std::cout << "Writing the output file" << std::endl;
    FILE *outfile = fopen(filename2, "wb");
    if (outfile == 0)
        {
            fprintf(stderr, "Unable to open output file\n");
            exit(EXIT_FAILURE);
        }

    /* Write resampled image to a file */
    for (long slice = 0; slice < NumberOfSlices; slice++) {
        point[2] = slice;
        for (long row = 0; row < ImageHeight; row++) {
            point[1] = row;
            for (long col = 0; col < ImageWidth; col++) {
                point[0] = col;
                index.SetIndex(point);
                buff[col] = resamp->GetPixel(index);
            }
            if (bigend)
                itk::ByteSwapper<PixelType>::SwapRangeBE(buff, ImageWidth);
            else
                itk::ByteSwapper<PixelType>::SwapRangeLE(buff, ImageWidth);
            count = fwrite(buff, 2, ImageWidth, outfile);
            if (count != (size_t)ImageWidth) {
                fprintf(stderr, "Error writing output file\n");
                exit(EXIT_FAILURE); }
        }
    }
    fclose(outfile);

    delete [] buff;
    return 0;
}
<|endoftext|>


<commit_before>#include "LightRenderSystem.h"

#include "GraphicsBackendSystem.h"
#include <BufferFactory.h>
#include <GraphicsWrapper.h>
#include <InstanceData.h>
#include <LightInstanceData.h>
#include <LightMesh.h>

LightRenderSystem::LightRenderSystem( GraphicsBackendSystem* p_gfxBackend )
	: EntitySystem( SystemType::LightRenderSystem )
{
	m_gfxBackend = p_gfxBackend;

	m_box = NULL;
}

LightRenderSystem::~LightRenderSystem()
{
	delete m_box;
}

void LightRenderSystem::initialize()
{
	GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();

	BufferFactory* bufferFactory = new BufferFactory( gfxWrapper->getDevice(),
		gfxWrapper->getDeviceContext() );

	m_box = bufferFactory->createLightBoxMesh();
	delete bufferFactory;
}

void LightRenderSystem::processEntities( const vector<Entity*>& p_entities )
{
	GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();

	gfxWrapper->beginLightPass();			  // finalize, draw to back buffer
	//gfxWrapper->renderLights( NULL, NULL );

	static float range = 10.0f;
	AntTweakBarWrapper::getInstance()->addWriteVariable(AntTweakBarWrapper::GRAPHICS, "lightCubeWidth", TwType::TW_TYPE_FLOAT, &range,"");

	AglMatrix mat = AglMatrix::identityMatrix();
	mat[0] = mat[5] = mat[10] =  range / 2.0f; // The cube is 2.0f wide, therefore 2 and not 1

	LightInstanceData instData;
	instData.range = range; // Should be synced with wolrdTransform
	for( int i=0; i<16; i++ ){
		instData.worldTransform[i] = mat[i];
	}

	instData.lightDir[0] = 1.0f;
	instData.lightDir[1] = 0.0f;
	instData.lightDir[2] = 0.0f;

	instData.attenuation[0] = 1.1f;
	instData.attenuation[1] = 0.01f;
	instData.attenuation[2] = 0.1f;
	instData.spotPower = 100.0f;

	instData.ambient[0] = 0.01f;
	instData.ambient[1] = 0.01f;
	instData.ambient[2] = 0.01f;
	instData.ambient[3] = 1.01f;

	instData.diffuse[0] = 0.0f;
	instData.diffuse[1] = 0.5f;
	instData.diffuse[2] = 0.0f;
	instData.diffuse[3] = 1.0f;

	instData.specular[0] = 0.5f;
	instData.specular[1] = 0.1f;
	instData.specular[2] = 0.0f;
	instData.specular[3] = 1.0f;

	instData.enabled = true;
	instData.type = LightTypes::E_LightTypes_POINT;

	vector<LightInstanceData> instDatas;
	for( int x=0; x<5; x++ )
	{
		instData.worldTransform[3] = x * (range+1.0f) - 25.0f;
		instData.diffuse[1] += 0.1f;
		for( int y=0; y<5; y++ )
		{
			instData.worldTransform[7] = y * (range+1.0f) - 25.0f;
			instData.diffuse[2] += 0.1f;
			for( int z=0; z<5; z++ )
			{
				instData.worldTransform[11] = z * (range+1.0f) - 25.0f;
				instData.diffuse[3] += 0.1f;
				instDatas.push_back( instData );
			}
		}
	}

	gfxWrapper->renderLights( m_box, &instDatas );

	gfxWrapper->endLightPass();
}
<commit_msg>Removed AntTweakBar errors from the output.<commit_after>#include "LightRenderSystem.h"

#include "GraphicsBackendSystem.h"
#include <BufferFactory.h>
#include <GraphicsWrapper.h>
#include <InstanceData.h>
#include <LightInstanceData.h>
#include <LightMesh.h>

LightRenderSystem::LightRenderSystem( GraphicsBackendSystem* p_gfxBackend )
	: EntitySystem( SystemType::LightRenderSystem )
{
	m_gfxBackend = p_gfxBackend;

	m_box = NULL;
}

LightRenderSystem::~LightRenderSystem()
{
	delete m_box;
}

void LightRenderSystem::initialize()
{
	GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();

	BufferFactory* bufferFactory = new BufferFactory( gfxWrapper->getDevice(),
		gfxWrapper->getDeviceContext() );

	m_box = bufferFactory->createLightBoxMesh();
	delete bufferFactory;
}

void LightRenderSystem::processEntities( const vector<Entity*>& p_entities )
{
	GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();

	gfxWrapper->beginLightPass();			  // finalize, draw to back buffer
	//gfxWrapper->renderLights( NULL, NULL );

	static float range = 10.0f;

	AglMatrix mat = AglMatrix::identityMatrix();
	mat[0] = mat[5] = mat[10] =  range / 2.0f; // The cube is 2.0f wide, therefore 2 and not 1

	LightInstanceData instData;
	instData.range = range; // Should be synced with wolrdTransform
	for( int i=0; i<16; i++ ){
		instData.worldTransform[i] = mat[i];
	}

	instData.lightDir[0] = 1.0f;
	instData.lightDir[1] = 0.0f;
	instData.lightDir[2] = 0.0f;

	instData.attenuation[0] = 1.1f;
	instData.attenuation[1] = 0.01f;
	instData.attenuation[2] = 0.1f;
	instData.spotPower = 100.0f;

	instData.ambient[0] = 0.01f;
	instData.ambient[1] = 0.01f;
	instData.ambient[2] = 0.01f;
	instData.ambient[3] = 1.01f;

	instData.diffuse[0] = 0.0f;
	instData.diffuse[1] = 0.5f;
	instData.diffuse[2] = 0.0f;
	instData.diffuse[3] = 1.0f;

	instData.specular[0] = 0.5f;
	instData.specular[1] = 0.1f;
	instData.specular[2] = 0.0f;
	instData.specular[3] = 1.0f;

	instData.enabled = true;
	instData.type = LightTypes::E_LightTypes_POINT;

	vector<LightInstanceData> instDatas;
	for( int x=0; x<5; x++ )
	{
		instData.worldTransform[3] = x * (range+1.0f) - 25.0f;
		instData.diffuse[1] += 0.1f;
		for( int y=0; y<5; y++ )
		{
			instData.worldTransform[7] = y * (range+1.0f) - 25.0f;
			instData.diffuse[2] += 0.1f;
			for( int z=0; z<5; z++ )
			{
				instData.worldTransform[11] = z * (range+1.0f) - 25.0f;
				instData.diffuse[3] += 0.1f;
				instDatas.push_back( instData );
			}
		}
	}

	gfxWrapper->renderLights( m_box, &instDatas );

	gfxWrapper->endLightPass();
}
<|endoftext|>