BoundingBox  ComposedEntity::getAbsoluteBoundingBox()
{
	//check if some of the contained solid objects have to update their bounding box
	if(boxNeedToBeUpdated)computeBoundingBox();
	return SolidEntity::getAbsoluteBoundingBox();

}
示例#2
0
MolecularOrbitals::MolecularOrbitals(unsigned const nAlpha, unsigned const nBeta, 
   QList<double> const& alphaCoefficients, QList<double> const& alphaEnergies,  
   QList<double> const& betaCoefficients, QList<double> const& betaEnergies,
   ShellList const& shells) : m_nAlpha(nAlpha), m_nBeta(nBeta), 
   m_alphaEnergies(alphaEnergies), m_betaEnergies(betaEnergies), m_shellList(shells)
{
   m_nOrbitals = m_alphaEnergies.size();
   m_nBasis    = alphaCoefficients.size()/m_nOrbitals;

   if (alphaCoefficients.size() != (int)m_nOrbitals*(int)m_nBasis ||
       betaCoefficients.size()  != (int)m_nOrbitals*(int)m_nBasis) {
      m_nOrbitals = 0;
      return;
   }

   m_alphaCoefficients.resize(m_nOrbitals, m_nBasis);
   unsigned ka(0);
   for (unsigned i = 0; i < m_nOrbitals; ++i) {
       for (unsigned j = 0; j < m_nBasis; ++j, ++ka) {
           m_alphaCoefficients(i,j) = alphaCoefficients[ka];
       }
   }
 
   m_betaCoefficients.resize(m_nOrbitals, m_nBasis);
   unsigned kb(0);
   for (unsigned i = 0; i < m_nOrbitals; ++i) {
       for (unsigned j = 0; j < m_nBasis; ++j, ++kb) {
           m_betaCoefficients(i,j) = betaCoefficients[kb];
       }
   }

   m_restricted = (m_nAlpha == m_nBeta) && (m_alphaEnergies == m_betaEnergies);
   computeBoundingBox();
}
示例#3
0
void computeBoundingBox(const PCPtr& cloud, PCXYZ& min, PCXYZ& max)
{
	ofVec3f vMin, vMax;
	computeBoundingBox(cloud, vMin, vMax);
	min = OFVEC3F_PCXYZ(vMin);
	max = OFVEC3F_PCXYZ(vMax);
}
示例#4
0
	void PCModelObject::setCloud(const PCPtr& nuCloud)
	{
		cloud = nuCloud;
		computeBoundingBox(cloud, vMin, vMax);
		setCenter(computeCentroid(cloud));
		cloudScreenCoords = getScreenCoords(cloud);
	}
