// 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;
}
/** @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);
  

  if (getPerformValidation() == true)
  {
    flatmodel->populateAllElementIdList();
    flatmodel->populateAllElementMetaIdList();
    result = validateFlatDocument(flatmodel,
                    modelPlugin->getPackageVersion(), modelPlugin->getLevel(), 
                    modelPlugin->getVersion());
    if (result != LIBSBML_OPERATION_SUCCESS)
    {
      delete flatmodel;
      return result;
    }
  }

  // now reconstruct the document to be returned 
  // taking user options into account
  result = reconstructDocument(flatmodel);
  delete flatmodel;


  if (result != LIBSBML_OPERATION_SUCCESS) 
  {
    restoreNamespaces();
    return result;
  }

  return LIBSBML_OPERATION_SUCCESS;
}
Ejemplo n.º 3
0
 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;
                 n++;
             }
         }
         
         int weight = (i < 2 ? i : 2*i - 2);
         
         std::cout << "Weight " << weight << ": (average) " << totalTime / n  << " (success rate) " << ((1.0f * successes.at(i)) / N) * 100.0f << "%" << std::endl;
     }
 }
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;
}
/**
 * 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);

}
Ejemplo n.º 6
0
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();
            }
        }
    }
}
Ejemplo n.º 7
0
void calcularCapsaMinimaContenidora() {
	first = false;
	const int &tam = m.vertices().size();
	const Vertex *v;
	const Face &f = m.faces()[0];
	v = &m.vertices()[f.v[0]];
	xmax = xmin = (*v);
	ymax = ymin = *(v+1);
	zmax = zmin = *(v+2);
	for (int i = 0; i < tam; i+=3) {
	       if (m.vertices()[i] > xmax) xmax = m.vertices()[i];
	       if (m.vertices()[i+1] > ymax) ymax = m.vertices()[i+1];
	       if (m.vertices()[i+2] > zmax) zmax = m.vertices()[i+2];
	       if (m.vertices()[i] < xmin) xmin = m.vertices()[i];
	       if (m.vertices()[i+1] < ymin) ymin = m.vertices()[i+1];
	       if (m.vertices()[i+2] < zmin) zmin = m.vertices()[i+2];
	}
	centrox = (xmax + xmin)/2.;
	centroy = (ymax + ymin)/2.;
	centroz = (zmax + zmin)/2.;
	
	tamx = xmax - xmin;			//tamx = ancho
	tamy = ymax - ymin;			//tamy = alto
	tamz = zmax - zmin;			//tamz = profundo

	diametro = sqrt((tamx*tamx) + (tamy*tamy) + (tamz*tamz));
	
	if (tamx >= tamy and tamx >= tamz) escalado = tamanyQueVolem/tamx;
	else if (tamy >= tamx and tamy >= tamz) escalado = tamanyQueVolem/tamy;
	else if (tamz >= tamx and tamz >= tamy) escalado = tamanyQueVolem/tamz;

	subirBase = tamanyQueVolem/2.;

	ancho_escalado = tamx*escalado;
	alto_escalado = tamy*escalado;
	profundo_escalado = tamz*escalado;
}
Ejemplo n.º 8
0
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());
}
Ejemplo n.º 9
0
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);
	TwAddSeparator(myBar, "sep2", NULL);
	TwAddButton(myBar, "ci", NULL, NULL, " label='Color selected' ");
	TwAddVarRO(myBar,"Red", TW_TYPE_FLOAT, &gr,NULL);
	TwAddVarRO(myBar,"Green", TW_TYPE_FLOAT, &gg,NULL);
	TwAddVarRO(myBar,"Blue", TW_TYPE_FLOAT, &gb,NULL);

	while (app.IsOpened())
	{
		float normalisedx = 0;
		float normalisedy = 0;
		nrOfObjects=rend.getNrOfModels();
		nrOfLights=lh.getNrOfLights();
		tradius=gui.getSliderRadius();
		tdropoff=gui.getSliderDropoff();
		topacity=gui.getSliderOpacity();
		nrOfParticleSystems=particleHandler.getNrOfParticleSystems();
		nrOfPaths=ph.getNrOfPaths();
		gr=gui.getNormalizedColor().x;
		gg=gui.getNormalizedColor().y;
		gb=gui.getNormalizedColor().z;
		

		getNormalizedXY(app.GetInput().GetMouseX(), app.GetInput().GetMouseY(),width,height,normalisedx, normalisedy);
		//events
		int handled;
		while(app.GetEvent(event))
		{
			handled = TwEventSFML(&event, 1,6);
			if(!handled)
			{
				if(event.Type==sf::Event::Closed)
				{
					app.Close();
				}
				if((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape))
				{
					app.Close();
				}
				if(event.Type==sf::Event::MouseMoved)
				{
					if(gui.getState()==GUIstate::PAINT)
					{
						vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
						terrain.setWorldXY(cam.getPos(),ray);
					}
				}


				if(event.Type == sf::Event::Resized)
				{
					height = app.GetHeight();
					width = app.GetWidth();
					glViewport(0,0,width,height);
					rend.updateProjMatrix(width,height);
					terrain.updateProjMatrix(width,height);
					ph.updateProjectionMatrix(width,height);
				}
				if(event.Type == sf::Event::MouseWheelMoved)
				{
					if(event.MouseWheel.Delta>0)
						cam.zoomIn(event.MouseWheel.Delta*2);
					else
						cam.zoomOut(-event.MouseWheel.Delta*2);
					rend.updateViewMatrix(cam.getViewMatrix());
					terrain.updateViewMatrix(cam.getViewMatrix());
					ph.updateViewMatrix(cam.getViewMatrix());
				}

				if(event.Type == sf::Event::MouseButtonPressed)
				{
					if(event.MouseButton.Button==sf::Mouse::Right)
					{
						gui.showMenu(true);
						gui.setRightClickXY(normalisedx,normalisedy);
						particleHandler.unselectAllParticleModels();
					}
				}

				if(event.Type == sf::Event::MouseButtonPressed)
				{
					if(event.MouseButton.Button==sf::Mouse::Left)
					{
						gui.setLeftClick(normalisedx,normalisedy);
						terrain.setActiveTex(gui.getActiveTex());
						

						if(gui.checkDialogAnswer()=="GRID")
						{
							terrain.showHideGridMap();
							gui.resetDialogAns();
						}

						if(!gui.isSaveMapDialogUp()&&!gui.isLoadMapDialogUp()&&!gui.isNewMapDialogUp())
						{
							
							if(gui.getState()==GUIstate::PARTICLE)
							{
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
									float x=-1;
									float z=1;
									terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
									if(gui.isPlacingParticleSystems())
									{
										if(x>0)
										{
											particleHandler.unselectAllParticleModels();
											Particle p;
											p=gui.getActiveParticleModel();
											p.setPos(vec3(x,gui.getActiveParticleModel().getPos().y,-z));
											particleHandler.addParticleModel(p);
											gui.setActiveParticleModel(particleHandler.getSelectedParticle());
										}
									}
									else
									{
										particleHandler.selectParticles(normalisedx,normalisedy,cam.getPos(),rend.getProjMatrix(),cam.getViewMatrix());
										gui.setActiveParticleModel(particleHandler.getSelectedParticle());
									}
								}
							}
							if(gui.getState()==GUIstate::ROAD)
							{
								if(gui.checkDialogAnswer()=="RS")
								{
									terrain.removeSelectedSurfaces();
									gui.resetDialogAns();
								}
							}
							if(gui.getState()==GUIstate::NONE)
							{
								if(gui.checkDialogAnswer()=="DEL") 
								{
									vector<Model> rm = rend.removeSelectedModels();
									lh.removeLightsBoundToModels(rm);
									vector<Model> tm =rend.getModels();
									terrain.recalcGridAroundModel(rm,tm);

									terrain.removeSelectedSurfaces();
									gui.resetDialogAns();
								}
							}
							if(gui.getState()==GUIstate::PARTICLE)
							{
								if(gui.checkDialogAnswer()=="DEL") 
								{
									particleHandler.removeSelectedParticles();
									gui.resetDialogAns();
								}
							}

							if(gui.getState()==GUIstate::PATH)
							{
								if(gui.checkDialogAnswer()=="DEL")
								{
									ph.removeSelectedPaths();
									gui.resetDialogAns();
								}
								if(gui.checkDialogAnswer()=="CRP")
								{
									ph.addPath();
									gui.resetDialogAns();
								}
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									if(gui.isSelectingRoad())
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											ph.addFlagToCurrentPath(vec3(x,0,-z));
										}
									}
									else
									{
										ph.selectPaths(normalisedx,normalisedy,cam.getPos());
									}
								}
							}
							if(gui.getState()==GUIstate::MODEL||gui.getState()==GUIstate::NONE)
							{
								if(gui.getState()==GUIstate::MODEL)
								{
									if(gui.isInDrawWindow(normalisedx,normalisedy))
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											if(m.getType()=="light")
											{
												m.bindId(bindCounter);
												vec3 lpos = m.getPos();
												lpos.y+=1;
												Light tmpLight;
												tmpLight.setColor(gui.getNormalizedColor());
												tmpLight.setPos(lpos);
												tmpLight.setRadius(gui.getSliderLightRadius());
												tmpLight.bindId(bindCounter);
												tmpLight.setContrast(gui.getContrast());
												tmpLight.setLightType(LightType::POINTLIGHTSHADOW);
												lh.addLight(tmpLight);
												bindCounter++;
											}
											rend.addModel(m);
											terrain.setWorldXY(cam.getPos(),ray);
											terrain.makeGridUnderModel(m);
										}
									}
								}
								if(gui.getState()==GUIstate::NONE)
								{
									if(gui.isInDrawWindow(normalisedx,normalisedy))
									{
										rend.selectModel(normalisedx,normalisedy,cam.getPos());

									}
								}
							}
							if(gui.getState()==GUIstate::ROAD)
							{
								vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
								terrain.setWorldXY(cam.getPos(),ray);
								terrain.selectTexSurfaces(0.5,cam.getPos(),ray);
							}
							
							if(gui.getState()==GUIstate::LIGHT)
							{
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									if(gui.isPlacingLightMode())
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											Light l = gui.getActiveLight();
											lh.deselectAllLights();
											l.setPos(vec3(x,l.getPos().y,-z));
											lh.addLight(l);
										}
									}
									else
									{
										int lightPos=lh.selectLight(normalisedx,normalisedy,cam.getPos(),rend.getProjMatrix(),cam.getViewMatrix());
										if(lightPos>=0)
										{
											Light tmpl = lh.getSelectedLight();
											gui.setSliderLightRadius(tmpl.getRadius());
											gui.setNormalizedColor(tmpl.getColor(),tmpl.getContrast());
											gui.setActiveLightModel(tmpl);
										}
									}
								}
								if(gui.checkDialogAnswer()=="DEL")
								{
									lh.removeSelectedLights();
								}
							}
						}

						if(gui.isSaveMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="svOK")
							{
								save(gui.getInputText(),terrain,rend,ph,lh,particleHandler);
								gui.hideSaveMapDialog();
							}
							if(gui.checkDialogAnswer()=="svC")
							{
								gui.hideSaveMapDialog();
							}
						}
						if(gui.isNewMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="nmCS")
							{
								terrain.createNewMap(0);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							
							if(gui.checkDialogAnswer()=="nmCM")
							{
								terrain.createNewMap(1);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							
							if(gui.checkDialogAnswer()=="nmCL")
							{
								terrain.createNewMap(2);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							if(gui.checkDialogAnswer()=="nmOK")
							{
								terrain.createNewMap(0);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							if(gui.checkDialogAnswer()=="nmC")
							{
								gui.hideNewMapDialog();
							}
						}
						if(gui.isLoadMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="lmOK")
							{
								load(gui.getInputText(),terrain,rend,ph,lh,particleHandler,mh);
								gui.hideLoadMapDialog();
							}
							if(gui.checkDialogAnswer()=="lmC")
							{
								gui.hideLoadMapDialog();
							}
						}
					}
				}

				if(event.Type == sf::Event::MouseButtonReleased)
				{
					if(event.MouseButton.Button==sf::Mouse::Right)
					{
						gui.showMenu(false);
						rend.unselectAllModels();
					}
				}
				//if the gui excpects text input
				if(gui.isInTextMode())
				{
					if(event.Type == sf::Event::KeyPressed)
					{
						if(int(event.Key.Code)>=97&&event.Key.Code<=122)
							gui.addChar(char(event.Key.Code));
					}
					if((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Back))
					{
						gui.removeChar();
					}
				}
			}
		}

		//realtime input
		
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Left))
		{
			if(!handled)
			{
				if(!gui.isSaveMapDialogUp()&&!gui.isLoadMapDialogUp()&&!gui.isNewMapDialogUp())
				{
					if(gui.isInDrawWindow(normalisedx,normalisedy))
					{
						if(gui.getState()==GUIstate::PAINT)
						{
							terrain.setTerState(TerrState::PAINT);
							terrain.paint(cam.getPos(),inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos()));
						}
						if(gui.getState()==GUIstate::ROAD)
						{
							terrain.setTerState(TerrState::DRAWSURFACE);
							vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
							terrain.addSurface(cam.getPos(),ray, gui.getActiveSurfaceTexHandle());
						}
					} 
					else 
					{
						gui.moveSliders(normalisedx,normalisedy);
						if(gui.getState()==GUIstate::PAINT)
						{
							terrain.setRadius(gui.getSliderRadius());
							terrain.setOpacity(gui.getSliderOpacity());
							terrain.setDropoff(gui.getSliderDropoff());
						}
						if(gui.getState()==GUIstate::ROAD)
						{
							terrain.setRoadSpacing(gui.getRoadSliderSpacing());
							terrain.setRoadScale(gui.getRoadSliderScale());
						}
						if(gui.getState()==GUIstate::PARTICLE)
						{
							particleHandler.assignParticleNewParticle(gui.getActiveParticleModel());
						}
						
						if(gui.getState()==GUIstate::LIGHT)
							lh.assignLightAnotherLight(gui.getActiveLight());
					}
				}
			}
		}
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Right))
		{
			gui.setMouseXY(normalisedx,normalisedy);
			terrain.deselectAllSurfaceTex();
			lh.deselectAllLights();
		}


		//if the user isnt in text mode, it should be able to move
		if(!gui.isInTextMode())
		{
			if(app.GetInput().IsKeyDown(sf::Key::Delete))
			{
				if(gui.getState()==GUIstate::MODEL||gui.getState()==GUIstate::NONE)
				{
					vector<Model> rm = rend.removeSelectedModels();
					lh.removeLightsBoundToModels(rm);
					vector<Model> tm =rend.getModels();
					terrain.recalcGridAroundModel(rm,tm);
				}
				if(gui.getState()==GUIstate::PATH)
				{
					ph.removeSelectedPaths();
				}
				if(gui.getState()==GUIstate::PARTICLE)
				{
					particleHandler.removeSelectedParticles();
				}
				if(gui.getState()==GUIstate::ROAD)
				{
					terrain.removeSelectedSurfaces();
				}
				if(gui.getState()==GUIstate::LIGHT)
				{
					lh.removeSelectedLights();
				}
				
			}
			if(gui.getState()==GUIstate::PAINT)
			{
					vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
					terrain.setWorldXY(cam.getPos(),ray);
			}
			if(app.GetInput().IsKeyDown(sf::Key::W))
			{
				cam.moveForeward(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::S))
			{
				cam.moveBackward(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::A))
			{
				cam.strafeLeft(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::D))
			{
				cam.strafeRight(0.1);
			}
			rend.updateViewMatrix(cam.getViewMatrix());
			terrain.updateViewMatrix(cam.getViewMatrix());
			ph.updateViewMatrix(cam.getViewMatrix());
			if(gui.getState()==GUIstate::MODEL)
			{
				if(app.GetInput().IsKeyDown(sf::Key::Q))
					gui.rotateActiveModelLeft(1.0f);

				if(app.GetInput().IsKeyDown(sf::Key::E))
					gui.rotateActiveModelRight(1.0f);
				if(app.GetInput().IsKeyDown(sf::Key::R))
					gui.raiseActiveModel(0.01);
				if(app.GetInput().IsKeyDown(sf::Key::F))
					gui.raiseActiveModel(-0.01);
			}
		}
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Middle))
		{
			cam.rotateLeft(mousedx-app.GetInput().GetMouseX());
			cam.rotateUp(mousedy-app.GetInput().GetMouseY());
			rend.updateViewMatrix(cam.getViewMatrix());
			terrain.updateViewMatrix(cam.getViewMatrix());
			ph.updateViewMatrix(cam.getViewMatrix());
		}

		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Right))
		{
			gui.showMenu(true);
			if(gui.getState()==GUIstate::PAINT)
			{
				terrain.showCircle();
			}
			else
				terrain.hideCircle();
		}
		//saves the position of the mouse, used for rotation
		mousedx=app.GetInput().GetMouseX();
		mousedy=app.GetInput().GetMouseY();

		glClearColor(0.75f, 0.87f, 0.85f, 0.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		terrain.draw();
		rend.draw();

		if(gui.getState()==GUIstate::PATH)
		{
			ph.drawPaths();
			if(gui.isSelectingRoad())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
					ph.drawFlag(vec3(x,0,-z));
			}
		}
		if(gui.getState()==GUIstate::ROAD)
		{
			vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
			terrain.drawSurface(cam.getPos(),ray, gui.getActiveSurfaceTexHandle(),app.GetInput().IsMouseButtonDown(sf::Mouse::Left));
		}
		if(gui.getState()==GUIstate::LIGHT)
		{
			lh.drawLights(rend.getProjMatrix(),cam.getViewMatrix());
			
			if(gui.isPlacingLightMode())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
				{
					Light l = gui.getActiveLight();
					l.setPos(vec3(x,l.getPos().y,-z));
					//l.select();
					lh.drawLight(rend.getProjMatrix(),cam.getViewMatrix(),l);
				}
			}
		}
		if(gui.getState()==GUIstate::MODEL &&gui.isInDrawWindow(normalisedx,normalisedy) )
		{
			vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
			float x=-1;
			float z=1;
			terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
			if(x>0)
			{
				m=gui.getActiveModel();
				m.setPos(vec3(x,gui.getActiveModel().getPos().y,-z));
				m.scaleXYZ(m.getScale());
				m.rotateY(m.getRot().y);
				rend.drawModel(m);
			}
		}
		if(gui.getState()==GUIstate::PARTICLE)
		{
			particleHandler.drawParticleModels(rend.getProjMatrix(),cam.getViewMatrix());
			
			if(gui.isPlacingParticleSystems())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
				{
					Particle p = gui.getActiveParticleModel();
					p.setPos(vec3(x,gui.getActiveParticleModel().getPos().y,-z));
					particleHandler.drawParticleModel(rend.getProjMatrix(),cam.getViewMatrix(),p);
				}
			}
		}
		gui.draw();

		fps= 1.0f/clock.GetElapsedTime();
		clock.Reset();
		TwDraw();
		app.Display();
	}
	TwTerminate();
	lh.free();
	
	return EXIT_SUCCESS;
}
Ejemplo n.º 10
0
void load(string filename, Terrain &terr, Renderer &r, PathHandler& p, LightHandler &l, ParticleHandler &part,MeshHandler &m)
{
	ifstream stream;
	string fullPath = path+filename+".txt";
	stream.open(fullPath.c_str());
	if(stream.is_open())
	{
		r.clear();
		l.clear();
		p.clear();
		part.clear();
		int mapsize=0;
		
		int highBind=0;
		string bmp1="";
		string bmp2="";
		int width=0;
		while(!stream.eof())
		{
			char buf[1024];
			char key[1024];
			stream.getline(buf, 1024);
			sscanf(buf, "%s", key);

			if(strcmp(key, "bmp1:") == 0)
			{
				char file[100];
				sscanf(buf, "bmp1: %s", &file);
				bmp1= string(file);
			}
			else if(strcmp(key, "bmp2:") == 0)
			{
				char file[100];
				sscanf(buf, "bmp2: %s", &file);
				bmp2= string(file);
				
				if(width == 128)
					mapsize=1;
				if(width==256)
					mapsize=2;
				terr.createNewMap(mapsize);
				terr.loadMaps(path+bmp1,path+bmp2,path+filename+"gm.png");
			}
			else if(strcmp(key, "width:") == 0)
			{
				sscanf(buf, "width: %d", &width);
			}		
			else if(strcmp(key, "Surfaceplanes:") == 0)
			{
				string texture;
				int surfCounter=-1;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "SF:") == 0)
					{
						char in[100];
						sscanf(buf, "SF: %s", &in);
						texture = string(in);
						surfCounter++;
					}
					else if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					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
					{
						char in[100];
						sscanf(buf, "%s", &in);

						if(strcmp(key, "AM") == 0)
						{
							vec3 direction;
							vec3 color;
							vec3 rot;
							vec3 pos;

							sscanf(buf, "AM %f %f %f %f %f %f %f %f %f %f %f %f", &direction.x, &direction.y, &direction.z, &color.x, &color.y, &color.z,&rot.x,&rot.y,&rot.z,&pos.x,&pos.y,&pos.z);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(pos);
							tmpLight.setRadius(0);
							tmpLight.setLightType(LightType::AMBIENT);
							tmpLight.rotateX(rot.x);
							tmpLight.rotateY(rot.y);
							tmpLight.rotateZ(rot.z);
							l.addLight(tmpLight);
						}
						else if(strcmp(key, "PLS") == 0)
						{
							vec3 position;
							vec3 rotation;
							vec3 color;
							float radius;
							int id=0;
							sscanf(buf, "PLS %f %f %f %f %f %f %f %f %f %f %d", &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &color.x, &color.y, &color.z, &radius,&id);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(radius);
							tmpLight.setLightType(LightType::POINTLIGHTSHADOW);
							tmpLight.rotateX(rotation.x);
							tmpLight.rotateY(rotation.y);
							tmpLight.rotateZ(rotation.z);
							tmpLight.bindId(id);
							l.addLight(tmpLight);

						}
						else if(strcmp(key, "PL") == 0)
						{
							vec3 position;
							vec3 rotation;
							vec3 color;
							float radius;
							int id=0;
							sscanf(buf, "PL %f %f %f %f %f %f %f %f %f %f %f", &position.x, &position.y, &position.z, &rotation.y, &rotation.x, &rotation.z, &color.x, &color.y, &color.z, &radius,&id);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(radius);
							tmpLight.setLightType(LightType::POINTLIGHT);
							tmpLight.rotateX(rotation.x);
							tmpLight.rotateY(rotation.y);
							tmpLight.rotateZ(rotation.z);
							tmpLight.bindId(id);
							l.addLight(tmpLight);
						}
						else if(strcmp(key, "SL") == 0)
						{
							vec3 position;
							vec3 direction;
							vec3 color;
							vec3 rot;
							sscanf(buf, "SL %f %f %f %f %f %f %f %f %f %f %f %f", &position.x, &position.y, &position.z, &direction.x, &direction.y, &direction.z, &color.x, &color.y, &color.z,&rot.x, &rot.y, &rot.z);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(0);
							tmpLight.setLightType(LightType::SPOTLIGHT);
							tmpLight.rotateX(rot.x);
							tmpLight.rotateY(rot.y);
							tmpLight.rotateZ(rot.z);
							l.addLight(tmpLight);
						}
					}
				}
			}
			else if(strcmp(key, "path") == 0)
			{
				p.addPath();
				stream.getline(buf, 1024);
				sscanf(buf, "%s", key);

				int nrOfPoints = 0;
				vec3 points[100];
				while(strcmp(key, "end") != 0)
				{
					float notInvertZ;
					points[nrOfPoints]=vec3(0.0f);
					sscanf(buf, "%f %f", &points[nrOfPoints].x, &points[nrOfPoints].z);
					nrOfPoints++;
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
				}

				for(int i = 0; i < nrOfPoints; i++)
				{
					p.addFlagToCurrentPath(points[i]);
				}

			}
			else if(strcmp(key, "PARTICLESYSTEMS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
						vec3 position;
						vec3 rotation;
						vec3 color;

						sscanf(buf, "%s %f %f %f %f %f %f %f %f %f", &key, &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &color.x, &color.y, &color.z);
						
						Particle particle;
						particle.setPos(position);
						particle.rotateX(rotation.x);
						particle.rotateY(rotation.y);
						particle.rotateZ(rotation.z);
						particle.setColor(color);
						string particleType=key;
						if(particleType=="GLOWRING")
							particle.setParticleType(ParticleType::GLOWRING);
						if(particleType=="FIRE")
							particle.setParticleType(ParticleType::FIRE);
						if(particleType=="EMIT")
							particle.setParticleType(ParticleType::EMIT);
						if(particleType=="FLOW")
							particle.setParticleType(ParticleType::FLOW);
						if(particleType=="SMOKE")
							particle.setParticleType(ParticleType::SMOKE);
						part.addParticleModel(particle);

						//Create particle system
						int lol = 0;
					}
				}
			}
			sscanf("bugfix", "%s", key);
		}	
		bindCounter++;
		stream.close();
	}
}
Ejemplo n.º 11
0
/**
 * 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);

        osimModel.addForce(piston);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // Added ControllableSpring between the first linkage and the second block
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ControllableSpring *spring = new ControllableSpring;
        spring->setName("spring");
        spring->setBodyA(block);
        spring->setBodyB(linkage1);
        spring->setPointA(pointOnBodies);
        spring->setPointB(pointOnBodies);
        spring->setOptimalForce(2000.0);
        spring->setPointsAreGlobal(false);
        spring->setRestLength(0.8);

        osimModel.addForce(spring);

        // define the simulation times
        double t0(0.0), tf(15);

        // create a controller to control the piston and spring actuators
        // the prescribed controller sets the controls as functions of time
        PrescribedController *legController = new PrescribedController();
        // give the legController control over all (two) model actuators
        legController->setActuators(osimModel.updActuators());

        // specify some control nodes for spring stiffness control
        double t[] = {0.0, 4.0, 7.0,  10.0, 15.0};
        double x[] = {1.0, 1.0, 0.25,  0.25, 5.0};

        // specify the control function for each actuator
        legController->prescribeControlForActuator("piston", new Constant(0.1));
        legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));

        // add the controller to the model
        osimModel.addController(legController);     
        
        // define the acceration due to gravity
        osimModel.setGravity(Vec3(0, -9.80665, 0));

        // enable the model visualizer see the model in action, which can be
        // useful for debugging
        osimModel.setUseVisualizer(true);

        // Initialize system
        SimTK::State& si = osimModel.initSystem();
        
        // Pin joint initial states
        double q1_i = -Pi/4;
        double q2_i = - 2*q1_i;
        CoordinateSet &coordinates = osimModel.updCoordinateSet();
        coordinates[0].setValue(si, q1_i, true);
        coordinates[1].setValue(si,q2_i, true);

        // Setup integrator and manager
        SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
        integrator.setAccuracy(1.0e-3);

        ForceReporter *forces = new ForceReporter(&osimModel);  
        osimModel.updAnalysisSet().adoptAndAppend(forces);
        Manager manager(osimModel, integrator);
    
        //Examine the model
        osimModel.printDetailedInfo(si, std::cout);
        // Save the model
        osimModel.print("toyLeg.osim");
        // Print out the initial position and velocity states
        si.getQ().dump("Initial q's");
        si.getU().dump("Initial u's");
        std::cout << "Initial time: " << si.getTime() << std::endl;

        // Integrate
        manager.setInitialTime(t0);
        manager.setFinalTime(tf);
        std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
        manager.integrate(si);

        // Save results
        auto controlsTable = osimModel.getControlsTable();
        STOFileAdapter::write(controlsTable, "SpringActuatedLeg_controls.sto");

        auto statesTable = manager.getStatesTable();
        osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);
        STOFileAdapter::write(statesTable, "SpringActuatedLeg_states.sto");

        auto forcesTable = forces->getForcesTable();
        STOFileAdapter::write(forcesTable, "SpringActuatedLeg_forces.sto");
    }
    catch (const std::exception& ex)
    {
        std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
        return 1;
    }

    std::cout << "Exiting" << std::endl;
    return 0;
}
Ejemplo n.º 12
0
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();

    std::cout << "Background EM..." << std::endl;
    emBackground->SetData(backgroundRGBpoints);
    emBackground->SetModels(backgroundModels);
    emBackground->Update();

    // Create image from models (this is for sanity only)
    CreateImageFromModels(emForeground, emBackground);

    std::cout << "Cutting graph..." << std::endl;
    graphCutFilter->SetInputData(this->OriginalImage);
    graphCutFilter->SetSourceSinkMask(this->AlphaMask);
    graphCutFilter->Update();

    std::cout << "Refreshing..." << std::endl;
    this->AlphaMask->ShallowCopy(graphCutFilter->GetOutput());

    graphCutFilter->Modified();
    emForeground->Modified();
    emBackground->Modified();

    this->Refresh();

    std::stringstream ss;
    ss << i << ".jpg";
    writer->SetFileName(ss.str().c_str());
    writer->Write();
    }

  vtkSmartPointer<vtkLookupTable> lookupTable =
    vtkSmartPointer<vtkLookupTable>::New();
  lookupTable->SetNumberOfTableValues(3);
  lookupTable->SetRange(0.0,255.0);
  lookupTable->SetTableValue(0, 0.0, 0.0, 0.0, ImageGraphCut::SINK); //transparent
  lookupTable->SetTableValue(1, 0.0, 0.0, 0.0, ImageGraphCut::ALWAYSSINK); //transparent
  lookupTable->SetTableValue(2, 0.0, 1.0, 0.0, FOREGROUNDALPHA); //opaque and green
  lookupTable->Build();

  vtkSmartPointer<vtkImageMapToColors> mapTransparency =
    vtkSmartPointer<vtkImageMapToColors>::New();
  mapTransparency->SetLookupTable(lookupTable);
  mapTransparency->SetInputData(graphCutFilter->GetOutput());
  mapTransparency->PassAlphaToOutputOn();

  this->MaskActor->SetInputData(mapTransparency->GetOutput());

  this->RightRenderer->AddActor(this->MaskActor);
  this->Refresh();
}
Ejemplo n.º 13
0
void scene::displayModel(Model activeModel, Shader shader)
{
	activeModel.draw(shader);
}
void RefractionCalibration::setModel(const Model &model) {
	setModel(model, FixedParams(model.size(), false));
}
Ejemplo n.º 15
0
void calcularCapsaMinimaContenidora2() {
	first2 = false;
	const int &tam = m.vertices().size();
	const Vertex *v;
	const Face &f = m.faces()[0];
	v = &m.vertices()[f.v[0]];
	xmax = xmin = (*v);
	ymax = ymin = *(v+1);
	zmax = zmin = *(v+2);
	for (int i = 0; i < tam; i+=3) {
	       if (m.vertices()[i] > xmax) xmax = m.vertices()[i];
	       if (m.vertices()[i+1] > ymax) ymax = m.vertices()[i+1];
	       if (m.vertices()[i+2] > zmax) zmax = m.vertices()[i+2];
	       if (m.vertices()[i] < xmin) xmin = m.vertices()[i];
	       if (m.vertices()[i+1] < ymin) ymin = m.vertices()[i+1];
	       if (m.vertices()[i+2] < zmin) zmin = m.vertices()[i+2];
	}
	centrox2 = (xmax + xmin)/2.;
	centroy2 = (ymax + ymin)/2.;
	centroz2 = (zmax + zmin)/2.;
	
	tamx2 = xmax - xmin;			//tamx = ancho
	tamy2 = ymax - ymin;			//tamy = alto
	tamz2 = zmax - zmin;			//tamz = profundo

	diametro2 = sqrt((tamx2*tamx2) + (tamy2*tamy2) + (tamz2*tamz2));
	
	if (tamx2 >= tamy2 and tamx2 >= tamz2) escalado2 = tamanyQueVolem2/tamx2;
	else if (tamy2 >= tamx2 and tamy2 >= tamz2) escalado2 = tamanyQueVolem2/tamy2;
	else if (tamz2 >= tamx2 and tamz2 >= tamy2) escalado2 = tamanyQueVolem2/tamz2;
	//escalado2 = tamanyQueVolem2/dimensionMasGrande

	subirBase2 = tamanyQueVolem2/2.;

	ancho_escalado2 = tamx2*escalado2;
	alto_escalado2 = tamy2*escalado2;
	profundo_escalado2 = tamz*escalado2;
}
Ejemplo n.º 16
0
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);
                }
            }
        }
    }
}
Ejemplo n.º 17
0
int main() {
	sf::ContextSettings Settings;
	Settings.depthBits = 24; // Request a 24 bits depth buffer
	Settings.stencilBits = 8;  // Request a 8 bits stencil buffer
	Settings.antialiasingLevel = 2;  // Request 2 levels of antialiasing
	sf::Window window(sf::VideoMode(WNDW_WIDTH, WNDW_HEIGHT, 32), APP_NAME, sf::Style::Close, Settings);
	window.setKeyRepeatEnabled(false); // not count key holding press

	if (!init()) exit(EXIT_FAILURE);

	if (!K.init()) KinectOn = false;
	M.init();

	std::cout << "LOADING OK" << std::endl;

	sf::Clock clock;
	sf::Time elapsed;

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					window.close();
					break;
				case sf::Event::KeyPressed:
					switch (event.key.code) {
						case sf::Keyboard::Num1: M.increaseRotation(1, 0.0f, 0.0f); break;
						case sf::Keyboard::Num2: M.increaseRotation(-1, 0.0f, 0.0f); break;
						case sf::Keyboard::Num3: M.increaseRotation(0.0f, 1.0f, 0.0f); break;
						case sf::Keyboard::Num4: M.increaseRotation(0.0f, -1.0f, 0.0f); break;
						case sf::Keyboard::Num5: M.increaseRotation(0.0f, 0.0f, 1.0f); break;
						case sf::Keyboard::Num6: M.increaseRotation(0.0f, 0.0f, -1.0f); break;
						case sf::Keyboard::P: K.playRecord(); break;
						case sf::Keyboard::R: K.record(); break;
						case sf::Keyboard::S: K.stopRecord(); break;
						case sf::Keyboard::Z: M.setShocked(); break;
						case sf::Keyboard::X: M.undoShocked(); break;
						case sf::Keyboard::Escape: window.close(); break;
						default: break;
					}
					break;
				default:
					break;
			}				
		}

		elapsed = clock.getElapsedTime();
		if (elapsed.asSeconds() > 1.0 / 30) { // 30 fps = 1.0/60
			window.setActive();
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			if (KinectOn) {
				K.update();
				if (K.IsTracked()) {
					FLOAT* sc = K.GetScale();
					FLOAT* rot = K.GetRotation();
					FLOAT* trans = K.GetTranslation();
					FLOAT* AU = K.GetAnimationUnits();
					UINT* numAU = K.GetNumAU();
					FLOAT* SU = K.GetShapeUnits();
					UINT* numSU = K.GetNumSU();
					M.registerResult(sc, rot, trans, AU, numAU, SU, numSU);
				}
				else M.stopAnimation();
			}
			M.update();
			K.render();
			M.render();
			window.display();
		}
	}

	return 0;
}
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;
}
Ejemplo n.º 19
0
/*
 * Setup OpenGL
 *
 * Set up GLFW and GLEW, opens a window.
 */
