当前位置: 首页>>代码示例>>C++>>正文


C++ Model类代码示例

本文整理汇总了C++中Model的典型用法代码示例。如果您正苦于以下问题:C++ Model类的具体用法?C++ Model怎么用?C++ Model使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Model类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: EnablePackageOnParentDocument

// simple callback enabling packages on main doc
int EnablePackageOnParentDocument(Model* m, SBMLErrorLog *, void* userdata)
{
  if (m == NULL) return LIBSBML_OPERATION_FAILED;

  // pull information out of userdata
  disable_info * info = static_cast<disable_info*>(userdata);
  
  SBMLDocument *mainDoc = static_cast<SBMLDocument*>(info->doc);
  std::set<std::pair<std::string, std::string> > disabled = 
    static_cast<std::set <std::pair <std::string, std::string> > >(info->disabledPkgs);


  if (mainDoc == NULL) return LIBSBML_OPERATION_FAILED;

  XMLNamespaces *mainNS = mainDoc->getSBMLNamespaces()->getNamespaces();

  XMLNamespaces *ns = m->getSBMLNamespaces()->getNamespaces();
  for (int i = 0; i < ns->getLength(); i++)
  {
    std::string nsURI = ns->getURI(i);
    std::string prefix = ns->getPrefix(i);
    if (prefix.empty() == true)
    {
      continue;
    }
    else if (mainNS->containsUri(nsURI) == false)
    {
      bool alreadyDisabled = false;
      for (set<pair<string, string> >::iterator pkg = disabled.begin();
           pkg != disabled.end(); pkg++)
      {
        if ((*pkg).first == nsURI)
        {
          alreadyDisabled = true;
          break;
        }
      }
      // just in case
      if (m->getSBMLDocument() == NULL)
      {
        continue;
      }
      if (m->isPackageEnabled(prefix) == true)
      {
        mainNS->add(nsURI, prefix);
        mainDoc->enablePackage(nsURI, prefix, true);
        mainDoc->setPackageRequired(prefix, 
          m->getSBMLDocument()->getPackageRequired(prefix));
        

        // we also need to make sure that if m was a modelDefinition
        // that we enable the package on its parent model
        Model * parent = dynamic_cast<Model*>(m->getAncestorOfType(SBML_MODEL));
        if (parent != NULL)
        {
          parent->enablePackageInternal(nsURI, prefix, true);
        }
      }
      else if (m->getSBMLDocument()->hasUnknownPackage(nsURI) == true)
      {
        // here we are dealing with an unknown package
        // need to decide whether to add the ns or not
        bool addNS = true;
        // if it was listed to be stripped do not add
        if (info->strippedPkgs.contains(prefix) == true) 
        {
          addNS = false;
        }
        // if it has already been disabled do not add
        else if (alreadyDisabled == true) 
        {
          addNS = false;
        }
        // if it is an unflattenable package and flags dicatate do not add
        else if (info->stripUnflattenable == true)
        {
          if (info->abortForRequiredOnly == false)
          {
            addNS = false;
          }
          else if (m->getSBMLDocument()->getPackageRequired(nsURI) == true)
          {
            addNS = false;
          }
        }

        if (addNS == true)
        {
          // we have an unknown package so we cannot enable it
          // but we do tell the parent doc about it
          mainNS->add(nsURI, prefix);
          mainDoc->addUnknownPackageRequired(nsURI, prefix,
            m->getSBMLDocument()->getPackageRequired(nsURI));
        }
      }
    }
  }

  return LIBSBML_OPERATION_SUCCESS;
//.........这里部分代码省略.........
开发者ID:copasi,项目名称:copasi-dependencies,代码行数:101,代码来源:CompFlatteningConverter.cpp

示例2: stripPackages

/** @cond doxygenLibsbmlInternal */
int 
CompFlatteningConverter::performConversion()
{  
  int result = LIBSBML_OPERATION_FAILED;

  if (mDocument == NULL) 
  {
    return LIBSBML_INVALID_OBJECT;
  }

  Model* mModel = mDocument->getModel();
  if (mModel == NULL) 
  {
    return LIBSBML_INVALID_OBJECT;
  }

  CompSBMLDocumentPlugin *plugin = 
                  (CompSBMLDocumentPlugin*)(mDocument->getPlugin("comp"));

  // if we don't have a comp model we are done already
  if (plugin == NULL)
  {
    return LIBSBML_OPERATION_SUCCESS;
  }

  // strip packages as instructed by user
  int success = stripPackages();
  if (success != LIBSBML_OPERATION_SUCCESS)
  {
    return LIBSBML_OPERATION_FAILED;
  }

  // look at the document and work out the status of any remaining packages
  mPackageValues.clear();
  analyseDocument();

  bool canFlatten = canBeFlattened();
  

  if (canFlatten == false)
  {
    return LIBSBML_OPERATION_FAILED;
  }

 

  /* strip any unflattenable packages before we run validation */
  if (getStripUnflattenablePackages() == true)
  {
    stripUnflattenablePackages();
  }

  /* run the comp validation rules as flattening will fail
   * if there are bad or missing references between elements
   */

  if (getPerformValidation() == true)
  {
    result = validateOriginalDocument();
    if (result != LIBSBML_OPERATION_SUCCESS) 
    {
      return result;
    }
  }
  CompModelPlugin *modelPlugin = (CompModelPlugin*)(mModel->getPlugin("comp"));

  if (modelPlugin==NULL) 
  {
    restoreNamespaces();
    return LIBSBML_OPERATION_FAILED;
  }

  mDocument->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed,
    modelPlugin->getPackageVersion(), mDocument->getLevel(), 
    mDocument->getVersion(),
    "The subsequent errors are from this attempt.");

  // setup callback that will enable the packages on submodels
  disable_info mainDoc;
  mainDoc.doc = mDocument;
  mainDoc.strippedPkgs = getPackagesToStrip();
  mainDoc.disabledPkgs = mDisabledPackages;
  mainDoc.stripUnflattenable = getStripUnflattenablePackages();
  mainDoc.abortForRequiredOnly = getAbortForRequired(); 
 
  Submodel::addProcessingCallback(&EnablePackageOnParentDocument, &(mainDoc));
  Model* flatmodel = modelPlugin->flattenModel();
  

  if (flatmodel == NULL) 
  {
    //'flattenModel' sets its own error messages.
    restoreNamespaces();
    return LIBSBML_OPERATION_FAILED;
  }

  // we haven't failed flattening so remove that error message
  mDocument->getErrorLog()->remove(CompModelFlatteningFailed);
  
//.........这里部分代码省略.........
开发者ID:copasi,项目名称:copasi-dependencies,代码行数:101,代码来源:CompFlatteningConverter.cpp

示例3: assert

 void Benchmarker::benchmark(int N, const Action6D::ActionSet &actionSet)
 {
     assert(environment_ != nullptr);
     
     std::cout << "\t *** BEGIN BENCHMARKING ***" << std::endl;
     
     MPVec3 halfSize = MPVec3MultiplyScalar(environment_->getSize(), 0.5f);
     
     MPVec3 min = MPVec3Subtract(environment_->getOrigin(), halfSize);
     MPVec3 max = MPVec3Add(environment_->getOrigin(), halfSize);
     
     MPAABox environmentBounds = MPAABoxMake(min, max);
     
     // Randomly generate N start/goal pairs within the bounds of the environment
     generateRandomStartGoalPairs3D(N, environmentBounds);
     
     if(planner_ != nullptr)
     {
         delete planner_;
         planner_ = nullptr;
     }
     
     // Set the action set to be in 3D
     Model *activeObject = environment_->getActiveObject();
     activeObject->setActionSet(actionSet);
     
     // Instantiate the planner
     planner_ = new AStarPlanner<Transform3D>(environment_, manhattanHeuristic);
     
     std::vector<std::vector<float> > planningTimes;
     std::vector<int> successes;
     
     // Test the planner with various weights
     for(int step = 0; step < 8; ++step)
     {
         int w;
         if(step < 2)
             w = step;
         else
             w = 2*step - 2;
         
         static_cast<AStarPlanner<Transform3D> *>(planner_)->setWeight(1.0f * w);
         
         std::cout << "\t *** WEIGHT = " << w << " ***" << std::endl;
         
         Timer timer;
         planningTimes.push_back(std::vector<float>());
         double planningTime = 0.0f;
         int success = 0, failure = 0;
         std::vector<Transform3D> plan;
         for(int i = 0; i < N; ++i)
         {
             planCounter_ = (step + 1) * i;
             plan.clear();
             std::cout << "Start: (" << startGoalPairs_.at(i).first.getPosition().x
             << ", " << startGoalPairs_.at(i).first.getPosition().y
             << ", " << startGoalPairs_.at(i).first.getPosition().z
             << "), Goal: (" << startGoalPairs_.at(i).second.getPosition().x
             << ", " << startGoalPairs_.at(i).second.getPosition().y
             << ", " << startGoalPairs_.at(i).second.getPosition().z
             << ")" << std::endl;
             
             // Reset the environment before each plan
             environment_->reset();
             
             timer.start();
             // Give the planner a timeout, and then force it to stop
             Later stopPlanner(PLANNER_TIMEOUT * 1000.0f, true, &Benchmarker::stopPlanning, this, (step + 1) * i);
             
             if(planner_->plan(startGoalPairs_.at(i).first, startGoalPairs_.at(i).second, plan))
             {
                 planningTime = (GET_ELAPSED_MICRO(timer) / 1000000.0f);
                 std::cout << "Success! Plan took " << planningTime << " seconds " << std::endl;
                 success++;
             }
             else
             {
                 std::cout << "Plan failed :(" << std::endl;
                 failure++;
             }
             
             planningTimes.at(step).push_back(planningTime);
         }
         
         std::cout << "\t *** TEST DONE ***" << std::endl;
         std::cout << success << " succeeded plans, " << failure << " failed plans" << std::endl;;
         std::cout << "Success rate: " << (1.0f * success / N) * 100.0f << "%" << std::endl;
         successes.push_back(success);
     }
     
     std::cout << "\t *** SUMMARY ***" << std::endl;
     for(int i = 0; i < planningTimes.size(); ++i)
     {
         float totalTime = 0.0f;
         int n = 0;
         for(auto time : planningTimes.at(i))
         {
             if(time <= PLANNER_TIMEOUT)
             {
                 totalTime += time;
//.........这里部分代码省略.........
开发者ID:jvisenti,项目名称:compgeo,代码行数:101,代码来源:MPBenchmarker.cpp

示例4: sizeof

void ModelViewer::Startup( void )
{
	m_RootSig.Reset(6, 2);
	m_RootSig.InitStaticSampler(0, SamplerAnisoWrapDesc, D3D12_SHADER_VISIBILITY_PIXEL);
	m_RootSig.InitStaticSampler(1, SamplerShadowDesc, D3D12_SHADER_VISIBILITY_PIXEL);
	m_RootSig[0].InitAsConstantBuffer(0, D3D12_SHADER_VISIBILITY_VERTEX);
	m_RootSig[1].InitAsConstantBuffer(0, D3D12_SHADER_VISIBILITY_PIXEL);
#if USE_ROOT_BUFFER_SRV || USE_VERTEX_BUFFER
	m_RootSig[2].InitAsBufferSRV(0, D3D12_SHADER_VISIBILITY_VERTEX);
#else
	m_RootSig[2].InitAsDescriptorRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 1, D3D12_SHADER_VISIBILITY_VERTEX);
#endif
	m_RootSig[3].InitAsDescriptorRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 6, D3D12_SHADER_VISIBILITY_PIXEL);
	m_RootSig[4].InitAsDescriptorRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 64, 3, D3D12_SHADER_VISIBILITY_PIXEL);
	m_RootSig[5].InitAsConstants(1, 1, D3D12_SHADER_VISIBILITY_VERTEX);
#if USE_VERTEX_BUFFER
	m_RootSig.Finalize(D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
#else
	m_RootSig.Finalize();
#endif

	DXGI_FORMAT ColorFormat = g_SceneColorBuffer.GetFormat();
	DXGI_FORMAT DepthFormat = g_SceneDepthBuffer.GetFormat();
	DXGI_FORMAT ShadowFormat = g_ShadowBuffer.GetFormat();

#if USE_VERTEX_BUFFER
	D3D12_INPUT_ELEMENT_DESC vertElem[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
		{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
		{ "BITANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
	};
#endif

	m_DepthPSO.SetRootSignature(m_RootSig);
	m_DepthPSO.SetRasterizerState(RasterizerDefault);
	m_DepthPSO.SetBlendState(BlendNoColorWrite);
	m_DepthPSO.SetDepthStencilState(DepthStateReadWrite);
#if USE_VERTEX_BUFFER
	m_DepthPSO.SetInputLayout(_countof(vertElem), vertElem);
#endif
	m_DepthPSO.SetPrimitiveTopologyType(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
	m_DepthPSO.SetRenderTargetFormats(0, nullptr, DepthFormat);
	m_DepthPSO.SetVertexShader(g_pDepthViewerVS, sizeof(g_pDepthViewerVS));
	m_DepthPSO.SetPixelShader(g_pDepthViewerPS, sizeof(g_pDepthViewerPS));
	m_DepthPSO.Finalize();

	m_ShadowPSO = m_DepthPSO;
	m_ShadowPSO.SetRasterizerState(RasterizerShadow);
	m_ShadowPSO.SetRenderTargetFormats(0, nullptr, g_ShadowBuffer.GetFormat());
	m_ShadowPSO.Finalize();

	m_ModelPSO = m_DepthPSO;
	m_ModelPSO.SetBlendState(BlendDisable);
	m_ModelPSO.SetDepthStencilState(DepthStateTestEqual);
	m_ModelPSO.SetRenderTargetFormats(1, &ColorFormat, DepthFormat);
	m_ModelPSO.SetVertexShader( g_pModelViewerVS, sizeof(g_pModelViewerVS) );
	m_ModelPSO.SetPixelShader( g_pModelViewerPS, sizeof(g_pModelViewerPS) );
	m_ModelPSO.Finalize();

	m_ExtraTextures[0] = g_SSAOFullScreen.GetSRV();
	m_ExtraTextures[1] = g_ShadowBuffer.GetSRV();

	TextureManager::Initialize(L"Textures/");
	ASSERT(m_Model.Load("Models/sponza.h3d"), "Failed to load model");
	ASSERT(m_Model.m_Header.meshCount > 0, "Model contains no meshes");

	CreateParticleEffects();

	float modelRadius = Length(m_Model.m_Header.boundingBox.max - m_Model.m_Header.boundingBox.min) * .5f;
	const Vector3 eye = (m_Model.m_Header.boundingBox.min + m_Model.m_Header.boundingBox.max) * .5f + Vector3(modelRadius * .5f, 0.0f, 0.0f);
	m_Camera.SetEyeAtUp( eye, Vector3(kZero), Vector3(kYUnitVector) );
	m_Camera.SetZRange( 1.0f, 10000.0f );
	m_pCameraController = new CameraController(m_Camera, Vector3(kYUnitVector));

	MotionBlur::Enable = true;
	TemporalAA::Enable = true;
	FXAA::Enable = true;
	PostEffects::EnableHDR = true;
	PostEffects::EnableAdaptation = true;
	PostEffects::AdaptationRate = 0.05f;
	PostEffects::TargetLuminance = 0.4f;
	PostEffects::MinExposure = 1.0f;
	PostEffects::MaxExposure = 8.0f;
	PostEffects::BloomThreshold = 1.0f;
	PostEffects::BloomStrength = 0.10f;
}
开发者ID:SuperWangKai,项目名称:DirectX-Graphics-Samples,代码行数:89,代码来源:ModelViewer.cpp

示例5: TEST_F

/**
 * Tests whether the ForwarTranslator will handle the name of the GeneratorMicroTurbine correctly in the PlantEquipmentOperationHeatingLoad
 **/
TEST_F(EnergyPlusFixture,ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop)
{

  // TODO: Temporarily output the Log in the console with the Trace (-3) level
  // for debug
  // openstudio::Logger::instance().standardOutLogger().enable();
  // openstudio::Logger::instance().standardOutLogger().setLogLevel(Trace);


  // Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter
  Model model;

  GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model);
  GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp);
  ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get());

  PlantLoop plantLoop(model);
  // Add a supply branch for the mchpHR
  ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR));

  // Create a WaterHeater:Mixed
  WaterHeaterMixed waterHeater(model);
  // Add it on the same branch as the chpHR, right after it
  Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>();
  ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode));

  // Create a plantEquipmentOperationHeatingLoad
  PlantEquipmentOperationHeatingLoad operation(model);
  operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad");
  ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation));
  ASSERT_TRUE(operation.addEquipment(mchpHR));
  ASSERT_TRUE(operation.addEquipment(waterHeater));

  // Create an ELCD
  ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model);
  elcd.setName("Capstone C65 ELCD");
  elcd.setElectricalBussType("AlternatingCurrent");
  elcd.addGenerator(mchp);

  // Forward Translates
  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);

  EXPECT_EQ(0u, forwardTranslator.errors().size());
  ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size());
  ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size());
  // The MicroTurbine should have been forward translated since there is an ELCD

  WorkspaceObjectVector microTurbineObjects(workspace.getObjectsByType(IddObjectType::Generator_MicroTurbine));
  EXPECT_EQ(1u, microTurbineObjects.size());
  // Check that the HR nodes have been set
  WorkspaceObject idf_mchp(microTurbineObjects[0]);
  EXPECT_EQ(mchpHR.inletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterInletNodeName).get());
  EXPECT_EQ(mchpHR.outletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterOutletNodeName).get());

  OptionalWorkspaceObject idf_operation(workspace.getObjectByTypeAndName(IddObjectType::PlantEquipmentOperation_HeatingLoad,*(operation.name())));
  ASSERT_TRUE(idf_operation);
  // Get the extensible
  ASSERT_EQ(1u, idf_operation->numExtensibleGroups());
  // IdfExtensibleGroup eg = idf_operation.getExtensibleGroup(0);
   // idf_operation.targets[0]
  ASSERT_EQ(1u, idf_operation->targets().size());
  WorkspaceObject plantEquipmentList(idf_operation->targets()[0]);
  ASSERT_EQ(2u, plantEquipmentList.extensibleGroups().size());

  IdfExtensibleGroup eg(plantEquipmentList.extensibleGroups()[0]);
  ASSERT_EQ("Generator:MicroTurbine", eg.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
  // This fails
  EXPECT_EQ(mchp.name().get(), eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());

  IdfExtensibleGroup eg2(plantEquipmentList.extensibleGroups()[1]);
  ASSERT_EQ("WaterHeater:Mixed", eg2.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
  EXPECT_EQ(waterHeater.name().get(), eg2.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());

  model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.osm"), true);
  workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.idf"), true);

}
开发者ID:NREL,项目名称:OpenStudio,代码行数:81,代码来源:GeneratorMicroTurbine_GTest.cpp

示例6: tr

void MainWindow::openFile()
{
    // If the current model has been modified, warn the user before opening the new file
    QMessageBox::StandardButton proceed = QMessageBox::Ok;
    if (modelLoaded)
        if (model->wasModified())
            proceed = QMessageBox::question(this, tr("Network Editor for SUMO"), tr("Model has been modified and not saved. Continue opening a new file?"),
                                            QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel);
    if (proceed == QMessageBox::Ok)
    {
        // Get file name from File Dialog
        QString filePath = QFileDialog::getOpenFileName(this, tr("Open SUMO Network file"),
            xmlPath, tr("XML Network files (*.net.xml)"));
        QCoreApplication::processEvents();

        // Open file
        if (!filePath.isEmpty())
        {
            QFile file(filePath);
            if (file.open(QIODevice::ReadOnly))
            {
                // Start counting opening time
                QTime t;
                t.start();

                // Create the model, parsing XML data first
                statusBar()->showMessage(tr("Loading XML file..."));
                Model *newModel = new Model(&file, this);

                // If the file has valid XML data, continue loading the model
                if (newModel->xmlDataParsed())
                {
                    // Delete the old model and connect the new one
                    if (modelLoaded) delete model;
                    connect(newModel, SIGNAL(statusUpdate(QString)), statusBar(), SLOT(showMessage(QString)));

                    // Create the item selection model so that it is passed onto the
                    // individual graphic elements as they are created
                    treeSelections = new QItemSelectionModel(newModel);
                    newModel->setSelectionModel(treeSelections);

                    // Interpret XML tree and create the traffic network elements
                    newModel->loadModel();

                    // Connect model with tree view
                    tView->setModel(newModel);
                    tView->setSelectionModel(treeSelections);
                    tView->resizeColumnToContents(0);
                    tView->resizeColumnToContents(1);

                    // Connect model with network view
                    nView->setScene(newModel->netScene);
                    nView->setSelectionModel(treeSelections);
                    nView->zoomExtents();
                    nView->setRenderHint(QPainter::Antialiasing, true);

                    // Connect model with controls and properties view
                    controls->reset();
                    controls->model = newModel;
                    pView->model = newModel;
                    eView->model = newModel;
                    controlWidget->show();
                    propsWidget->show();
                    editWidget->show();

                    // Replace old model by new model
                    model = newModel;
                    modelLoaded = true;
                    xmlPath = filePath;

                    // Update window title
                    QFileInfo fileInfo(file.fileName());
                    QString filename(fileInfo.fileName());
                    setWindowTitle(filename + tr(" - Network Editor for SUMO"));

                    // Connect signals and slots between all views
                    connect(tView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(showItem(QModelIndex)));
                    connect(nView, SIGNAL(updateStatusBar(QString)), statusBar(), SLOT(showMessage(QString)));
                    connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), model, SLOT(selectionChanged(QItemSelection, QItemSelection)));
                    connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), pView, SLOT(selectionChanged(QItemSelection, QItemSelection)));
                    connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), eView, SLOT(selectionChanged(QItemSelection, QItemSelection)));
                    connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(scrollTo(QItemSelection, QItemSelection)));
                    connect(model, SIGNAL(attrUpdate(QItemSelection, QItemSelection)), pView, SLOT(selectionChanged(QItemSelection, QItemSelection)));
                    connect(model, SIGNAL(attrUpdate(QItemSelection, QItemSelection)), eView, SLOT(selectionChanged(QItemSelection, QItemSelection)));
                    statusBar()->showMessage(tr("Ready. Model loaded in %1ms.").arg(t.elapsed()));
                }
                else
                {
                    // The XML data in the file was not valid, so do not load the model
                    delete newModel;
                    QMessageBox::warning(this, tr("Network Editor for SUMO"), tr("Error parsing XML data."));
                }
                // Close file
                file.close();
            }
        }
    }
}
开发者ID:matt-wirtz,项目名称:SUMO-NetEditor,代码行数:98,代码来源:mainwindow.cpp