示例#5
0
void SphereScene::init(){
	if(_loaded){
		return;
	}
	_loaded = true;
	
	// Objects creation.
	Object sphere1(Object::Type::Regular, "sphere", { {"sphere_wood_lacquered_albedo", true }, {"sphere_wood_lacquered_normal", false}, {"sphere_wood_lacquered_rough_met_ao", false}});
	Object sphere2(Object::Type::Regular, "sphere", { {"sphere_gold_worn_albedo", true }, {"sphere_gold_worn_normal", false}, {"sphere_gold_worn_rough_met_ao", false}});
	const glm::mat4 model1 = glm::translate(glm::scale(glm::mat4(1.0f),glm::vec3(0.3f)), glm::vec3(1.2f,0.0f, 0.0f));
	const glm::mat4 model2 = glm::translate(glm::scale(glm::mat4(1.0f),glm::vec3(0.3f)), glm::vec3(-1.2f,0.0f, 0.0f));
	sphere1.update(model1);
	sphere2.update(model2);
	
	objects.push_back(sphere1);
	objects.push_back(sphere2);
	
	// Background creation.
	backgroundReflection = Resources::manager().getCubemap("studio", {GL_RGB32F})->id;
	background = Object(Object::Type::Skybox, "skybox", {}, {{"studio", false }});
	loadSphericalHarmonics("studio_shcoeffs");
	
	// Compute the bounding box of the shadow casters.
	const BoundingBox bbox = computeBoundingBox(true);
	// Lights creation.
	// Create directional light.
	//directionalLights.emplace_back(glm::vec3(-2.0f, -1.5f, 0.0f), glm::vec3(3.0f), bbox);
	// Create point lights.
	pointLights.emplace_back( glm::vec3(0.5f,-0.1f,0.5f), 6.0f*glm::vec3(0.2f,0.8f,1.2f), 0.9f, bbox);
	pointLights.emplace_back( glm::vec3(-0.5f,-0.1f,0.5f), 6.0f*glm::vec3(2.1f,0.3f,0.6f), 0.9f, bbox);
	
}
示例#6
0
RigidObject::RigidObject(std::string model, std::string ver_shader,
                         std::string frag_shader)
    : model((GLchar*)model.c_str()),
      shader((GLchar*)ver_shader.c_str(), (GLchar*)frag_shader.c_str()),
      model_matrix_(),
      is_visible_(true) {
  computeBoundingBox();
}
示例#7
0
void Object::setupObject()
{
	defineVBO();
	defineEBO();
	defineVAO();

	computeBoundingBox();
}
示例#8
0
PixelOrientedOverview::PixelOrientedOverview(TulipGraphDimension *data,
                                             PixelOrientedMediator *pixelOrientedMediator,
                                             Coord blCornerPos, const std::string &dimName,
                                             const Color &backgroundColor, const Color &textColor)
    : data(data), pixelOrientedMediator(pixelOrientedMediator), blCornerPos(blCornerPos),
      dimName(dimName), frame(nullptr), frame2(nullptr), overviewGen(false),
      backgroundColor(backgroundColor), textColor(textColor) {

  if (this->dimName.empty()) {
    this->dimName = data->getDimensionName();
  }

  overviewId = overviewCpt++;

  textureName = dimName + " texture " + getStringFromNumber(overviewId);

  unsigned int width = pixelOrientedMediator->getImageWidth();
  unsigned int height = pixelOrientedMediator->getImageHeight();

  unsigned int labelHeight = height / 4;

  Graph *graph = data->getTulipGraph();
  pixelLayout = new LayoutProperty(graph);
  pixelSize = new SizeProperty(graph);
  graphComposite = new GlGraphComposite(graph);
  setGraphView(graphComposite);
  GlGraphInputData *glGraphInputData = graphComposite->getInputData();
  glGraphInputData->setElementLayout(pixelLayout);
  glGraphInputData->setElementSize(pixelSize);

  frame = new GlRect(Coord(blCornerPos.getX() - 3, blCornerPos.getY() + height + 3),
                     Coord(blCornerPos.getX() + width + 3, blCornerPos.getY() - 3), Color(0, 0, 0),
                     Color(0, 0, 0), false, true);
  addGlEntity(frame, dimName + "frame");
  frame2 = new GlRect(Coord(blCornerPos.getX() - 4, blCornerPos.getY() + height + 4),
                      Coord(blCornerPos.getX() + width + 4, blCornerPos.getY() - 4), Color(0, 0, 0),
                      Color(0, 0, 0), false, true);
  addGlEntity(frame2, dimName + "frame 2");

  backgroundRect = new GlRect(Coord(blCornerPos.getX(), blCornerPos.getY() + height),
                              Coord(blCornerPos.getX() + width, blCornerPos.getY()),
                              Color(255, 255, 255), Color(255, 255, 255), true, false);
  addGlEntity(backgroundRect, "background rect");
  clickLabel = new GlLabel(Coord(blCornerPos.getX() + width / 2, blCornerPos.getY() + height / 2),
                           Size(width, height / 4), Color(0, 0, 0));
  clickLabel->setText("Double Click to generate overview");
  addGlEntity(clickLabel, "label");

  computeBoundingBox();

  overviewLabel =
      new GlLabel(Coord(blCornerPos.getX() + width / 2, blCornerPos.getY() - labelHeight / 2),
                  Size(width, labelHeight), textColor);
  overviewLabel->setText(dimName);
  addGlEntity(overviewLabel, "overview label");
}
bool ComposedEntity::linkToBase(PositionableEntity *p)
{
	if(p==0)return false;
	//if linked... do nothing
	if(p->location.getBase())return false;
	//else directly link
	p->location.linkTo(getReferenciableLocation());
	computeBoundingBox();
return true;
}
示例#10
0
// Computes the enclosing circle of the elements contained in a boolean property.
Circlef getEnclosingCircle(GlGraphInputData *inputData, BooleanProperty *selection) {
    BoundingBox bbox(computeBoundingBox(inputData->getGraph(), inputData->getElementLayout(), inputData->getElementSize(), inputData->getElementRotation(), selection));
    Coord center(bbox.center());
    float norm = (bbox[1] - bbox[0]).norm();
    Circlef result;
    result[0] = center.getX();
    result[1] = center.getY();
    result.radius = norm;
    return result;
}
示例#11
0
void CScene::init (const string& fileName)
{
  m_boundingSpheresMode = false;
  m_selectedItem        = NULL;

  addMaterial(new CMaterial(this));

  cout << "Chargement de la scène " << fileName << endl;
  ObjImporter::import(this,fileName,m_objectsArray);
  computeBoundingBox();
}
示例#12
0
/// \param mesh Specifies the edit mesh to be converted.
/// \note Any part and material information is lost in the conversion.
void	TriMesh::fromEditMesh(const EditTriMesh &mesh) {
	int	i;

	// Make a copy of the mesh

	EditTriMesh tempMesh(mesh);

	// Make sure UV's are perperly set at the vertex level

	tempMesh.copyUvsIntoVertices();

	// Optimize the order of the vertices for best cache performance.
	// This also discards unused vertices

	tempMesh.optimizeVertexOrder();

	// Allocate memory

	allocateMemory(tempMesh.vertexCount(), tempMesh.triCount());

	// Make sure we have something

	if (triCount < 1) {
		return;
	}

	// Convert vertices

	for (i = 0 ; i < vertexCount ; ++i) {
		const EditTriMesh::Vertex *s = &tempMesh.vertex(i);
		RenderVertex *d = &vertexList[i];

		d->p = s->p;
		d->n = s->normal;
		d->u = s->u;
		d->v = s->v;
	}

	// Convert faces

	for (i = 0 ; i < triCount ; ++i) {
		const EditTriMesh::Tri *s = &tempMesh.tri(i);
		RenderTri *d = &triList[i];
		d->index[0] = s->v[0].index;
		d->index[1] = s->v[1].index;
		d->index[2] = s->v[2].index;
	}

	// Make sure bounds are computed

	computeBoundingBox();
}
示例#13
0
void AmbientOcclusionEngine::run()
{
   m_nVertices  = m_vertexData.size()/6;
   m_nTriangles = m_nVertices/3;
   if (m_nTriangles < 1) return;

   computeBoundingBox();
qDebug() << "Computing bounding box min:" << m_boundingBoxOrigin.x  << m_boundingBoxOrigin.y 
                                          << m_boundingBoxOrigin.z  << m_nx << m_ny << m_nz;
qDebug() << "Computing bounding box max:" << m_boundingBoxOrigin.x + m_nx*m_cellLength
                                          << m_boundingBoxOrigin.y + m_ny*m_cellLength
                                          << m_boundingBoxOrigin.z + m_nz*m_cellLength;

   allocateBoxes();
   assignTrianglesToBoxes();

   unsigned nGrid(loadLebedevGrid());
   QList<unsigned> triangles;
   double occlusion;
   Vec v, n, r, z(0.0, 0.0, 1.0);

   // loop over each vertex
   for (unsigned i = 0; i < m_nVertices; ++i) {
       n = normal(i); 
       v = vertex(i); 
       // determine the alignment for the Lebedev grid and z-axis
       Quaternion q(n,z);
       occlusion = 0.0;
      
       // loop over the rays in the grid
       for (unsigned j = 0; j < nGrid; ++j) {
           r = q*m_gridPositions[j];
           triangles = triangleShortList(v, r);
//qDebug() << "Triangle considered " << triangles.size();
           for (int k = 0; k < triangles.size(); ++k) {
               if (rayIntersectsTriangle(v, r, triangles[k])) {
                  //occlusion += m_gridWeights[j];
                  occlusion += 1.0;
                  break;
               }
           }
       }

       m_data.append(1.0-occlusion/nGrid);
   }

   // clean up
   deallocateBoxes();
   qDebug() << "AO finished computing" << m_data.size() << "values for" 
            << m_nVertices << "vertices";
}
示例#14
0
bool ATOM_TerrainPatch::initialize (ATOM_TerrainQuadtree *quadtree, ATOM_TerrainPatch *parent, PatchPosition position, ATOM_VertexArray *baseVertices)
{
	ATOM_STACK_TRACE(ATOM_TerrainPatch::initialize);

	ATOM_ASSERT(quadtree);

	unsigned patchSize = quadtree->getPatchSize ();
	unsigned rootSize = quadtree->getRootSize ();
	float scaleX = quadtree->getScaleX ();
	float scaleZ = quadtree->getScaleZ ();

	_mipLevel = parent ? parent->getMipLevel() + 1 : 0;
	unsigned step = ((rootSize - 1) / (patchSize - 1)) >> _mipLevel;
	unsigned interval = (patchSize - 1) * step;
	unsigned parentOffsetX = parent ? parent->getOffsetX() : 0;
	unsigned parentOffsetZ = parent ? parent->getOffsetZ() : 0;

	switch (position)
	{
	case ATOM_TerrainPatch::LeftTop:
		_offsetX = parentOffsetX;
		_offsetZ = parentOffsetZ;
		break;
	case ATOM_TerrainPatch::RightTop:
		_offsetX = parentOffsetX + interval;
		_offsetZ = parentOffsetZ;
		break;
	case ATOM_TerrainPatch::LeftBottom:
		_offsetX = parentOffsetX;
		_offsetZ = parentOffsetZ + interval;
		break;
	case ATOM_TerrainPatch::RightBottom:
		_offsetX = parentOffsetX + interval;
		_offsetZ = parentOffsetZ + interval;
		break;
	default:
		return false;
	}

	_position = position;
	_quadtree = quadtree;
	_step = step;
	_parent = parent;
	_maxError = computeMaxError ();

	setupVertices (computeSkirtLength (), baseVertices);
	_boxRadius = computeBoundingBox (_boundingBox);

	return true;
}
示例#15
0
void DragonScene::init(){
	if(_loaded){
		return;
	}
	_loaded = true;
	
	//Position fixed objects.
	const glm::mat4 dragonModel = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(-0.1,-0.05,-0.25)),glm::vec3(0.5f));
	const glm::mat4 planeModel = glm::scale(glm::translate(glm::mat4(1.0f),glm::vec3(0.0f,-0.35f,-0.5f)), glm::vec3(2.0f));
	const glm::mat4 suzanneModel = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(0.2,0.0,0.0)),glm::vec3(0.25f));
	
	// Objects creation.
	Object suzanne(Object::Type::Regular, "suzanne", { {"suzanne_texture_color", true }, {"suzanne_texture_normal", false}, {"suzanne_texture_rough_met_ao", false} });
	Object dragon(Object::Type::Regular, "dragon", { { "dragon_texture_color", true }, { "dragon_texture_normal", false }, { "dragon_texture_rough_met_ao", false } });
	Object plane(Object::Type::Parallax, "groundplane", { { "groundplane_texture_color", true }, { "groundplane_texture_normal", false }, { "groundplane_texture_rough_met_ao", false }, { "groundplane_texture_depth", false } }, {}, false);
	
	suzanne.update(suzanneModel);
	dragon.update(dragonModel);
	plane.update(planeModel);
	
	objects.push_back(suzanne);
	objects.push_back(dragon);
	objects.push_back(plane);
	
	// Background creation.
	backgroundReflection = Resources::manager().getCubemap("corsica_beach_cube", {GL_RGB32F, GL_LINEAR, GL_CLAMP_TO_EDGE})->id;
	// \todo Find a way to avoid passing the gamma flag to the object.
	background = Object(Object::Type::Skybox, "skybox", {}, {{"corsica_beach_cube", false }});
	loadSphericalHarmonics("corsica_beach_cube_shcoeffs");
	
	// Compute the bounding box of the shadow casters.
	const BoundingBox bbox = computeBoundingBox(true);
	
	// Lights creation.
	// Create directional light.
	directionalLights.emplace_back(glm::vec3(-2.0f,-1.5f,0.0f), glm::vec3(1.0f,1.0f, 0.92f), bbox);
	directionalLights[0].castShadow(true);
	// Create spotlight.
	spotLights.emplace_back(glm::vec3(2.0f,2.0f,2.0), glm::vec3(-1.0f,-1.0f,-1.0f), glm::vec3(0.0f,10.0f,10.0f), 0.5f, 0.6f, 5.0f, bbox);
	spotLights[0].castShadow(true);
	
	// Create point lights.
	const float lI = 4.0; // Light intensity.
	const std::vector<glm::vec3> colors = { glm::vec3(lI,0.0,0.0), glm::vec3(0.0,lI,0.0), glm::vec3(0.0,0.0,lI), glm::vec3(lI,lI,0.0)};
	for(size_t i = 0; i < 4; ++i){
		const glm::vec3 position = glm::vec3(-1.0f+2.0f*(i%2),-0.1f,-1.0f+2.0f*(i/2));
		pointLights.emplace_back(position, colors[i], 1.2f, bbox);
	}
}
bool BaseOfSupport::update(const Eigen::VectorXd& xi_k) {
    // Get feet corners
    Eigen::MatrixXd feetCorners;
    feetCorners = _stepController->getContact2DCoordinates();
    // Compute the bounding box of the current support configuration
    Eigen::Matrix2d minMaxBoundingBox;
    computeBoundingBox(feetCorners, minMaxBoundingBox);
    // Update right-hand side of constraints
    buildb(minMaxBoundingBox);
    buildf();
    // Matrices in the preview window s.t.
    // A*X <= fbar - B*xi_k
    // Therefore we can prebuild A, fbar and B which are not time-dependent
    buildfbar(_f);
    _rhs = _fbar - _B*xi_k;
    return true;
}
示例#17
0
PointSet<Points3D>::PointSet(const Points3D & pts) :
_points3d(pts)
{
	//
	computeBoundingBox();

	//map positions to [0,1]
	cube_type c;
	getBoundingCube(c);
	point_type tr = c.min();
	T scale = c.size();
	_points3d_01.resize(_points3d.size());
	point_type tmp;
	for (uint i=0;i<_points3d.size();i++)
	{
		tmp = _points3d[i];
		tmp -= tr;
		tmp *= 1/scale;
		_points3d_01[i] = tmp;
	}


}
示例#18
0
bool ClusterMesh::readFile(const char* filename)
{
	if (filename==NULL)
		return false;
	mesh.clear();
	bool result=OpenMesh::IO::read_mesh(mesh, filename);

	// some debug information
	std::cout << "faces: "<< mesh.n_faces()<<std::endl;
	std::cout << "vertices: "<< mesh.n_vertices()<<std::endl;
	std::cout << "edges: "<< mesh.n_edges()<<std::endl;

	// precomputing step
	removeCluster();
	mesh.update_face_normals();
	mesh.update_vertex_normals();
	computeBoundingBox();
	computeFaceCenter();
	computeDualEdgeLength();
	computeEdgeAngle();
	computeEdgeCost();
	return result;
}
示例#19
0
RigidObject::RigidObject(std::string file_name,
                         Ogre::SceneManager *scene_manager, int segment_ind)
    : segment_ind_{ segment_ind }, scene_manager_{ scene_manager } {
  Ogre::MeshPtr object_mesh = render::loadMeshFromResource(file_name);
  entity_ = scene_manager_->createEntity(file_name);
  Ogre::MaterialPtr mat =
      Ogre::MaterialManager::getSingleton().getByName("textured");
  std::stringstream ss;
  ss << "textured_" << segment_ind_;
  Ogre::MaterialPtr cloned_mat = mat->clone(ss.str());
  Ogre::Pass *pass = cloned_mat->getTechnique(0)->getPass(0);
  Ogre::TextureUnitState *tex_unit = pass->createTextureUnitState();
  Ogre::MaterialPtr tmp = Ogre::MaterialManager::getSingleton().getByName(
      object_mesh->getSubMesh(0)->getMaterialName());
  tex_unit->setTextureName(tmp->getTechnique(0)
                               ->getPass(0)
                               ->getTextureUnitState(0)
                               ->getTextureName());
  entity_->setMaterial(cloned_mat);

  texture_name_ = tex_unit->getTextureName();
  file_name_ = file_name;

  Ogre::SubEntity *pSub = entity_->getSubEntity(0);
  // mark segment index for vertex shader
  pSub->setCustomParameter(1, Ogre::Vector4(segment_ind_, 0, 0, 0));

  visual_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode();
  visual_node_->attachObject(entity_);

  // store the vertex positions
  extractMeshPositions(object_mesh.get());
  //  std::cout << "extracted " << positions_.size() << " vertices\n";

  // compute the bounding box
  computeBoundingBox();
}
示例#20
0
void PixelOrientedOverview::computePixelView(GlMainWidget *glWidget) {

  reset(false);

  if (clickLabel != nullptr) {
    delete clickLabel;
    clickLabel = nullptr;
  }

  if (backgroundRect != nullptr) {
    delete backgroundRect;
    backgroundRect = nullptr;
  }

  if (frame != nullptr) {
    delete frame;
    frame = nullptr;
  }

  if (frame2 != nullptr) {
    delete frame2;
    frame2 = nullptr;
  }

  Graph *graph = data->getTulipGraph();

  unsigned int width = pixelOrientedMediator->getImageWidth();
  unsigned int height = pixelOrientedMediator->getImageHeight();

  GlProgressBar *glProgressBar = nullptr;

  if (glWidget != nullptr) {
    glProgressBar =
        new GlProgressBar(Coord(blCornerPos.getX() + width / 2, blCornerPos.getY() + height / 2),
                          width, height, Color(0, 0, 255));
    glProgressBar->setComment("Generating overview ...");
    addGlEntity(glProgressBar, "progress bar");
  }

  unsigned int currentStep = 0;
  unsigned int maxStep = graph->numberOfNodes();
  unsigned int drawStep = maxStep / 10;

  set<int> xCoordSet;

  for (unsigned int i = 0; i < graph->numberOfNodes(); ++i) {
    node n = node(data->getItemIdAtRank(i));
    pocore::Vec2i pos = pixelOrientedMediator->getPixelPosForRank(i);
    Coord nodeCoord = Coord(pos[0], pos[1], 0);
    xCoordSet.insert(pos[0]);
    pixelLayout->setNodeValue(n, nodeCoord);
    ++currentStep;

    if (glWidget != nullptr && currentStep % drawStep == 0) {
      glProgressBar->progress(currentStep, maxStep);
      glWidget->draw();
    }
  }

  if (xCoordSet.size() < 2)
    return;

  set<int>::iterator it = xCoordSet.begin();
  int x1 = *(it++);
  int x2 = *it;
  int size = x2 - x1;

  pixelSize->setAllNodeValue(Size(size, size, size));

  overviewLabel->setColor(textColor);

  GlOffscreenRenderer *glOffscreenRenderer = GlOffscreenRenderer::getInstance();

  glOffscreenRenderer->setViewPortSize(width, height);
  glOffscreenRenderer->clearScene();
  glOffscreenRenderer->setSceneBackgroundColor(backgroundColor);
  glOffscreenRenderer->addGraphCompositeToScene(graphComposite);
  glOffscreenRenderer->renderScene(true);

  if (glWidget != nullptr) {
    glProgressBar->progress(maxStep, maxStep);
    glWidget->draw();

    deleteGlEntity(glProgressBar);
    delete glProgressBar;
  }

  GLuint textureId = glOffscreenRenderer->getGLTexture(true);
  GlTextureManager::getInst().deleteTexture(textureName);
  GlTextureManager::getInst().registerExternalTexture(textureName, textureId);

  if (findGlEntity(dimName) == nullptr) {
    addGlEntity(new Gl2DRect(blCornerPos.getY() + pixelOrientedMediator->getImageHeight(),
                             blCornerPos.getY(), blCornerPos.getX(),
                             blCornerPos.getX() + pixelOrientedMediator->getImageWidth(),
                             textureName),
                dimName);
    addGlEntity(overviewLabel, "overview label");
    computeBoundingBox();
  }

  overviewGen = true;
}
    void Ex_006_BoundingBoxTest::run() {
        const string path = "/Users/saburookita/Personal Projects/Three.cpp Rev.2/examples/assets/";
        
        ForwardRenderer renderer;
        renderer.init( "Ex 006: Bounding Box Tests", 1600 * 2 / 4, 900 * 2 / 4 );
        renderer.setCameraControl(Arcball::create(2.0f));
        
        /* Create scene */
        auto scene = Scene::create();
        scene->setFog(Fog::create( 0x72645b / 2, 2.0, 15.0 ));
        scene->setViewport( 0.0, 0.0, renderer.getWidth(), renderer.getHeight() );
        scene->setShadowMapType( SHADOW_MAP::PCF );
        
        /* Create camera */
        auto camera = PerspectiveCamera::create( 50.0, renderer.getAspectRatio(), 0.001, 100.0 );
        camera->translate(0.0, 1.5, 5.5);
        camera->lookAt( 0.0, 1.0, 0.0 );
        
        /* Load our ply models */
        vector<string> filenames = {
            "dragon_vrip_res3.ply",
            "happy_vrip_res3.ply",
        };
        
        vector<ptr<Mesh>> statues;
        
        float x_offset = -1.0;
        for( string filename: filenames ) {
            auto statue = Loader::loadPLY(path + "/ply models/", filename,
                                          aiProcess_Triangulate |
                                          aiProcess_OptimizeMeshes |
                                          aiProcess_JoinIdenticalVertices |
                                          aiProcess_GenSmoothNormals | aiProcess_FlipWindingOrder );
            
            statue->setMaterial(PhongMaterial::create(0xcccccc, 0x0, 0x000000, 0x999999, 10, true));
            statue->getGeometry()->setScale(10.0f);
            statue->castShadow      = true;
            statue->receiveShadow   = true;
            
            auto bbox = statue->computeBoundingBox();
            glm::vec3 center = bbox->center();
            glm::vec3 size   = bbox->size();
            statue->translate(x_offset, -(center.y - size.y * 0.5), 0.0);
            
            cout << *bbox << endl;
            
            x_offset += 2.0f;
            scene->add( statue );
            statues.push_back( statue );
        }
        
        auto box = Mesh::create( CubeGeometry::create(1.0f, 3),
                                PhongMaterial::create(0x777777, 0x777777, 0x0, 0x0, 0.0, true) );
        box->setTexture( TextureUtils::loadAsTexture( path, "crate.tga") );
        box->getGeometry()->rotateX(45.0f);
        box->getGeometry()->setScale(1.5f);
        box->translate(3.0f, 0.5, 0.0);
        box->castShadow = true;
        box->receiveShadow = true;
        scene->add( box );
        
        auto cylinder = Mesh::create( CylinderGeometry::create(0.5, 0.5, 1.0, 30, 5, false),
                                      PhongMaterial::create( 0xDDDDDD, 0x0, 0x0, 0x111111, 150.0, true )
                                     );
        cylinder->translate(-3.0f, 0.5f, 0.0f);
        cylinder->castShadow = true;
        cylinder->receiveShadow = true;
        scene->add( cylinder );
        
        
        /* And the ground plane */
        auto plane = Mesh::create( PlaneGeometry::create(50.0f), PhongMaterial::create() );
        plane->rotateX(-90.0f);
        plane->receiveShadow = true;
        scene->add( plane );

        /* Cubemap */
//        auto env = Mesh::create( CubeGeometry::create(50.0f), MeshCubeMapMaterial::create() );
//        env->setTexture( TextureUtils::loadAsEnvMap( path + "cube/pisa",
//                                                    "nx.png", "ny.png", "nz.png",
//                                                    "px.png", "py.png", "pz.png"));
//        
//        cylinder->setEnvMap( env->getTexture() );
//        scene->add( env );
        
        
        /* Create a (rotating) directional light */
        auto dir_light = DirectionalLight::create(0x99CCFF, 1.35, glm::vec3( 3.0, 1.0, 3.0 ) );
        dir_light->castShadow       = true;
        dir_light->shadowBias       = -0.0001;
        dir_light->shadowCameraNear = -10.0;
        dir_light->shadowCameraFar  =  10.0;
        dir_light->shadowMapSize    = glm::vec2(512);
        scene->add( dir_light );
        
        /* Create a spotlight, the shadow should be casted no the left hand side */
        auto spot_light = SpotLight::create(0x99CCFF, 1.0, 20.0, 50.0, 1.0 );
        spot_light->position = glm::vec3(3.0, 2.0, 3.0);
        spot_light->castShadow = true;
        scene->add( spot_light );
        
        
        /* Create an ambient light */
        scene->add( AmbientLight::create(0xCCCCCC));
        
        /* Create a post render callback for objects rotation */
        bool rotate_objects = false;
        float light_rotation_1 = 0.0;
        renderer.setPostRenderCallbackHandler( [&](){
            dir_light->position.x = ( 3.0 * cosf( light_rotation_1 ) );
            dir_light->position.z = ( 3.0 * sinf( light_rotation_1 ) );
            
            light_rotation_1 += 0.01;
            
            if( rotate_objects ) {
                box->rotateY(-1.0f);
                statues[0]->rotateY(-0.5f);
            }
        });
        
        
        renderer.setMouseButtonCallbackHandler([&] (GLFWwindow *, int button, int action, int mod){
            auto descendants = scene->getDescendants();
            /* Reset the color first */
            for( auto obj: descendants ) {
                if( instance_of(obj, Mesh)) {
                    auto mesh = downcast( obj, Mesh );
                    if( instance_of(mesh->getMaterial(), PhongMaterial)){
                        auto phong = downcast(mesh->getMaterial(), PhongMaterial);
                        phong->setDiffuseColor( 0xDDDDDD );
                    }
                }
            }
            
            if( action == GLFW_PRESS ) {
                auto raycaster = Projector::pickingRay(renderer.getCursorPosition(), camera);
                
                /* Upon selected / ray picked, change the diffuse color to red */
                for( auto obj: descendants ) {
                    if( instance_of(obj, Geometry))
                        continue;
                    
                    auto bound = obj->getBoundingBox();
                    
                    if(raycaster->ray->intersects(bound)) {
                        if( instance_of(obj, Mesh)) {
                            auto mesh = downcast( obj, Mesh );
                            
                            if( instance_of(mesh->getMaterial(), PhongMaterial)){
                                auto phong = downcast(mesh->getMaterial(), PhongMaterial);
                                phong->setDiffuseColor( 0xDD0000 );
                            }
                        }
                    }
                }
            }
        });
        
        /* Override key callback handler */
        renderer.setKeyCallbackHandler([&](GLFWwindow *, int key, int scancode, int action, int mod) {
            if( action == GLFW_PRESS ) {
                switch ( key) {
                    case GLFW_KEY_R: /* Toggle rotation */
                        rotate_objects = !rotate_objects;
                        break;
                        
                    default: break;
                }
            }
        });
        
        renderer.setGamma( true, true );
        
        renderer.setClearColor( scene->getFog()->getColor() );
        renderer.render(scene, camera );
    }