void
SetupOpenGL()
{
    if (!glfwInit()) {
        std::cerr << "Failed to initialize GLFW." << std::endl;
        exit(1);
    }
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    s_window = glfwCreateWindow(1024, 768, "Bullet + OpenGL", nullptr, nullptr);

    if (s_window == nullptr) {
        std::cerr << "Failed to open GLFW window." << std::endl;
        glfwTerminate();
        exit(1);
    }
    glfwMakeContextCurrent(s_window);
    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK) {
        std::cerr << "Failed to initialize GLEW." << std::endl;
        glfwTerminate();
        exit(1);
    }
    glfwSetInputMode(s_window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(s_window, 1024/2, 768/2);

    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_CULL_FACE);

    glGenVertexArrays(1, &s_vertexArrayId);
    glBindVertexArray(s_vertexArrayId);

    s_model = LoadModelFromObjFile("../res/textures/cube.obj");

    glGenBuffers(1, &s_vertexBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, s_vertexBufferId);
    glBufferData(GL_ARRAY_BUFFER, s_model.vertices().size() * sizeof(glm::vec3),
                  &s_model.vertices()[0], GL_STATIC_DRAW);

    glGenBuffers(1, &s_uvCoordBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, s_uvCoordBufferId);
    glBufferData(GL_ARRAY_BUFFER, s_model.uvCoords().size() * sizeof(glm::vec2),
                 &s_model.uvCoords()[0], GL_STATIC_DRAW);

    glGenBuffers(1, &s_normalBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, s_normalBufferId);
    glBufferData(GL_ARRAY_BUFFER, s_model.normals().size() * sizeof(glm::vec3),
                 &s_model.normals()[0], GL_STATIC_DRAW);

    LoadShaders("../res/shaders/vertex.glsl", "../res/shaders/fragment.glsl");
    s_mvpMatrixId = glGetUniformLocation(s_programId, "mvpMatrix");
    s_modelMatrixId = glGetUniformLocation(s_programId, "modelMatris");
    s_viewMatrixId = glGetUniformLocation(s_programId, "modelMatrix");

    s_textureId = LoadDDS("../res/textures/uvmap.DDS");
    s_uniformTextureId = glGetUniformLocation(s_programId, "myTextureSampler");

    glUseProgram(s_programId);
    s_lightPositionId = glGetUniformLocation(s_programId, "lightPosition_worldspace");
    s_lightColorId = glGetUniformLocation(s_programId, "lightColor");
    s_lightPowerId = glGetUniformLocation(s_programId, "lightPower");
}
int main()
{
    // Load data
    std::string fileName = getAbsModelPath("icub_sensorised.urdf");
    Model fullModel = getModel(fileName);
    SensorsList fullSensors = getSensors(fileName);

    // Store data for a given FT sensor
    DataFT dataFT_l_leg;
    dataFT_l_leg.jointName = "l_leg_ft_sensor";
    // Links
    dataFT_l_leg.parent_linkName = "l_hip_2";
    dataFT_l_leg.child_linkName = "l_hip_3";
    dataFT_l_leg.grandparent_linkName = "l_hip_1";
    dataFT_l_leg.grandchild_linkName = "l_upper_leg";
    // Joints
    dataFT_l_leg.grandparentToParent_jointName = "l_hip_roll";
    dataFT_l_leg.childToGranchild_jointName = "l_hip_yaw";

    // Get all the iCub joints
    vector<string> fullJoints = get_iCubJointsSensorised();

    // Keep only one FT
    vector<string> removedJoints;
    removedJoints.push_back("r_leg_ft_sensor");
    removedJoints.push_back("l_foot_ft_sensor");
    removedJoints.push_back("r_foot_ft_sensor");
    removedJoints.push_back("l_arm_ft_sensor");
    removedJoints.push_back("r_arm_ft_sensor");
    vector<string> fullJoints_1FT = removeJoints(fullJoints, removedJoints);

    // Setup the experiments
    // ---------------------

    // 1) The reduced model doesn't lump links which the FT is connected
    ExperimentFT test_defaultModel;
    test_defaultModel.dataFT = dataFT_l_leg;
    test_defaultModel.expectedFirstLinkName = dataFT_l_leg.parent_linkName;
    test_defaultModel.expectedSecondLinkName = dataFT_l_leg.child_linkName;

    // 2) The reduced model doesn't contain the firstLink
    ExperimentFT test_removeFirstLink;
    test_removeFirstLink.dataFT = dataFT_l_leg;
    test_removeFirstLink.removedJoints.push_back(test_removeFirstLink.dataFT.grandparentToParent_jointName);
    test_removeFirstLink.expectedFirstLinkName = dataFT_l_leg.grandparent_linkName;
    test_removeFirstLink.expectedSecondLinkName = dataFT_l_leg.child_linkName;

    // 3) The reduced model doesn't contain the secondLink
    ExperimentFT test_removeSecondLink;
    test_removeSecondLink.dataFT = dataFT_l_leg;
    test_removeSecondLink.removedJoints.push_back(test_removeSecondLink.dataFT.childToGranchild_jointName);
    test_removeSecondLink.expectedFirstLinkName = dataFT_l_leg.parent_linkName;
    test_removeSecondLink.expectedSecondLinkName = dataFT_l_leg.child_linkName;

    // 3) The reduced model doesn't contain both firstLink and secondLink
    ExperimentFT test_removeFirstAndSecondLink;
    test_removeFirstAndSecondLink.dataFT = dataFT_l_leg;
    test_removeFirstAndSecondLink.removedJoints.push_back(test_removeFirstAndSecondLink.dataFT.grandparentToParent_jointName);
    test_removeFirstAndSecondLink.removedJoints.push_back(test_removeFirstAndSecondLink.dataFT.childToGranchild_jointName);
    test_removeFirstAndSecondLink.expectedFirstLinkName = dataFT_l_leg.grandparent_linkName;
    test_removeFirstAndSecondLink.expectedSecondLinkName = dataFT_l_leg.child_linkName;

    // Group all the experiments together
    vector<ExperimentFT> experiments;
    experiments.push_back(test_defaultModel);
    experiments.push_back(test_removeFirstLink);
    experiments.push_back(test_removeSecondLink);
    experiments.push_back(test_removeFirstAndSecondLink);

    for (auto experiment : experiments)
    {
        bool ok;

        Model reducedModel;
        SensorsList reducedSensors;

        ok = createReducedModelAndSensors(fullModel,
                                          fullSensors,
                                          removeJoints(fullJoints_1FT, experiment.removedJoints),
                                          reducedModel,
                                          reducedSensors);
        ASSERT_IS_TRUE(ok);
        ASSERT_EQUAL_DOUBLE(reducedSensors.getNrOfSensors(SIX_AXIS_FORCE_TORQUE), 1);

        Sensor* s = reducedSensors.getSensor(SIX_AXIS_FORCE_TORQUE, 0);
        ASSERT_IS_TRUE(s != nullptr);
        ASSERT_IS_TRUE(s->isValid());

        JointSensor* jointSens = dynamic_cast<JointSensor*>(s);
        ASSERT_IS_TRUE(jointSens != nullptr);

        unique_ptr<SixAxisForceTorqueSensor> sensorCopy;
        sensorCopy.reset(static_cast<SixAxisForceTorqueSensor*>(jointSens->clone()));
        ASSERT_IS_TRUE(sensorCopy != nullptr);

        printFT(*sensorCopy);
        cout << endl;

        ASSERT_EQUAL_STRING(sensorCopy->getFirstLinkName(), experiment.expectedFirstLinkName);
        ASSERT_EQUAL_STRING(sensorCopy->getSecondLinkName(), experiment.expectedSecondLinkName);

        // Test transform
        // --------------

        // Get the transform from the fixed joint.
        // It uses the createReducedModel() logic. It is used as ground truth.
        Transform parent_H_child;
        auto jointFT = reducedModel.getJoint(reducedModel.getJointIndex(experiment.dataFT.jointName));
        parent_H_child = jointFT->getRestTransform(jointFT->getFirstAttachedLink(),
                                                   jointFT->getSecondAttachedLink());

        // Get the transform from the sensor.
        // This is calculated by createReducedModelAndSensors() and it is the method under test.
        LinkIndex firstLinkIndex = sensorCopy->getFirstLinkIndex();
        LinkIndex secondLinkIndex = sensorCopy->getSecondLinkIndex();
        Transform firstLink_H_sensorFrame;
        Transform secondLink_H_sensorFrame;
        ok = true;
        ok = ok && sensorCopy->getLinkSensorTransform(firstLinkIndex,  firstLink_H_sensorFrame);
        ok = ok && sensorCopy->getLinkSensorTransform(secondLinkIndex, secondLink_H_sensorFrame);
        ASSERT_IS_TRUE(ok);

        ASSERT_EQUAL_TRANSFORM(parent_H_child,
                               firstLink_H_sensorFrame*secondLink_H_sensorFrame.inverse());
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 21
0
int
main()
{
    SetupOpenGL();

    std::unique_ptr<btBroadphaseInterface> broadphase { new btDbvtBroadphase };
    std::unique_ptr<btDefaultCollisionConfiguration> collisionConfiguration {
        new btDefaultCollisionConfiguration
    };
    std::unique_ptr<btCollisionDispatcher> dispatcher { new btCollisionDispatcher {
        collisionConfiguration.get()
    } };
    std::unique_ptr<btSequentialImpulseConstraintSolver> solver {
        new btSequentialImpulseConstraintSolver
    };
    std::unique_ptr<btDiscreteDynamicsWorld> dynamicsWorld { new btDiscreteDynamicsWorld {
        dispatcher.get(), broadphase.get(), solver.get(), collisionConfiguration.get()
    } };
    dynamicsWorld->setGravity(btVector3 { 0, -10, 0 });
    std::unique_ptr<btCollisionShape> groundShape {
        new btStaticPlaneShape { btVector3 { 0, 1, 0 }, 1 }
    };
    std::unique_ptr<btSphereShape> fallShape { new btSphereShape { 1 } };
    std::unique_ptr<btDefaultMotionState> groundMotionState { new btDefaultMotionState {
        btTransform { btQuaternion { 0, 0, 0, 1 }, btVector3 { 0, -1, 0 } }
    } };
    btRigidBody::btRigidBodyConstructionInfo groundRigidBodyConstructionInfo {
        0, groundMotionState.get(), groundShape.get(), btVector3 { 0, 0, 0 }
    };
    std::unique_ptr<btRigidBody> groundRigidBody { new btRigidBody {
        groundRigidBodyConstructionInfo
    } };

    dynamicsWorld->addRigidBody(groundRigidBody.get());

    std::unique_ptr<btDefaultMotionState> fallMotionState { new btDefaultMotionState {
        btTransform { btQuaternion { 0, 0, 0, 1 }, btVector3 { 0, 50, 0 } }
    } };
    btScalar mass { 1 };
    btVector3 fallInertia { 0, 0, 0 };

    fallShape->calculateLocalInertia(mass, fallInertia);

    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyConstructionInfo {
        mass, fallMotionState.get(), fallShape.get(), fallInertia
    };
    std::unique_ptr<btRigidBody> fallRigidBody { new btRigidBody {
        fallRigidBodyConstructionInfo
    } };

    dynamicsWorld->addRigidBody(fallRigidBody.get());

    glm::mat4 projectionMatrix = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
    glm::mat4 viewMatrix;
    glm::mat4 modelMatrix;
    glm::mat4 mvp;
    glm::vec3 lightPosition { 3, 3, 3 };
    glm::vec3 lightColor { 1, 1, 1 };
    float lightPower { 50.0f };

    btTransform transformation;

    double currentTime, lastTime = glfwGetTime();
    double fps { 0.0 };
    size_t nFrames { 0l };

    do {
        dynamicsWorld->stepSimulation(1 / 60.0f, 10);
        fallRigidBody->getMotionState()->getWorldTransform(transformation);

        ProcessInputs();
        modelMatrix = glm::translate(glm::mat4 { 1.0f }, glm::vec3 {
            transformation.getOrigin().getX(),
            transformation.getOrigin().getY(),
            transformation.getOrigin().getZ()
        });
        viewMatrix = glm::lookAt(
            s_position,
            s_position + s_direction,
            s_up
        );
        mvp = projectionMatrix * viewMatrix * modelMatrix;

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glUseProgram(s_programId);
        glUniformMatrix4fv(s_mvpMatrixId, 1, GL_FALSE, &mvp[0][0]);
        glUniformMatrix4fv(s_modelMatrixId, 1, GL_FALSE, &modelMatrix[0][0]);
        glUniformMatrix4fv(s_viewMatrixId, 1, GL_FALSE, &viewMatrix[0][0]);
        glUniform3f(s_lightPositionId, lightPosition.x, lightPosition.y, lightPosition.z);
        glUniform3f(s_lightColorId, lightColor.x, lightColor.y, lightColor.z);
        glUniform1f(s_lightPowerId, lightPower);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, s_textureId);
        glUniform1i(s_uniformTextureId, 0);

        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, s_vertexBufferId);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, s_uvCoordBufferId);
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);

        glEnableVertexAttribArray(2);
        glBindBuffer(GL_ARRAY_BUFFER, s_normalBufferId);
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

        glDrawArrays(GL_TRIANGLES, 0, s_model.vertices().size());

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(2);

        currentTime = glfwGetTime();
        ++nFrames;
        if (currentTime - lastTime > 1.0) {
            fps = 1000.0/nFrames;
            nFrames = 0;
            lastTime += 1.0;
        }
        ShowStatus(transformation.getOrigin().getY(), fps);

        glfwSwapBuffers(s_window);
        glfwPollEvents();
    } while (glfwGetKey(s_window, GLFW_KEY_ESCAPE) != GLFW_PRESS
             && glfwGetKey(s_window, GLFW_KEY_Q) != GLFW_PRESS
             && glfwWindowShouldClose(s_window) == 0);
    dynamicsWorld->removeRigidBody(fallRigidBody.get());
    dynamicsWorld->removeRigidBody(groundRigidBody.get());
    CleanupOpenGL();

    return 0;
}
/*
 * Checks that all ids on KineticLawParameters are unique.
 */