示例7: TEST_F

TEST_F(AnalysisDriverFixture,RuntimeBehavior_StopCustomAnalysis) {
  // Tests for stopping time < 20s.

  // RETRIEVE PROBLEM
  Problem problem = retrieveProblem("UserScriptContinuous",true,false);

  // DEFINE SEED
  Model model = model::exampleModel();
  openstudio::path p = toPath("./example.osm");
  model.save(p,true);
  FileReference seedModel(p);

  // CREATE ANALYSIS
  Analysis analysis("Stop Custom Analysis",
                    problem,
                    seedModel);
  // generate 100 random points
  boost::mt19937 mt;
  typedef boost::uniform_real<> dist_type;
  typedef boost::variate_generator<boost::mt19937&, dist_type > gen_type;
  InputVariableVector variables = problem.variables();
  ContinuousVariable cvar = variables[0].cast<ContinuousVariable>();
  gen_type generator0(mt,dist_type(cvar.minimum().get(),cvar.maximum().get()));
  cvar = variables[1].cast<ContinuousVariable>();
  gen_type generator1(mt,dist_type(cvar.minimum().get(),cvar.maximum().get()));
  cvar = variables[2].cast<ContinuousVariable>();
  gen_type generator2(mt,dist_type(cvar.minimum().get(),cvar.maximum().get()));

  for (int i = 0, n = 100; i < n; ++i) {
    std::vector<QVariant> values;
    double value = generator0();
    values.push_back(value);
    value = generator1();
    values.push_back(value);
    value = generator2();
    values.push_back(value);
    OptionalDataPoint dataPoint = problem.createDataPoint(values);
    ASSERT_TRUE(dataPoint);
    ASSERT_TRUE(analysis.addDataPoint(*dataPoint));
  }

  // RUN ANALYSIS
  ProjectDatabase database = getCleanDatabase("StopCustomAnalysis");
  AnalysisDriver analysisDriver(database);
  AnalysisRunOptions runOptions = standardRunOptions(analysisDriver.database().path().parent_path());
  runOptions.setQueueSize(2);
  StopWatcher watcher(analysisDriver);
  watcher.watch(analysis.uuid());
  CurrentAnalysis currentAnalysis = analysisDriver.run(analysis,runOptions);
  EXPECT_EQ(2,currentAnalysis.numQueuedJobs());
  EXPECT_EQ(0,currentAnalysis.numQueuedDakotaJobs());
  EXPECT_EQ(100,currentAnalysis.totalNumJobsInOSIteration());
  EXPECT_EQ(0,currentAnalysis.numCompletedJobsInOSIteration());
  analysisDriver.waitForFinished();
  EXPECT_FALSE(analysisDriver.isRunning());
  EXPECT_GE(watcher.nComplete(),watcher.stopNum());
  EXPECT_LE(watcher.stoppingTime(),openstudio::Time(0,0,0,20));

  // check conditions afterward
  RunManager runManager = analysisDriver.database().runManager();
  EXPECT_FALSE(runManager.workPending());
  BOOST_FOREACH(const Job& job,runManager.getJobs()) {
    EXPECT_FALSE(job.running());
    EXPECT_FALSE(job.treeRunning());
  }
  EXPECT_TRUE(currentAnalysis.numCompletedJobsInOSIteration() > 0);
  EXPECT_TRUE(currentAnalysis.analysis().dataPointsToQueue().size() > 0u);
  EXPECT_TRUE(currentAnalysis.analysis().dataPointsToQueue().size() < 100u);
  EXPECT_EQ(0u,analysisDriver.currentAnalyses().size());
}
开发者ID:Rahjou,项目名称:OpenStudio,代码行数:70,代码来源:RuntimeBehavior_GTest.cpp