int main(int argc, char **argv){

    std::string filename("");
	unsigned int scale = 5, dmst = 2, window = 3, detectorType = 0, descriptorType = 0, distanceType = 2, strategy = 0;
    double baseSigma = 0.2, sigmaStep = 1.4, minPeak = 0.34, minPeakDistance = 0.001, success = 0.95, inlier = 0.4, matchingThreshold = 0.4;
	bool useMaxRange = false;
	
	int i = 1;
	while(i < argc){
		if(strncmp("-filename", argv[i], sizeof("-filename")) == 0 ){
			filename = argv[++i];
			i++;
		} else if(strncmp("-detector", argv[i], sizeof("-detector")) == 0 ){
			detectorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-descriptor", argv[i], sizeof("-descriptor")) == 0 ){
			descriptorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-corresp", argv[i], sizeof("-corresp")) == 0 ){
			corresp = atoi(argv[++i]);
			i++;
		}  else if(strncmp("-distance", argv[i], sizeof("-distance")) == 0 ){
			distanceType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-baseSigma", argv[i], sizeof("-baseSigma")) == 0 ){
			baseSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-sigmaStep", argv[i], sizeof("-sigmaStep")) == 0 ){
			sigmaStep = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeak", argv[i], sizeof("-minPeak")) == 0 ){
			minPeak = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeakDistance", argv[i], sizeof("-minPeakDistance")) == 0 ){
			minPeakDistance = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-scale", argv[i], sizeof("-scale")) == 0 ){
			scale = atoi(argv[++i]);
			i++;
		} else if(strncmp("-dmst", argv[i], sizeof("-dmst")) == 0 ){
			dmst = atoi(argv[++i]);
			i++;
		} else if(strncmp("-window", argv[i], sizeof("-window")) == 0 ){
			scale = atoi(argv[++i]);
			i++;
		} else if(strncmp("-acceptanceSigma", argv[i], sizeof("-acceptanceSigma")) == 0 ){
			acceptanceSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-success", argv[i], sizeof("-success")) == 0 ){
			success = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-inlier", argv[i], sizeof("-inlier")) == 0 ){
			inlier = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-matchingThreshold", argv[i], sizeof("-matchingThreshold")) == 0 ){
			matchingThreshold = strtod(argv[++i], NULL);
			i++;
		} else {
			i++;
		}
    }
    
    if(!filename.size()){
		help();
		exit(-1);
    }
    
    CarmenLogWriter writer;
    CarmenLogReader reader;
    
    m_sensorReference = LogSensorStream(&reader, &writer);
    
    m_sensorReference.load(filename);
    
    SimpleMinMaxPeakFinder *m_peakMinMax = new SimpleMinMaxPeakFinder(minPeak, minPeakDistance);
    
    
    std::string detector("");
    switch(detectorType){
	case 0:
	    m_detectorCurvature = new CurvatureDetector(m_peakMinMax, scale, baseSigma, sigmaStep, dmst);
		m_detectorCurvature->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorCurvature;
	    detector = "curvature";
	    break;
	case 1:
	    m_detectorNormalEdge = new NormalEdgeDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
	    m_detectorNormalEdge->setUseMaxRange(useMaxRange);
		m_detector = m_detectorNormalEdge;
	    detector = "edge";
	    break;
	case 2:
	    m_detectorNormalBlob = new NormalBlobDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
		m_detectorNormalBlob->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorNormalBlob;
	    detector = "blob";
	    break;
	case 3:
	    m_detectorRange = new RangeDetector(m_peakMinMax, scale, baseSigma, sigmaStep);
		m_detectorRange->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorRange;
	    detector = "range";
	    break;
	default:
	    std::cerr << "Wrong detector type" << std::endl;
	    exit(-1);
    }
    
    HistogramDistance<double> *dist = NULL;
    
    std::string distance("");
    switch(distanceType){
	case 0:
	    dist = new EuclideanDistance<double>();
	    distance = "euclid";
	    break;
	case 1:
	    dist = new Chi2Distance<double>();
	    distance = "chi2";
	    break;
	case 2:
	    dist = new SymmetricChi2Distance<double>();
	    distance = "symchi2";
	    break;
	case 3:
	    dist = new BatthacharyyaDistance<double>();
	    distance = "batt";
	    break;
	case 4:
	    dist = new KullbackLeiblerDistance<double>();
	    distance = "kld";
	    break;
	case 5:
	    dist = new JensenShannonDistance<double>();
	    distance = "jsd";
	    break;
	default:
	    std::cerr << "Wrong distance type" << std::endl;
	    exit(-1);
    }
    
    std::string descriptor("");
    switch(descriptorType){
	case 0:
	    m_betaGenerator = new BetaGridGenerator(0.02, 0.5, 4, 12);
	    m_betaGenerator->setDistanceFunction(dist);
	    m_descriptor = m_betaGenerator;
	    descriptor = "beta";
	    break;
	case 1:
	    m_shapeGenerator = new ShapeContextGenerator(0.02, 0.5, 4, 12);
	    m_shapeGenerator->setDistanceFunction(dist);
	    m_descriptor = m_shapeGenerator;
	    descriptor = "shape";
	    break;
	default:
	    std::cerr << "Wrong descriptor type" << std::endl;
	    exit(-1);
    }
    
    std::cerr << "Processing file:\t" << filename << "\nDetector:\t\t" << detector << "\nDescriptor:\t\t" << descriptor << "\nDistance:\t\t" << distance << std::endl;
    
    switch(strategy){
	case 0:
	    m_ransac = new RansacFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	case 1:
	    m_ransac = new RansacMultiFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	default:
	    std::cerr << "Wrong strategy type" << std::endl;
	    exit(-1);
    }

    m_sensorReference.seek(0,END);
    unsigned int end = m_sensorReference.tell();
    m_sensorReference.seek(0,BEGIN);

    m_pointsReference.resize(end + 1);
    m_posesReference.resize(end + 1);
        
    computeBoundingBox();
    
    detectLog();
    describeLog();
    
    std::stringstream mapFile;
    mapFile << filename << "_map.png";
/*    cairo_surface_t * cairoMapSurface = cairo_pdf_surface_create(mapFile.str().c_str(), sizeX, sizeY);
    cairo_surface_t * cairoOutSurface = cairo_pdf_surface_create(outFile.str().c_str(), sizeX, sizeY);*/
    cairo_surface_t * cairoMapSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sizeX, sizeY);