void
UniqueVarsInRules::doCheck (const Model& m)
{
  for (unsigned int n = 0; n < m.getNumRules(); ++n) checkId( *m.getRule(n) );
}
Ejemplo n.º 23
0
int main() {
    Model model;
    model.setName("bicep_curl");
#ifdef VISUALIZE
    model.setUseVisualizer(true);
#endif

    // Create two links, each with a mass of 1 kg, center of mass at the body's
    // origin, and moments and products of inertia of zero.
    OpenSim::Body* humerus = new OpenSim::Body("humerus", 1, Vec3(0), Inertia(0));
    OpenSim::Body* radius  = new OpenSim::Body("radius",  1, Vec3(0), Inertia(0));

    // Connect the bodies with pin joints. Assume each body is 1 m long.
    PinJoint* shoulder = new PinJoint("shoulder",
            // Parent body, location in parent, orientation in parent.
            model.getGround(), Vec3(0), Vec3(0),
            // Child body, location in child, orientation in child.
            *humerus, Vec3(0, 1, 0), Vec3(0));
    PinJoint* elbow = new PinJoint("elbow",
            *humerus, Vec3(0), Vec3(0), *radius, Vec3(0, 1, 0), Vec3(0));

    // Add a muscle that flexes the elbow.
    Millard2012EquilibriumMuscle* biceps = new
        Millard2012EquilibriumMuscle("biceps", 200, 0.6, 0.55, 0);
    biceps->addNewPathPoint("origin",    *humerus, Vec3(0, 0.8, 0));
    biceps->addNewPathPoint("insertion", *radius,  Vec3(0, 0.7, 0));

    // Add a controller that specifies the excitation of the muscle.
    PrescribedController* brain = new PrescribedController();
    brain->addActuator(*biceps);
    // Muscle excitation is 0.3 for the first 0.5 seconds, then increases to 1.
    brain->prescribeControlForActuator("biceps",
            new StepFunction(0.5, 3, 0.3, 1));

    // Add components to the model.
    model.addBody(humerus);    model.addBody(radius);
    model.addJoint(shoulder);  model.addJoint(elbow);
    model.addForce(biceps);
    model.addController(brain);

    // Add a console reporter to print the muscle fiber force and elbow angle.
    ConsoleReporter* reporter = new ConsoleReporter();
    reporter->set_report_time_interval(1.0);
    reporter->addToReport(biceps->getOutput("fiber_force"));
    reporter->addToReport(
        elbow->getCoordinate(PinJoint::Coord::RotationZ).getOutput("value"),
        "elbow_angle");
    model.addComponent(reporter);

    // Add display geometry.
    Ellipsoid bodyGeometry(0.1, 0.5, 0.1);
    bodyGeometry.setColor(Gray);
    // Attach an ellipsoid to a frame located at the center of each body.
    PhysicalOffsetFrame* humerusCenter = new PhysicalOffsetFrame(
        "humerusCenter", *humerus, Transform(Vec3(0, 0.5, 0)));
    humerus->addComponent(humerusCenter);
    humerusCenter->attachGeometry(bodyGeometry.clone());
    PhysicalOffsetFrame* radiusCenter = new PhysicalOffsetFrame(
        "radiusCenter", *radius, Transform(Vec3(0, 0.5, 0)));
    radius->addComponent(radiusCenter);
    radiusCenter->attachGeometry(bodyGeometry.clone());

    // Configure the model.
    State& state = model.initSystem();
    // Fix the shoulder at its default angle and begin with the elbow flexed.
    shoulder->getCoordinate().setLocked(state, true);
    elbow->getCoordinate().setValue(state, 0.5 * Pi);
    model.equilibrateMuscles(state);

    // Configure the visualizer.
#ifdef VISUALIZE
    model.updMatterSubsystem().setShowDefaultGeometry(true);
    Visualizer& viz = model.updVisualizer().updSimbodyVisualizer();
    viz.setBackgroundType(viz.SolidColor);
    viz.setBackgroundColor(White);
#endif

    // Simulate.
    simulate(model, state, 10.0);

    return 0;
};
Ejemplo n.º 24
0
	void SetOptimizationPdvsAndAdvs(
			Optimizer * aOptimizer,
			Problem   * aProblem )
{
//	UInt modelId = 1;
//	Model* model = aProblem->GetModelById( 1 );
//	Mesh* mesh = model->GetMesh();
//
//	model->BuildNodeToElementTable();
//
//	// Vars for creating PDVs
//	DesignDepObject desDepObj = NOD_PROP;
//	UInt propId = 11;
//	int propType = NP_LS;
//
//	UInt myNumNodesInSet = model->GetNumNodes();
//
//	// ------------------------------------------------------------------------
//	std::vector < UInt > &DesVarKeys = aOptimizer->GetMyDesVarKeys();
//
//	DesVarKeys.assign( myNumNodesInSet, 0 );
//
//	for ( UInt in = 0; in < myNumNodesInSet; ++in )
//		DesVarKeys[in] = model->GetNode( in )->GetIdNum();
//
//	// Set the number of design variables per processor
//	aOptimizer->FinalizeDesVarCreation();
//
//	// ------------------------------------------------------------------------
//	// Create PDVs
//	std::vector < UInt > globalNodesIds( myNumNodesInSet, 0 );
//	for ( UInt in = 0; in < myNumNodesInSet; ++in )
//		globalNodesIds[in] = model->GetNode( in )->GetIdNum();
//
//	UInt *ElemIndices = NULL, *ElemIds = NULL;
//	UInt numLoadElems = 0;
//
//	// Initialize a ParseModelHelper
//	ParseModelHelper parseModelHelper = ParseModelHelper();
//
//	// Kill filter in inflow and outflow.
//	std::vector< UInt > noFilterNodeIds;
//
//	numLoadElems = parseModelHelper.GetSideSetNeighborElemsInfoByID( mesh, sSSetIds[sLoadNSSetIndx], ElemIndices, ElemIds );
//	for ( UInt ie = 0; ie < numLoadElems; ++ie ) {
//		std::vector < UInt > NodeIdsVec( FP_MAX_NODES, 0 );
//		Element* elem = model->GetElement( ElemIndices[ie] );
//		UInt numNodes = elem->GetNodeIds( &NodeIdsVec[0] );
//
//		for ( UInt in = 0; in < numNodes; ++in ) {
//			noFilterNodeIds.push_back( NodeIdsVec[in] );
//		}
//	}
//
//	FemdocAlgorithms::SortUniqueResizeStdVector( noFilterNodeIds );
//
//	// Read file
//	std::string line;
//	std::ifstream myfile ( "disttable" );
//
//	if ( myfile.is_open() )
//	{
//		std::fprintf( stdout, "\n ... Reading PDVs file\n" );
//		while ( myfile.good() )
//		{
//			getline( myfile, line );
//
//			//          char* lineChar = new char[line.size() + 1];
//			//          lineChar[line.size()] = 0;
//			//          memcpy( lineChar, line.c_str(), line.size() );
//
//			const char* lineChar = line.c_str();
//
//			Real test1 = 0.0;
//			Real test2 = 0.0;
//
//			std::sscanf( lineChar, "%lf %lf",  &test1, &test2 );
//			UInt glbNodeId = test1;
//			UInt numNeigb = test2;
//
//			assert( numNeigb > 0 );
//
//			if ( std::find( &globalNodesIds[0], &globalNodesIds[0] + myNumNodesInSet, glbNodeId ) - &globalNodesIds[0] != myNumNodesInSet )
//			{
//				Node* node = model->GetNodeById( glbNodeId );
//
//				std::vector < UInt > neigbIdsVec ( ( UInt ) numNeigb , 0.0 );
//				std::vector < Real > neigbWgtVec ( ( UInt ) numNeigb , 0.0 );
//
//				if ( node )
//				{
//					// If found in no filter IDs.
//					if ( std::find( &noFilterNodeIds[0], &noFilterNodeIds[0] + ( UInt ) noFilterNodeIds.size(), glbNodeId ) - &noFilterNodeIds[0] != ( UInt ) noFilterNodeIds.size() ) {
//						UInt numEntries[] = {1,0};
//
//						neigbIdsVec[0] = glbNodeId - 1;
//						neigbWgtVec[0] = 1.0;
//
//						UInt paramIndex = 0;
//						UInt propTypeKey = node->GetIndexNum();
//						PhysicalDesignVar* pdv = aOptimizer->CreatePhysDesVar( aProblem, modelId, desDepObj, propId, propType, propTypeKey, paramIndex );
//
//						Function* PDVEvalFunc = new FunctionScalarProduct( numEntries, &neigbWgtVec[0] );
//						pdv->CreateEvaluationFunction( PDVEvalFunc, &neigbIdsVec[0] );
//					}
//					else {
//						Real neighborIds = 0;
//						Real neighborWgt = 0;
//						UInt position = 28;
//						for ( UInt ii = 0; ii < numNeigb; ii++ )
//						{
//							std::sscanf( lineChar + position,"%lf",&neighborIds );
//							neigbIdsVec[ii] = neighborIds - 1;
//							position += 14;
//						}
//						for ( UInt ii = 0; ii < numNeigb; ii++ )
//						{
//							std::sscanf( lineChar + position,"%lf",&neighborWgt );
//							neigbWgtVec[ii] = neighborWgt;
//							position += 14;
//						}
//
//						UInt numEntries[] = {numNeigb, 0};
//						UInt paramIndex = 0;
//						UInt propTypeKey = node->GetIndexNum();
//						PhysicalDesignVar* pdv = aOptimizer->CreatePhysDesVar( aProblem, modelId, desDepObj, propId, propType, propTypeKey, paramIndex );
//
//						Function* PDVEvalFunc = new FunctionScalarProduct( numEntries, &neigbWgtVec[0] );
//						pdv->CreateEvaluationFunction( PDVEvalFunc, &neigbIdsVec[0] );
//					}
//				}
//			}
//		}
//	}
//	else
//	{
//		std::fprintf( stdout, " Unable to open file!!!\n" );
//	}

	// Set number of abstract design variables (radius)
	UInt modelId = 1;
	UInt numAbsDesVar   = 1;
	UInt AbsDesVarInd[] = {0};
	// ------------------------------------------------------------------------
	// Set number of abstract design variables
    aOptimizer->SetNumDesVars(numAbsDesVar);

    // ------------------------------------------------------------------------
    // Create PDV's
    DesignDepObject desDepObj = NOD_PROP;
    UInt propId   = 11;
    Int  propType = NP_LS;
    PhysicalDesignVar* pdv = NULL;

    // Create optimizer sweep function
	UInt numParameters[] = { 1, 1 };					// number of coefficients and independent variables
	Real ParameterVals[] = { 0.0 };	// radius and center of circle

	Real CntrXGlbCoords = sCenterX;
	Real CntrYGlbCoords = sCenterY;
	Real CntrZGlbCoords = sCenterZ;

	Model* model = aProblem->GetModelById(modelId);
	UInt numNodes = model->GetNumNodes();

	model->BuildNodeToElementTable();

	Node* node = NULL;
	Real NodeXGlbCoords = 0.0;
	Real NodeYGlbCoords = 0.0;
	Real NodeZGlbCoords = 0.0;

	for ( UInt in = 0; in < numNodes; ++in )
	{
		node = model->GetNode(in);
		NodeXGlbCoords = node->GetGlobalXCoord();
		NodeYGlbCoords = node->GetGlobalYCoord();
		NodeZGlbCoords = node->GetGlobalZCoord();

		Real distance = std::sqrt( std::pow((NodeXGlbCoords-CntrXGlbCoords),2) + std::pow((NodeYGlbCoords-CntrYGlbCoords),2) + std::pow((NodeZGlbCoords-CntrZGlbCoords),2));
		ParameterVals[0] = distance;

		// Parameters for moving circle will be [distance, xcoords of node, ycoords of node, zcoords of node]

		pdv = aOptimizer->CreatePhysDesVar(aProblem,modelId,desDepObj,propId,propType,node->GetIndexNum());
		Function* SweepFunc = new FunctionUserDefined(numParameters,ParameterVals,mySweepFunc,mySweepFuncDeriv);
		pdv->CreateEvaluationFunction(SweepFunc,AbsDesVarInd);
	}
}
Ejemplo n.º 25
0
void Renderer::render( Scene* toRender )
{
    glClearColor(1.0f,0.8f,0.8f,1.0f);
    Program::checkGLErrors( "glClearColor" );
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    Program::checkGLErrors( "glClear" );


    glm::mat4 mv, mvp;
    glm::mat3 rot, normal;
    
    ModelData data;
    Model model;
    Material mat;
    Program* shader;

    std::vector<DisplayObject> objects = toRender->getDisplayObjects();

    for(int i = 0; i < objects.size(); i++)
    {
        model = objects[i].getModel();

        for(int j = 0; j < model.numMeshes(); j++)
        {

            //Doesn't work ;_;
            //mat = *(objects[i].getMaterial( model.getMeshInfo(j).matIndex ));
            
            if(objects[i].customMatAvailable)
                mat = (objects[i].getMaterial(0));
            else
                mat = model.materials[ model.getMeshInfo(j).matIndex ];

            shader = mat.shader;

            setActiveProgram( shader );
            Program::checkGLErrors( "Setting active program" );

            glBindVertexArray( model.getVAO( j ) );
            Program::checkGLErrors("Binding vertex array");
            glBindTexture( GL_TEXTURE_2D, mat.texDiffuse );
            Program::checkGLErrors( "Binding texture" );
            
            //Update uniforms just loads the constant uniforms, e.g. Ld and stuff.
            updateUniforms( objects[i] );
            
            glDrawElements(GL_TRIANGLES, model.getMeshInfo(j).numIndices, GL_UNSIGNED_INT, NULL); 

            if( objects[i].renderBoundingBox )
            {
                setActiveProgram( simplePr );
                glBindVertexArray( bBoxVao );
                glBindTexture( GL_TEXTURE_2D, 0 );
                glBindBuffer( GL_ARRAY_BUFFER, model.getMeshInfo( j ).boundingBoxBuffer );
                //When you finally fix updateUniforms such that it isn't horrible, make sure to give a way to only send the mvp matrix in, so we can delete this line
                glm::mat4 mv = projection * (camera * objects[i].getTransform());
                glUniformMatrix4fv(activeProgram->getUniform("mvp"), 1, GL_FALSE, glm::value_ptr(mv) );

                glVertexAttribPointer( simplePr->getAttrib("theV"),3,GL_FLOAT,0,0,0);
                glEnableVertexAttribArray(simplePr->getAttrib("theV"));
                glDrawElements(GL_LINE_STRIP,20, GL_UNSIGNED_INT, NULL); 

            }

        }

        glBindVertexArray( 0 );
        glBindTexture( GL_TEXTURE_2D, 0 );

        setActiveProgram( 0 );
    }
    glFlush();
    Program::checkGLErrors("Post render");

}