示例8: main

int main(int argc, char **argv)
{
	int width,height;
	Camera cam;
	int mousedx=0;
	int mousedy=0;
	int fps=0;
	int nrOfObjects=0;
	int nrOfLights=0;
	float tdropoff=0.0f;
	float topacity=0.0f;
	float tradius=0.0f;
	int nrOfPaths=0;
	int nrOfParticleSystems=0;
	float gr=0.0f;
	float gg=0.0f;
	float gb=0.0f;
	sf::Clock clock;

	//window options
	width=1280;
	height=720;
	sf::WindowSettings settings;
	settings.DepthBits         = 24;
	settings.StencilBits       = 8;
	settings.AntialiasingLevel = 1;  
	sf::Window app;
	app.Create(sf::VideoMode(width, height, 32), "Saints Edit", sf::Style::Close|sf::Style::Resize, settings);
	app.UseVerticalSync(true);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		cout<<"ERROR starting GLEW: "<< glewGetErrorString(err);
	}
	
	
	//Start renderer after glewinit,GLSPprog needs it (could add init method for global renderer)
	Renderer rend;
	GUI gui;

	gui.init();
	gui.drawSplashScreen();
	app.Display();
	
	//sets up the terrain
	Terrain terrain(0);
	PathHandler ph;
	LightHandler lh;
	ParticleHandler particleHandler;
	particleHandler.init();
	lh.init();
	ph.init();
	terrain.setRadius(gui.getSliderRadius());
	terrain.setOpacity(gui.getSliderOpacity());
	gui.setSurfaceTexHandles(terrain.getSurfaceTexHandles());

	//the gui needs the textures for browsing
	gui.setTerrainInfo(terrain.getTerrInfo());
	rend.updateProjMatrix(width,height);
	rend.updateViewMatrix(cam.getViewMatrix());
	terrain.updateProjMatrix(width,height);
	terrain.updateViewMatrix(cam.getViewMatrix());
	ph.updateProjectionMatrix(width,height);
	ph.updateViewMatrix(cam.getViewMatrix());
	glViewport(0,0,width,height);

	MeshHandler mh("./models/");

	for(int i=0; i<mh.getNrOfMeshes(); i++)
	{
		Model tmp;
		tmp.setMesh(mh.getMeshInfo(i));
		tmp.setBoundingBox(mh.getBoundingBox(i));
		tmp.setMeshName(mh.getMeshName(i));
		tmp.setType(mh.getMeshType(i));
		gui.addDisplayModel(tmp);
	}


	sf::Event event;

	Model m;
	
	TwInit(TW_OPENGL_CORE,NULL);
	TwWindowSize(width,height);
	TwBar *myBar;
	myBar = TwNewBar("info");
	TwDefine(" info position='25 40' size='240 320' help='Information about the map etc.' refresh=0.1 ");
	TwAddButton(myBar, "gi", NULL, NULL, " label='General info' ");
	TwAddVarRO(myBar,"fps ", TW_TYPE_INT32, &fps,NULL);
	TwAddVarRO(myBar,"# Models ", TW_TYPE_INT32, &nrOfObjects,NULL);
	TwAddVarRO(myBar,"# Lights ", TW_TYPE_INT32, &nrOfLights,NULL);
	TwAddVarRO(myBar,"# Particlesystems ", TW_TYPE_INT32, &nrOfParticleSystems,NULL);
	TwAddVarRO(myBar,"# Paths ", TW_TYPE_INT32, &nrOfPaths,NULL);
	TwAddSeparator(myBar, "sep1", NULL);
	TwAddButton(myBar, "di", NULL, NULL, " label='Brush info' ");
	TwAddVarRO(myBar,"Radius", TW_TYPE_FLOAT, &tradius,NULL);
	TwAddVarRO(myBar,"Dropoff", TW_TYPE_FLOAT, &tdropoff,NULL);
	TwAddVarRO(myBar,"Opacity", TW_TYPE_FLOAT, &topacity,NULL);