//     cairo_surface_t * cairoMapSurface = cairo_svg_surface_create(mapFile.str().c_str(), sizeX, sizeY);
    cairoMap = cairo_create(cairoMapSurface);
    
    std::stringstream outDir;
    outDir << filename << "_" << detector << "_" << descriptor << "_" << distance << "/";
    mkdir(outDir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    
    computeMap();

    std::string bar(50,' ');
    bar[0] = '#';
    unsigned int progress = 0;
    
    
    for(unsigned int i =0; i < m_pointsReference.size(); i++){
	unsigned int currentProgress = (i*100)/(m_pointsReference.size() - 1);
	if (progress < currentProgress){
	    progress = currentProgress;
	    bar[progress/2] = '#';
	    std::cout << "\rMatching  [" << bar << "] " << progress << "%" << std::flush;
	}
	std::stringstream outFile;
	outFile << outDir.str() << "frame_";
	outFile.width(4);
	outFile.fill('0');
	outFile << std::right << i << ".png";
	cairo_surface_t * cairoOutSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sizeX, sizeY);
// 	cairo_surface_t * cairoOutSurface = cairo_svg_surface_create(outFile.str().c_str(), sizeX, sizeY);
	cairoOut = cairo_create(cairoOutSurface);
	cairo_translate(cairoOut, -offsetX, -offsetY);
	cairo_scale(cairoOut, scaleFactor, scaleFactor);
	cairo_set_line_width(cairoOut, 1./scaleFactor);
	match(i);
 	cairo_surface_write_to_png(cairoOutSurface, outFile.str().c_str());
	cairo_surface_destroy(cairoOutSurface);
	cairo_destroy(cairoOut);
    }
    std::cout << " done." << std::endl;
    
    cairo_surface_write_to_png(cairoMapSurface, mapFile.str().c_str());
    
    cairo_surface_destroy(cairoMapSurface);
    cairo_destroy(cairoMap);
//     cairo_show_page(cairoOut);
}
    void Ex_008_FontStashIntegration::run() {
//        const string path = "/Users/saburookita/Personal Projects/Three.cpp Rev.2/examples/assets/";
        const string path = "../examples/assets/";
        
        ForwardRenderer renderer;
        renderer.init( "Ex 008: FontStash integration test", 1600 * 2 / 4, 900 * 2 / 4 );
        renderer.setCameraControl(Arcball::create(2.0f));
        
        
        /* First load the fonts */
        renderer.addFont("droid-regular",   path + "fonts/DroidSerif-Regular.ttf");
        renderer.addFont("droid-italic",    path + "fonts/DroidSerif-Italic.ttf");
        renderer.addFont("droid-bold",      path + "fonts/DroidSerif-Bold.ttf");
        renderer.addFont("droid-japanese",  path + "fonts/DroidSansJapanese.ttf");
        
        /*Then write on screen*/
        renderer.addText( "Test FontStash",     100, 100, "droid-regular", 0x0, 32.0f );
        renderer.addText( "writing in italic",  100, 130, "droid-italic", 0x00FF00, 24.0f );
        renderer.addText( "... or bold",        250, 130, "droid-bold", 0xFF0000, 24.0f );
        
        renderer.addText( "éßüä",               400, 90, "droid-regular", 0x0000FF, 24.0f );
        renderer.addText( "日本語もできます。",    400, 120, "droid-japanese", 0xFFFFFF, 24.0f );
        
        renderer.addText( "spacing = 1.0",   100, 200, "droid-italic", 0x00FF00, 20.0f, 1.0f );
        renderer.addText( "spacing = 5.0",   100, 225, "droid-italic", 0xFFFF00, 20.0f, 5.0f );
        renderer.addText( "spacing = 10.0",  100, 250, "droid-italic", 0x00FFFF, 20.0f, 10.0f );
        
        renderer.addText( "blur = 1.0",   400, 200, "droid-bold", 0x99CCFF, 30.0f, 0.0f, 1.0f );
        renderer.addText( "blur = 5.0",   400, 240, "droid-bold", 0xFFCC99, 30.0f, 0.0f, 5.0f );
        renderer.addText( "blur = 10.0",  400, 280, "droid-bold", 0xCCFF99, 30.0f, 0.0f, 10.0f );
        
        int cursor_pos_text = renderer.addText( "Cursor Position: ", 80, 400, "droid-regular", 0xFFFFFF, 20.0f );
        
        /* Create scene */
        auto scene = Scene::create();
        scene->setFog(Fog::create( 0x72645b, 2.0, 15.0 ));
        scene->setViewport( 0.0, 0.0, renderer.getWidth(), renderer.getHeight() );
        scene->setShadowMapType( SHADOW_MAP::PCF );
        
        /* Create camera */
        auto camera = PerspectiveCamera::create( 50.0, renderer.getAspectRatio(), 0.001, 100.0 );
        camera->translate(0.0, 1.5, 5.5);
        camera->lookAt( 0.0, 1.0, 0.0 );
        
        /* Load our ply models */
        float x_offset = -1.0;
        auto statue = Loader::loadPLY(path + "/ply models/", "happy_vrip_res3.ply",
                                      aiProcess_JoinIdenticalVertices |
                                      aiProcess_GenSmoothNormals | aiProcess_FlipWindingOrder );
        
        statue->setMaterial(PhongMaterial::create(0x777777, 0x0, 0x777777, 0x0, 0, true));
        statue->getGeometry()->setScale(10.f);
        statue->castShadow      = true;
        statue->receiveShadow   = true;
        
        auto bounding_box = statue->computeBoundingBox();
        glm::vec3 size    = bounding_box->size();
        glm::vec3 center  = bounding_box->center();
        statue->translate(x_offset, -(center.y - size.y * 0.5), 0.0);
        
        x_offset += 2.0f;
        scene->add( statue );
     
        
        /* A sphere, cube, and cylinder walk into a pub */
        auto sphere = Mesh::create( SphereGeometry::create(30, 20, 0.66f ),
                                   PhongMaterial::create( 0xCCCCCC, 0x0, 0x0, 0x222222, 130.0, true ) );
        
        sphere->setTexture      ( TextureUtils::loadAsTexture    ( path + "planets", "earth_atmos_2048.jpg") );
        sphere->setNormalMap    ( TextureUtils::loadAsNormalMap  ( path + "planets", "earth_normal_2048.jpg" ) );
        sphere->setSpecularMap  ( TextureUtils::loadAsSpecularMap( path + "planets", "earth_specular_2048.jpg" ) );
        sphere->receiveShadow = true;
        sphere->castShadow    = true;
        sphere->translate( x_offset, 0.66f, 0.0f );
        scene->add( sphere );
        
        
        auto plane = Mesh::create( PlaneGeometry::create(20.0f),
                                   PhongMaterial::create(0x777777, 0x777777, 0x0, 0x999999, 30) );
        plane->name = "plane";
        plane->rotateX(-90.0f);
        plane->receiveShadow = true;
        scene->add( plane );
        
        /* Cubemap */
        auto env = Mesh::create( CubeGeometry::create(50.0f), MeshCubeMapMaterial::create() );
        env->setTexture( TextureUtils::loadAsEnvMap( path + "cube/pisa",
                                                    "nx.png", "ny.png", "nz.png",
                                                    "px.png", "py.png", "pz.png"));
        statue->setEnvMap( env->getTexture() );
        scene->add( env );
        
        
        /* Create a (rotating) directional light */
        auto dir_light = DirectionalLight::create(0x99CCFF, 1.35, glm::vec3( 3.0, 1.0, 3.0 ) );
        dir_light->castShadow       = true;
        dir_light->shadowBias       = -0.001;
        dir_light->shadowCameraNear = -10.0;
        dir_light->shadowCameraFar  =  10.0;
        scene->add( dir_light );
        
        /* Create a spotlight, the shadow should be casted no the left hand side */
        auto spot_light = SpotLight::create(0x99CCFF, 1.0, 20.0, 50.0, 1.0 );
        spot_light->position = glm::vec3(3.0, 2.0, 3.0);
        spot_light->castShadow = true;
        scene->add( spot_light );
        
        /* Create an ambient light */
        scene->add( AmbientLight::create(0x777777));
        
        /* Create a post render callback for objects rotation */
        bool rotate_objects = false;
        float light_rotation_1 = 0.0;
        renderer.setPostRenderCallbackHandler( [&](){
            dir_light->position.x = ( 3.0 * cosf( light_rotation_1 ) );
            dir_light->position.z = ( 3.0 * sinf( light_rotation_1 ) );
            
            light_rotation_1 += 0.01;
            
            if( rotate_objects ) {
                statue->rotateY(1.0f);
                sphere->rotateY(-1.0f);
            }
        });
        
        renderer.setCursorCallbackHandler([&](GLFWwindow *, double x, double y){
            stringstream ss;
            ss.precision(4);
            ss << "Cursor Position: (" << x << ", " << y << ")";
            renderer.setText(cursor_pos_text, ss.str() );
        });
        
        /* Override key callback handler */
        renderer.setKeyCallbackHandler([&](GLFWwindow *window, int key, int scancode, int action, int mod) {
            if( action == GLFW_PRESS ) {
                switch ( key) {
                    case GLFW_KEY_R: /* Toggle rotation */
                        rotate_objects = !rotate_objects;
                        break;
                        
                    default:
                        break;
                }
            }
        });
        
        
        renderer.setGamma( true, true );
        
        renderer.setClearColor( scene->getFog()->getColor() );
        renderer.render(scene, camera );
    }