//.........这里部分代码省略.........
开发者ID:nepo1337,项目名称:medit,代码行数:101,代码来源:main.cpp

示例9: load


//.........这里部分代码省略.........
					else // Else its an actual road piece (at least we hope so because else we are screwed)
					{
						float rot,scale;
						float x, z;
						sscanf(buf, "%f %f %f %f", &rot, &x, &z,&scale);
						terr.addSurface(vec3(x,0,z),rot,surfCounter,scale);
						

						//m_roads.push_back(g_graphicsEngine->createRoad(texture, FLOAT3(x, 0.0f, -z), rot));
					}
				}
			}
			else if(strcmp(key, "MODELS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
						char in[100];
						vec3 position;
						vec3 rotation;
						float scale;
						int id = 0;
						sscanf(buf, "%s %f %f %f %f %f %f %f %d", &in, &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &scale,&id);
						Model model;
						string modelName = string(in);
						int meshIndex = m.getMeshByName(modelName);
						model.setMesh(m.getMeshInfo(meshIndex));
						model.setBoundingBox(m.getBoundingBox(meshIndex));
						model.setMeshName(m.getMeshName(meshIndex));
						model.setPos(position);
						model.rotateX(rotation.x);
						model.rotateY(rotation.y);
						model.rotateZ(rotation.z);
						model.scaleXYZ(scale);
						model.bindId(id);
						r.addModel(model);
						if(id>bindCounter)
							bindCounter=id;
					}
				}
			}
			else if(strcmp(key, "LIGHTS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
开发者ID:nepo1337,项目名称:medit,代码行数:67,代码来源:main.cpp

示例10: main

/**
 * Run a simulation of block sliding with contact on by two muscles sliding with contact 
 */
int main()
{

    try {
        // Create a new OpenSim model
        Model osimModel;
        osimModel.setName("osimModel");

        double Pi = SimTK::Pi;
        
        
        // Get the ground body
        OpenSim::Body& ground = osimModel.getGroundBody();
        ground.addDisplayGeometry("checkered_floor.vtp");

        // create linkage body
        double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
        
        Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
        Vec3 linkageMassCenter(0,linkageLength/2,0);
        Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);

        OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);

        // Graphical representation
        linkage1->addDisplayGeometry("cylinder.vtp");
        //This cylinder.vtp geometry is 1 meter tall, 1 meter diameter.  Scale and shift it to look pretty
        GeometrySet& geometry = linkage1->updDisplayer()->updGeometrySet();
        DisplayGeometry& thinCylinder = geometry[0];
        thinCylinder.setScaleFactors(linkageDimensions);
        thinCylinder.setTransform(Transform(Vec3(0.0,linkageLength/2.0,0.0)));
        linkage1->addDisplayGeometry("sphere.vtp");
        //This sphere.vtp is 1 meter in diameter.  Scale it.
        geometry[1].setScaleFactors(Vec3(0.1));
        
        // Creat a second linkage body
        OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
        linkage2->setName("linkage2");

        // Creat a block to be the pelvis
        double blockMass = 20.0, blockSideLength = 0.2;
        Vec3 blockMassCenter(0);
        Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
        OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
        block->addDisplayGeometry("block.vtp");
        //This block.vtp is 0.1x0.1x0.1 meters.  scale its appearance
        block->updDisplayer()->updGeometrySet()[0].setScaleFactors(Vec3(2.0));

        // Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
        
        Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);

        PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1, 
            locationInChild, orientationInChild);

        PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
            locationInChild, orientationInChild);

        PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
            locationInChild, orientationInChild);
        
        double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
        CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
        ankleCoordinateSet[0].setName("q1");
        ankleCoordinateSet[0].setRange(range);

        CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
        kneeCoordinateSet[0].setName("q2");
        kneeCoordinateSet[0].setRange(range);

        CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
        hipCoordinateSet[0].setName("q3");
        hipCoordinateSet[0].setRange(range);

        // Add the bodies to the model
        osimModel.addBody(linkage1);
        osimModel.addBody(linkage2);
        osimModel.addBody(block);

        // Define contraints on the model
        //  Add a point on line constraint to limit the block to vertical motion

        Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
        PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
        osimModel.addConstraint(lineConstraint);

        // Add PistonActuator between the first linkage and the block
        Vec3 pointOnBodies(0);
        PistonActuator *piston = new PistonActuator();
        piston->setName("piston");
        piston->setBodyA(linkage1);
        piston->setBodyB(block);
        piston->setPointA(pointOnBodies);
        piston->setPointB(pointOnBodies);
        piston->setOptimalForce(200.0);
        piston->setPointsAreGlobal(false);