示例#24
0
void Scene::addObject(Object &o)
{
    pobjects.push_back(o);
    computeBoundingBox();
}
示例#25
0
AlembicPoints::meshInfo AlembicPoints::CacheShapeMesh(Mesh* pShapeMesh, BOOL bNeedDelete, Matrix3 meshTM, int nMatId, int particleId, TimeValue ticks, ShapeType &type, Abc::uint16_t &instanceId, float &animationTime)
{
    ESS_PROFILE_FUNC();

	type = ShapeType_Instance;
	//animationTime = 0;
	
	//Mesh* pShapeMesh = pExt->GetParticleShapeByIndex(particleId);

	if(pShapeMesh->getNumFaces() == 0 || pShapeMesh->getNumVerts() == 0){
		meshInfo mi;
      return mi;
	}

    meshDigests digests;
    {
    ESS_PROFILE_SCOPE("AlembicPoints::CacheShapeMesh - compute hash");
	AbcU::MurmurHash3_x64_128( pShapeMesh->verts, pShapeMesh->numVerts * sizeof(Point3), sizeof(Point3), digests.Vertices.words );
	AbcU::MurmurHash3_x64_128( pShapeMesh->faces, pShapeMesh->numFaces * sizeof(Face), sizeof(Face), digests.Faces.words );
	if(mJob->GetOption("exportMaterialIds")){

		std::vector<MtlID> matIds;

		if(nMatId < 0){
			matIds.reserve(pShapeMesh->getNumFaces());
			for(int i=0; i<pShapeMesh->getNumFaces(); i++){
				matIds.push_back(pShapeMesh->getFaceMtlIndex(i));
			}
		}
		else{
			matIds.push_back(nMatId);
		}

		AbcU::MurmurHash3_x64_128( &matIds[0], matIds.size() * sizeof(MtlID), sizeof(MtlID), digests.MatIds.words );
	}
	if(mJob->GetOption("exportUVs")){
		//TODO...
	}
    }
	
	mTotalShapeMeshes++;

	meshInfo currShapeInfo;
	faceVertexHashToShapeMap::iterator it = mShapeMeshCache.find(digests);
	if( it != mShapeMeshCache.end() ){
		currShapeInfo = it->second;
	}
	else{
		meshInfo& mi = mShapeMeshCache[digests];
		mi.pMesh = pShapeMesh;

      mi.bbox = computeBoundingBox(pShapeMesh);

		mi.nMatId = nMatId;
		
		std::stringstream nameStream;
		nameStream<< EC_MCHAR_to_UTF8( mMaxNode->GetName() ) <<"_";
		nameStream<<"InstanceMesh"<<mNumShapeMeshes;
		mi.name=nameStream.str();

		mi.bNeedDelete = bNeedDelete;
		mi.meshTM = meshTM;
        mi.nMeshInstanceId = mNumShapeMeshes;

		currShapeInfo = mi;
		mNumShapeMeshes++;

		mMeshesToSaveForCurrentFrame.push_back(&mi);

		//ESS_LOG_WARNING("ticks: "<<ticks<<" particleId: "<<particleId);
		//ESS_LOG_WARNING("Adding shape with hash("<<vertexDigest.str()<<", "<<faceDigest.str()<<") \n auto assigned name "<<mi.name <<" efficiency:"<<(double)mNumShapeMeshes/mTotalShapeMeshes);
	}

    instanceId = currShapeInfo.nMeshInstanceId;

 //   {
 //      ESS_PROFILE_SCOPE("CacheShapeMesh push_back instance name");

	//std::string pathName("/");
	//pathName += currShapeInfo.name;

	//instanceId = FindInstanceName(pathName);
	//if (instanceId == USHRT_MAX){
	//	mInstanceNames.push_back(pathName);
	//	instanceId = (Abc::uint16_t)mInstanceNames.size()-1;
	//}

 //   }

    return currShapeInfo;
}
示例#26
0
game_level* game_CreateLevel(void) {
	int i;
	game_level* l;

	l = malloc( sizeof(game_level) );
	scripting_GetGlobal("level", NULL);
	// get scalability flag
	scripting_GetValue("scalable");
	scripting_GetIntegerResult(& l->scalable);
	// get number of spawnpoints
	scripting_GetValue("spawn");
	scripting_GetArraySize(& l->nSpawnPoints);
	// copy spawnpoints into vec2's
	l->spawnPoints = malloc(l->nSpawnPoints * sizeof(game_spawnpoint));

	// fixme, use scalability
	for(i = 0; i < l->nSpawnPoints; i++) {
		scripting_GetArrayIndex(i + 1);

		scripting_GetValue("x");
		scripting_GetFloatResult(& l->spawnPoints[i].v.v[0]);
		scripting_GetValue("y");
		scripting_GetFloatResult(& l->spawnPoints[i].v.v[1]);
		scripting_GetValue("dir");
		scripting_GetIntegerResult(& l->spawnPoints[i].dir);

		scripting_Pop(); // index i
	}
	scripting_Pop(); // spawn
	
	// get number of boundary segments
	scripting_GetValue("boundary");
	scripting_GetArraySize(& l->nBoundaries);
	// copy boundaries into segments
	l->boundaries = malloc(l->nBoundaries * sizeof(segment2));
	for(i = 0; i < l->nBoundaries; i++) {
		scripting_GetArrayIndex(i + 1);
		
		scripting_GetArrayIndex(1);
		scripting_GetValue("x");
		scripting_GetFloatResult(& l->boundaries[i].vStart.v[0]);
		scripting_GetValue("y");
		scripting_GetFloatResult(& l->boundaries[i].vStart.v[1]);
		scripting_Pop(); // index 0
		
		scripting_GetArrayIndex(2);
		{
			vec2 v;
			scripting_GetValue("x");
			scripting_GetFloatResult(& v.v[0]);
			scripting_GetValue("y");
			scripting_GetFloatResult(& v.v[1]);
			vec2_Sub(& l->boundaries[i].vDirection, &v, &l->boundaries[i].vStart);
		}
		scripting_Pop(); // index 1
	
		scripting_Pop(); // index i
	}
	scripting_Pop(); // boundary

	scripting_Pop(); // level

	computeBoundingBox(l);

	return l;
}
示例#27
0
double DkIntersectPoly::compute() {

	// defines
	gamut = 500000000;
	minRange = nmc::DkVector(FLT_MAX, FLT_MAX);
	maxRange = nmc::DkVector(-FLT_MAX, -FLT_MAX);
	computeBoundingBox(vecA, &minRange, &maxRange);
	computeBoundingBox(vecB, &minRange, &maxRange);

	scale = maxRange - minRange;

	if (scale.minCoord() == 0) return 0; //rechteck mit h�he oder breite = 0

	scale.x = gamut / scale.x;
	scale.y = gamut / scale.y;

	float ascale = scale.x * scale.y;

	// check input
	if (vecA.size() < 3 || vecB.size() < 3) {
		qDebug() << "The polygons must consist of at least 3 points but they are: (vecA: " << vecA.size() << ", vecB: " << vecB.size();
		return 0;
	}

	// compute edges
	std::vector<DkVertex> ipA;
	std::vector<DkVertex> ipB;

	getVertices(vecA, &ipA, 0);
	getVertices(vecB, &ipB, 2);

	for (unsigned int idxA = 0; idxA < ipA.size() - 1; idxA++) {
		for (unsigned int idxB = 0; idxB < ipB.size() - 1; idxB++) {

			if (ovl(ipA[idxA].rx, ipB[idxB].rx) && ovl(ipA[idxA].ry, ipB[idxB].ry)) {

				int64 a1 = -area(ipA[idxA].ip, ipB[idxB].ip, ipB[idxB + 1].ip);
				int64 a2 = area(ipA[idxA + 1].ip, ipB[idxB].ip, ipB[idxB + 1].ip);

				if (a1 < 0 == a2 < 0) {
					int64 a3 = area(ipB[idxB].ip, ipA[idxA].ip, ipA[idxA + 1].ip);
					int64 a4 = -area(ipB[idxB + 1].ip, ipA[idxA].ip, ipA[idxA + 1].ip);

					if (a3 < 0 == a4 < 0) {

						if (a1 < 0) {
							cross(ipA[idxA], ipA[idxA + 1], ipB[idxB], ipB[idxB + 1], (double)a1, (double)a2, (double)a3, (double)a4);
							ipA[idxA].in++;
							ipB[idxB].in--;
						}
						else {
							cross(ipB[idxB], ipB[idxB + 1], ipA[idxA], ipA[idxA + 1], (double)a3, (double)a4, (double)a1, (double)a2);
							ipA[idxA].in--;
							ipB[idxB].in++;
						}
					}
				}

			}
		}
	}

	inness(ipA, ipB);
	inness(ipB, ipA);

	double areaD = (double)interArea / (ascale + FLT_MIN);

	return areaD;

}
示例#28
0
		glm::vec3 getCenter() {
			auto aabb = computeBoundingBox();
			return aabb.getCenter();
		}
示例#29
0
void PixelOrientedOverview::setBLCorner(const Coord &blCorner) {
  GlComposite::translate(blCorner - blCornerPos);
  blCornerPos = blCorner;
  computeBoundingBox();
}
示例#30
0
static void computeBoundingBox(::Ogre::SceneNode* node, ::Ogre::Vector3& minimum, ::Ogre::Vector3& maximum/*, int level=0*/)
{
	//node->_update(true,true) ;

	const ::Ogre::AxisAlignedBox& boundingbox = node->_getWorldAABB();

	// current node boundss
	::Ogre::Vector3 bbox_min = boundingbox.getMinimum();
	::Ogre::Vector3 bbox_max = boundingbox.getMaximum();

	//::std::string indent = "";
	//for (int i=0; i<level; i++)
	//	indent += "  ";


	// SubNodes
	::Ogre::SceneNode::ChildNodeIterator child_it = node->getChildIterator();
	while (child_it.hasMoreElements())
	{
		::Ogre::SceneNode* subnode = dynamic_cast<::Ogre::SceneNode*>(child_it.getNext());
		if (subnode != 0)
		{
			computeBoundingBox(subnode,minimum,maximum/*,level+1*/);
		}
	}

	// Entities
	//indent += "  ";
	::Ogre::SceneNode::ObjectIterator attch_obj_it = node->getAttachedObjectIterator();
	while (attch_obj_it.hasMoreElements())
	{
		const ::Ogre::Entity* ent = dynamic_cast<::Ogre::Entity*>(attch_obj_it.getNext());
		if (ent != 0)
		{
			::Ogre::AxisAlignedBox  box = ent->getMesh()->getBounds();
			//const ::Ogre::AxisAlignedBox  & box = ent->getMesh()->getBounds();

			if(box.isInfinite() || box.isNull()) { continue ; }

			box.transform(ent->getParentSceneNode()->_getFullTransform()) ;

			::Ogre::Vector3 box_min = box.getMinimum();
			::Ogre::Vector3 box_max = box.getMaximum();

			//box_min = ent->getParentSceneNode()->_getFullTransform() * box_min;
			//box_max = ent->getParentSceneNode()->_getFullTransform() * box_max;

			//::std::cout << indent << "Entity: " << ent->getName() << "\n";
			//::std::cout << indent << box_min[0] << " " << box_min[1] << " " <<  box_min[2] << "\n";
			//::std::cout << indent << box_max[0] << " " << box_max[1] << " " <<  box_max[2] << "\n";

			for (int i=0; i<3; i++)
			{
				minimum[i] = ::std::min(minimum[i], box_min[i]);
				maximum[i] = ::std::max(maximum[i], box_max[i]);
			}
		}
	}

	//::std::cout << indent << "Node: " << node->getName() << "\n";
	//::std::cout << indent << minimum[0] << " " << minimum[1] << " " <<  minimum[2] << "\n";
	//::std::cout << indent << maximum[0] << " " << maximum[1] << " " <<  maximum[2] << "\n";
}