//.........这里部分代码省略.........
开发者ID:ANKELA,项目名称:opensim-core,代码行数:101,代码来源:toyLeg_example.cpp

示例11: foregroundModels

void Form::btnCut_clicked()
{
  // Setup the mask
  int extent[6];
  this->OriginalImage->GetExtent(extent);
  //PrintExtent("extent", extent);

  this->AlphaMask->SetExtent(extent);
  this->AlphaMask->AllocateScalars(VTK_UNSIGNED_CHAR, 1);
  
  int clippedExtent[6];
  ClipFilter->GetOutput()->GetExtent(clippedExtent);
  //PrintExtent("clippedExtent", clippedExtent);

  // Initialize the mask (everything background)
  for(int y = extent[2]; y <= extent[3]; y++)
    {
    for(int x = extent[0]; x <= extent[1]; x++)
      {
      unsigned char* pixel = static_cast<unsigned char*>(this->AlphaMask->GetScalarPointer(x,y,0));
      pixel[0] = ImageGraphCut::ALWAYSSINK;
      }
    }

  // Mask the foreground
  for(int y = clippedExtent[2]; y <= clippedExtent[3]; y++)
    {
    for(int x = clippedExtent[0]; x <= clippedExtent[1]; x++)
      {
      unsigned char* pixel = static_cast<unsigned char*>(this->AlphaMask->GetScalarPointer(x,y,0));
      pixel[0] = ImageGraphCut::SOURCE;
      }
    }

  vtkSmartPointer<vtkJPEGWriter> writer =
    vtkSmartPointer<vtkJPEGWriter>::New();
  writer->SetInputData(this->AlphaMask);
  writer->SetFileName("InitialMask.jpg");
  writer->Write();

  unsigned int numberOfMixtures = 5;

  std::vector<Model*> foregroundModels(numberOfMixtures);

  for(unsigned int i = 0; i < foregroundModels.size(); i++)
    {
    Model* model = new GaussianND;
    model->SetDimensionality(3); // rgb
    model->Init();
    foregroundModels[i] = model;
    }

  std::vector<Model*> backgroundModels(numberOfMixtures);

  for(unsigned int i = 0; i < backgroundModels.size(); i++)
    {
    Model* model = new GaussianND;
    model->SetDimensionality(3); // rgb
    model->Init();
    backgroundModels[i] = model;
    }

  vtkSmartPointer<vtkExpectationMaximization> emForeground =
    vtkSmartPointer<vtkExpectationMaximization>::New();
  emForeground->SetMinChange(2.0);
  emForeground->SetInitializationTechniqueToKMeans();

  vtkSmartPointer<vtkExpectationMaximization> emBackground =
    vtkSmartPointer<vtkExpectationMaximization>::New();
  emBackground->SetMinChange(2.0);
  emBackground->SetInitializationTechniqueToKMeans();

  vtkSmartPointer<ImageGraphCut> graphCutFilter =
    vtkSmartPointer<ImageGraphCut>::New();
  graphCutFilter->BackgroundEM = emBackground;
  graphCutFilter->ForegroundEM = emForeground;

  unsigned int totalIterations = 3;
  for(unsigned int i = 0; i < totalIterations; i++)
    {
    std::cout << "Grabcuts iteration " << i << std::endl;

    // Convert these RGB colors to XYZ points to feed to EM

    std::vector<vnl_vector<double> > foregroundRGBpoints = CreateRGBPoints(ImageGraphCut::SOURCE);
    std::vector<vnl_vector<double> > backgroundRGBpoints = CreateRGBPoints(ImageGraphCut::SINK);
    std::vector<vnl_vector<double> > alwaysBackgroundRGBpoints = CreateRGBPoints(ImageGraphCut::ALWAYSSINK);
    backgroundRGBpoints.insert(backgroundRGBpoints.end(), alwaysBackgroundRGBpoints.begin(), alwaysBackgroundRGBpoints.end());
    std::cout << "There are " << foregroundRGBpoints.size() << " foreground points." << std::endl;
    if(foregroundRGBpoints.size() < 10)
      {
      std::cerr << "There are not enough foreground points!" << std::endl;
      exit(-1);
      }
    std::cout << "There are " << backgroundRGBpoints.size() << " background points." << std::endl;

    std::cout << "Foreground EM..." << std::endl;
    emForeground->SetData(foregroundRGBpoints);
    emForeground->SetModels(foregroundModels);
    emForeground->Update();
//.........这里部分代码省略.........
开发者ID:caomw,项目名称:GrabCut,代码行数:101,代码来源:form.cpp

示例12: displayModel

void scene::displayModel(Model activeModel, Shader shader)
{
	activeModel.draw(shader);
}
开发者ID:namnx228,项目名称:billiard,代码行数:4,代码来源:scene.cpp

示例13: setModel

void RefractionCalibration::setModel(const Model &model) {
	setModel(model, FixedParams(model.size(), false));
}
开发者ID:odiofan,项目名称:StereoReconstruction,代码行数:3,代码来源:refractioncalibration.cpp

示例14: addModelElement

void addModelElement(Element *elem, std::vector<Row_Information_Struct> &mRowInformation,
                     int &rowIndex, xLightsFrame *xframe,
                     std::vector <Element*> &elements,
                     bool submodel) {
    if(!elem->GetCollapsed())
    {
        for(int j =0; j<elem->GetEffectLayerCount();j++)
        {
            Row_Information_Struct ri;
            ri.element = elem;
            ri.displayName = elem->GetName();
            ri.Collapsed = elem->GetCollapsed();
            ri.Active = elem->GetActive();
            ri.colorIndex = 0;
            ri.layerIndex = j;
            ri.Index = rowIndex++;
            ri.submodel = submodel;
            mRowInformation.push_back(ri);
        }
    }
    else
    {
        Row_Information_Struct ri;
        ri.element = elem;
        ri.Collapsed = elem->GetCollapsed();
        ri.displayName = elem->GetName();
        ri.Active = elem->GetActive();
        ri.colorIndex = 0;
        ri.layerIndex = 0;
        ri.Index = rowIndex++;
        ri.submodel = submodel;
        mRowInformation.push_back(ri);
    }
    Model *cls = xframe->GetModel(elem->GetName());
    if (cls == nullptr) {
        return;
    }
    elem->InitStrands(*cls);
    if (cls->GetDisplayAs() == "ModelGroup" && elem->ShowStrands()) {
        wxString models = cls->GetModelXml()->GetAttribute("models");
        wxArrayString model=wxSplit(models,',');
        for(size_t m=0;m<model.size();m++) {
            for (size_t x = 0; x < elements.size(); x++) {
                if (elements[x]->GetName() == model[m]) {
                    addModelElement(elements[x], mRowInformation, rowIndex, xframe, elements, true);
                }
            }
        }
    } else if (elem->ShowStrands()) {
        for (size_t s = 0; s < elem->getStrandLayerCount(); s++) {
            StrandLayer * sl = elem->GetStrandLayer(s);
            if (elem->getStrandLayerCount() > 1) {
                Row_Information_Struct ri;
                ri.element = elem;
                ri.Collapsed = !elem->ShowStrands();
                ri.Active = elem->GetActive();
                ri.displayName = sl->GetName();

                ri.colorIndex = 0;
                ri.layerIndex = 0;
                ri.Index = rowIndex++;
                ri.strandIndex = s;
                ri.submodel = submodel;
                mRowInformation.push_back(ri);
            }

            if (sl->ShowNodes()) {
                for (int n = 0; n < sl->GetNodeLayerCount(); n++) {
                    Row_Information_Struct ri;
                    ri.element = elem;
                    ri.Collapsed = sl->ShowNodes();
                    ri.Active = !elem->GetActive();
                    ri.displayName = sl->GetNodeLayer(n)->GetName();
                    ri.colorIndex = 0;
                    ri.layerIndex = 0;
                    ri.Index = rowIndex++;
                    ri.strandIndex = s;
                    ri.nodeIndex = n;
                    ri.submodel = submodel;
                    mRowInformation.push_back(ri);
                }
            }
        }
    }
}
开发者ID:Jchuchla,项目名称:xLights,代码行数:85,代码来源:SequenceElements.cpp

示例15: Swap

bool PraetoriansTerrainWater::loadPackedMedia(const char* path)
{
  unsigned int signature;
  unsigned short chunkid;
  unsigned int chunklength;
  unsigned int texturescount;///use one in this version
  unsigned int watercount;
  unsigned int vertexcount;
  unsigned int indexcount;
  
  Tuple3f* vertices;
  unsigned short* indices;
  Tuple4ub* colors;
  Tuple2f* txcoords;
  ArchivedFile* file;
  WaterDatabase* wdatabase;
  
  if (!(file = FileSystem::checkOut(path)))
    return Logger::writeErrorLog(String("Could not load -> ") + path);
    
  wdatabase = Gateway::getWaterDatabase();
  
  file->read(&signature, 4);
  
  file->read(&chunkid, 2);
  file->read(&chunklength, 4);
  file->read(&texturescount, 4);
  for (unsigned int i = 0; i < texturescount; i++)
    file->seek((256 * 256 * 4) + 6, SEEKD);
    
  file->read(&watercount, 4);
  for (unsigned int i = 0; i < watercount; i++)
  {
    file->read(&chunkid, 2);
    file->read(&chunklength, 4);
    file->seek(48, SEEKD);
    file->read(&vertexcount, 4);
    
    vertices = new Tuple3f[vertexcount];
    colors = new Tuple4ub[vertexcount];
    txcoords = new Tuple2f[vertexcount];
    for (unsigned int j = 0; j < vertexcount; j++)
    {
      file->read(vertices[j], 12);
      Swap(vertices[j].x, vertices[j].z);
      file->read(colors[j], 4);
      Swap(colors[j].x, colors[j].z);
      file->read(txcoords[j], 8);
    }
    
    file->read(&indexcount, 4);
    indices = new unsigned short[indexcount];
    file->read(indices, indexcount * 2);
    
    String watername = String("H2O_") + int(wdatabase->getWatersCount());
    Geometry* geometry;
    geometry = new Geometry(watername, indexcount, vertexcount);
    geometry->setIndices(indices, false);
    geometry->setVertices(vertices, false);
    geometry->setColors(colors, false);
    geometry->setTextureElements(txcoords, 2, false);
    geometry->computeBounds();
    
    Appearance* appearance = new Appearance();
    appearance->setBlendAttributes(BlendAttributes(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
    appearance->setTexture(0, wdatabase->getWaterTexture());
    
    Model* model = new Model();
    model->setAppearance(appearance);
    model->setGeometry(geometry);
    
    TransformGroup* group = new TransformGroup();
    group->addChild(model);
    group->updateBoundsDescriptor();
    wdatabase->addWaterModel(group);
    
    deleteArray(vertices);
    deleteArray(indices);
    deleteArray(colors);
    deleteArray(txcoords);
  }
  
  FileSystem::checkIn(file);
  
  return true;
}
开发者ID:hyperiris,项目名称:praetoriansmapeditor,代码行数:86,代码来源:PraetoriansTerrainWater.cpp


注:本文中的Model类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。