void loadMeshes()
	{
		loadMesh("./../data/models/retroufo_red.X", &meshes.ufo, vertexLayout, 0.25f);
	}
Beispiel #2
0
	void loadMeshes()
	{
		loadMesh(getAssetPath() + "models/suzanne.obj", &meshes.object, vertexLayout, 0.25f);
	}
	void loadAssets()
	{
		loadMesh(getAssetPath() + "models/color_teapot_spheres.dae", &meshes.cube, vertexLayout, 0.1f);
		textureLoader->loadTexture(getAssetPath() + "textures/metalplate_nomips_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, &textures.colormap);
	}
void
TestInterpolationHCurl3D::testInterpolation( std::string one_element_mesh )
{
    //auto myexpr = unitX() + unitY() + unitZ() ; //(1,1,1)
    auto myexpr = vec( cst(1.), cst(1.), cst(1.));

    // one element mesh
    auto mesh_name = one_element_mesh + ".msh"; //create the mesh and load it
    fs::path mesh_path( mesh_name );

    mesh_ptrtype oneelement_mesh = loadMesh( _mesh=new mesh_type,
                                             _filename=mesh_name);

    // refined mesh (export)
    auto refine_level = std::floor(1 - math::log( 0.1 )); //Deduce refine level from meshSize (option)
    mesh_ptrtype mesh = loadMesh( _mesh=new mesh_type,
                                  _filename=mesh_name,
                                  _refine=( int )refine_level);

    space_ptrtype Xh = space_type::New( oneelement_mesh );

    std::vector<std::string> faces = {"yzFace","xyzFace","xyFace"};
    std::vector<std::string> edges = {"zAxis","yAxis","yzAxis","xyAxis","xzAxis","xAxis"};

    element_type U_h_int = Xh->element();
    element_type U_h_on = Xh->element();
    element_type U_h_on_boundary = Xh->element();

    submesh1d_ptrtype edgeMesh( new submesh1d_type );
    edgeMesh = createSubmesh(oneelement_mesh, boundaryedges(oneelement_mesh) ); //submesh of edges

    // Tangents on ref element
    auto t0 = vec(cst(0.),cst(0.),cst(-2.));
    auto t1 = vec(cst(0.),cst(2.),cst(0.));
    auto t2 = vec(cst(0.),cst(-2.),cst(2.));
    auto t3 = vec(cst(2.),cst(-2.),cst(0.));
    auto t4 = vec(cst(2.),cst(0.),cst(-2.));
    auto t5 = vec(cst(2.),cst(0.),cst(0.));

    // Jacobian of geometrical transforms
    std::string jac;
    if(mesh_path.stem().string() == "one-elt-ref-3d" || mesh_path.stem().string() == "one-elt-real-h**o-3d" )
        jac = "{1,0,0,0,1,0,0,0,1}:x:y:z";
    else if(mesh_path.stem().string() == "one-elt-real-rotx" )
        jac = "{1,0,0,0,0,-1,0,1,0}:x:y:z";
    else if(mesh_path.stem().string() == "one-elt-real-roty" )
        jac = "{0,0,1,0,1,0,-1,0,0}:x:y:z";
    else if(mesh_path.stem().string() == "one-elt-real-rotz" )
        jac = "{0,-1,0,1,0,0,0,0,1}:x:y:z";

    U_h_int(0) = integrate( markedelements(edgeMesh, edges[0]), trans(expr<3,3>(jac)*t0)*myexpr ).evaluate()(0,0);
    U_h_int(1) = integrate( markedelements(edgeMesh, edges[1]), trans(expr<3,3>(jac)*t1)*myexpr ).evaluate()(0,0);
    U_h_int(2) = integrate( markedelements(edgeMesh, edges[2]), trans(expr<3,3>(jac)*t2)*myexpr ).evaluate()(0,0);
    U_h_int(3) = integrate( markedelements(edgeMesh, edges[3]), trans(expr<3,3>(jac)*t3)*myexpr ).evaluate()(0,0);
    U_h_int(4) = integrate( markedelements(edgeMesh, edges[4]), trans(expr<3,3>(jac)*t4)*myexpr ).evaluate()(0,0);
    U_h_int(5) = integrate( markedelements(edgeMesh, edges[5]), trans(expr<3,3>(jac)*t5)*myexpr ).evaluate()(0,0);

    for(int i=0; i<edges.size(); i++)
        {
            double edgeLength = integrate( markedelements(edgeMesh, edges[i]), cst(1.) ).evaluate()(0,0);
            U_h_int(i) /= edgeLength;
        }

#if 0 //Doesn't work for now
    for(int i=0; i<Xh->nLocalDof(); i++)
        {
            CHECK( edgeMesh->hasMarkers( {edges[i]} ) );
            U_h_int(i) = integrate( markedelements(edgeMesh, edges[i]), trans( print(T(),"T=") )*myexpr ).evaluate()(0,0);
            std::cout << "U_h_int(" << i << ")= " << U_h_int(i) << std::endl;
        }
#endif

    // nedelec interpolant using on keyword
    // interpolate on element
    U_h_on.zero();
    U_h_on.on(_range=elements(oneelement_mesh), _expr=myexpr);
    U_h_on_boundary.on(_range=boundaryfaces(oneelement_mesh), _expr=myexpr);

    auto exporter_proj = exporter( _mesh=mesh, _name=( boost::format( "%1%" ) % this->about().appName() ).str() );
    exporter_proj->step( 0 )->add( "U_interpolation_handly_"+mesh_path.stem().string(), U_h_int );
    exporter_proj->step( 0 )->add( "U_interpolation_on_"+mesh_path.stem().string(), U_h_on );
    exporter_proj->save();

    // print coefficient only for reference element
    U_h_int.printMatlab( "U_h_int_" + mesh_path.stem().string() + ".m" );
    U_h_on.printMatlab( "U_h_on_" + mesh_path.stem().string() + ".m" );
    U_h_on_boundary.printMatlab( "U_h_on_boundary_" + mesh_path.stem().string() + ".m" );

    //L2 norm of error
    auto error = vf::project(_space=Xh, _range=elements(oneelement_mesh), _expr=idv(U_h_int) - idv(U_h_on) );
    double L2error = error.l2Norm();
    std::cout << "L2 error (elements) = " << L2error << std::endl;

    auto error_boundary = vf::project(_space=Xh, _range=elements(oneelement_mesh), _expr=idv(U_h_int) - idv(U_h_on_boundary) );
    double L2error_boundary = error_boundary.l2Norm();
    std::cout << "L2 error (boundary) = " << L2error_boundary << std::endl;
    BOOST_CHECK_SMALL( L2error_boundary - L2error, 1e-13 );
}
Beispiel #5
0
int scene::loadObject(string objectid){
    int id = atoi(objectid.c_str());
    if(id!=objects.size()){
        cout << "ERROR: OBJECT ID does not match expected number of objects" << endl;
        return -1;
    }else{
        cout << "Loading Object " << id << "..." << endl;
        geom newObject;
        string line;
        
        //load object type 
        getline(fp_in,line);
        if (!line.empty() && fp_in.good()){
            if(strcmp(line.c_str(), "sphere")==0){
                cout << "Creating new sphere..." << endl;
				newObject.type = SPHERE;
            }else if(strcmp(line.c_str(), "cube")==0){
                cout << "Creating new cube..." << endl;
				newObject.type = CUBE;
            }else{

				string objline = line;
                string name;
                string extension;
                istringstream liness(objline);
                getline(liness, name, '.');
                getline(liness, extension, '.');
                if(strcmp(extension.c_str(), "obj")==0){
                    cout << "Creating new mesh..." << endl;
                    cout << "Reading mesh from " << line << "... " << endl;
					// my code// 
		    		newObject.type = MESH;
					loadMesh(line);

                }else{
                    cout << "ERROR: " << line << " is not a valid object type!" << endl;
                    return -1;
                }
            }
        }
       
	//link material
	getline(fp_in,line);
	if(!line.empty() && fp_in.good())
	{
	    vector<string> tokens = utilityCore::tokenizeString(line);
	    newObject.materialid = atoi(tokens[1].c_str());
	    cout << "Connecting Object " << objectid << " to Material " << newObject.materialid << "..." << endl;
    }
        
	//load frames
    int frameCount = 0;
	getline(fp_in,line);
	vector<glm::vec3> translations;
	vector<glm::vec3> scales;
	vector<glm::vec3> rotations;
        while (!line.empty() && fp_in.good()){
	    
	    //check frame number
	    vector<string> tokens = utilityCore::tokenizeString(line);
            if(strcmp(tokens[0].c_str(), "frame")!=0 || atoi(tokens[1].c_str())!=frameCount){
                cout << "ERROR: Incorrect frame count!" << endl;
                return -1;
            }
	    
	    //load tranformations
	    for(int i=0; i<3; i++){
		glm::vec3 translation; glm::vec3 rotation; glm::vec3 scale;
		getline(fp_in,line);
		tokens = utilityCore::tokenizeString(line);
		if(strcmp(tokens[0].c_str(), "TRANS")==0){
			translations.push_back(glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())));
		}else if(strcmp(tokens[0].c_str(), "ROTAT")==0){
			rotations.push_back(glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())));
		}else if(strcmp(tokens[0].c_str(), "SCALE")==0){
			scales.push_back(glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())));
		}
	    }
	    
	    frameCount++;
	    getline(fp_in,line); 
	}
	
	//move frames into CUDA readable arrays
	newObject.translations = new glm::vec3[frameCount];
	newObject.rotations = new glm::vec3[frameCount];
	newObject.scales = new glm::vec3[frameCount];
	newObject.transforms = new cudaMat4[frameCount];
	newObject.inverseTransforms = new cudaMat4[frameCount];
	newObject.tranposeTranforms= new cudaMat4[frameCount];
	for(int i=0; i<frameCount; i++){
		newObject.translations[i] = translations[i];
		newObject.rotations[i] = rotations[i];
		newObject.scales[i] = scales[i];
		glm::mat4 transform = utilityCore::buildTransformationMatrix(translations[i], rotations[i], scales[i]);
		newObject.transforms[i] = utilityCore::glmMat4ToCudaMat4(transform);
		newObject.inverseTransforms[i] = utilityCore::glmMat4ToCudaMat4(glm::inverse(transform));
		newObject.tranposeTranforms[i] = utilityCore::glmMat4ToCudaMat4(glm::inverse(glm::transpose(transform)));
	}
//	if(newObject.type==CUBE || newObject.type==SPHERE)
//	{
        objects.push_back(newObject);
//	}
	//else if(newObject.type==MESH)
	//{
		//meshes.push_back(newObject); 
//	}
	
	cout << "Loaded " << frameCount << " frames for Object " << objectid << "!" << endl;
        return 1;
    }
}
Beispiel #6
0
int medit0() {
  pMesh    mesh;
  char     data[128],*name;
  int      k,l,ret;
  clock_t  ct;

  /* default */
  //  fprintf(stdout," \n medit0() \n");
  fprintf(stdout," Loading data file(s)\n");
  ct = clock();

  /* enter name */
  if ( !cv.nbm ) {
    fprintf(stdout,"  File name(s) missing. Please enter : ");
    fflush(stdout); fflush(stdin);
    fgets(data,120,stdin);
    if ( !strlen(data) ) {
      fprintf(stdout,"  ## No data\n");
      return(0);
    }

    /* parse file name(s) */
    name = strtok(data," \n");
    while( name ) {
      if ( !cv.mesh[cv.nbm] ) {
        cv.mesh[cv.nbm] = (pMesh)M_calloc(1,sizeof(Mesh),"medit0.mesh");
        if ( !cv.mesh[cv.nbm] )  return(0);
      }
      /*(cv.mesh[cv.nbm])->name = calloc(strlen(name)+1,sizeof(char));*/
      strcpy(cv.mesh[cv.nbm]->name,name);
      name = strtok(NULL," \n\0");
      if ( ++cv.nbm == MAX_MESH )  break;
    }
    if ( !cv.nbm ) return(0);
  }

  if ( !cv.nbm ) { 
    fprintf(stdout,"  Number of mesh missing:. Please enter : "); 
    fflush(stdout); fflush(stdin);
    fgets(data,120,stdin);
    cv.nbm = atoi(data);
  }

  /* read mesh(es) */
  k = 0;
  do {
    if ( !cv.mesh[k] ) {
      cv.mesh[k] = M_calloc(1,sizeof(Mesh),"medit0.mesh");
      if ( !cv.mesh[k] )  return(0);
    }
    mesh = cv.mesh[k];
    mesh->typ = 0;
    ret  = loadMesh(mesh);
    if ( ret < 0 ) {
      mesh->typ = 1;
      ret = inmsh2(mesh);
      if ( !ret ) {
        mesh->typ = 2;
        ret = loadGIS(mesh);
      }
    }
    if ( ret <= 0 ) {
      for (l=k+1; l<cv.nbm; l++)
	    cv.mesh[l-1] = cv.mesh[l];
      cv.nbm--;
      k--;
      continue;
    }

    /* compute mesh box */  
    if ( (mesh->ntet && !mesh->nt) || (mesh->nhex && !mesh->nq) )  
      meshSurf(mesh);
    meshBox(mesh,1);
    if ( !quiet )  meshInfo(mesh);

    /* read metric  */   
    if ( !loadSol(mesh,mesh->name,1) )
      bbfile(mesh);
    if ( !quiet && mesh->nbb )
      fprintf(stdout,"    Solutions  %8d\n",mesh->nbb);
  }
  while ( ++k < cv.nbm );
  cv.nbs = cv.nbm;

  ct = difftime(clock(),ct);
  fprintf(stdout,"  Input seconds:     %.2f\n",
          (double)ct/(double)CLOCKS_PER_SEC);

  return(cv.nbm);
}
Beispiel #7
0
int main()
{
	Engine &engine = Engine::getInstance();

	engine.LoadCore();
	engine.Init();

	//Camera info
	//Matrix4 view = Matrix4::Mat4MakeIdentity();
	//Matrix4 ortho = getOrtho(0, e_SCREEN_WIDTH, 0, e_SCREEN_HEIGHT, 0, 100);
	
	

	//mesh info
	Vertex verts[3] = { { { 0, 30, 0, 1},
						  { 0, 1, 1, 1 } },

					    { { -30, -30, 0, 1 }, 
						  { 1, 1, 0, 1 } },	

						{ { 30, -30, 0, 1 },
						  { 1, 0, 1, 1 } } };

	Triangle tris[1] = { 0, 1, 2 };
	
	//More debuggin'

	//Matrix4 a(1, 2, 4, 6,
	//		  2, 2, 2, 2,
	//		  1, 1, 1, 1,
	//		  4, 4, 4, 4);

	//Matrix4 b(2, 1, 3, 2,
	//		  2, 2, 2, 2,
	//		  1, 1, 1, 1,
	//		  3, 3, 3, 3);

	//Matrix4 c = a - b;

	//a -= b;

	//Matrix4 a_b_answer(3, 3, 7, 8,
	//				   4, 4, 4, 4,
	//				   2, 2, 2, 2,
	//				   7, 7, 7, 1);


	//assert(a == c);
	//printMat4(a);
	//std::cout << std::endl;
	//printMat4(c);
	//system("pause");


	RenderObject ro = loadMesh(verts, 3, tris, 1);
	//create shader program
	GLuint shader = CreateProgram("./shaders/simpleShader.vert",
								  "./shaders/simpleShader.frag");

	Tank blue(ro, shader, Matrix4::Mat4MakeIdentity(), 3);

	blue.m_transform.m_local.v4.x = e_SCREEN_WIDTH / 2;
	blue.m_transform.m_local.v4.y = e_SCREEN_HEIGHT / 2;
	blue.m_transform.m_local.v4.z = 0;
	blue.m_transform.m_local.v4.w = 1;

	Turret blueTurret(ro, shader, blue);

	blueTurret.m_transform.m_local = Matrix4::Mat4MakeIdentity();

	blueTurret.m_transform.m_local.v4.y = 60;
	blueTurret.m_torque = 1.5;

	float currentTime = 0;
	float deltaTime = 0;
	glfwSetTime(0);

	while (engine.Update())
	{
		deltaTime = Time::getInstance().getDeltaTime();

		blue.Draw();
		blueTurret.Draw();

		blue.Update();
		blueTurret.Update();
	}

	engine.Shutdown();
	return 0;
}
Beispiel #8
0
ModelMesh::ModelMesh(std::vector<vertex>& vertices, std::vector<texture>& textures, std::vector<GLuint>& indices) :
	vertices(vertices), textures(textures), indices(indices)
{
	loadMesh();
}
Beispiel #9
0
void GActiveMarker::markerCallback(const visualization_msgs::Marker& marker)
{
	int frameNo;
	bool found, renew;
	string name;
	GActiveMarker * tAM;
	vector<Gadget *>::iterator gadIt;
	
	switch (marker.action)
	{
		case visualization_msgs::Marker::DELETE:
			{
				// Make an appropriate name based on the namespace and marker ID
				name = marker.ns + boost::lexical_cast<std::string>(marker.id);
				
				found = false;
				for (gadIt = boss->gadgets.begin(); gadIt != boss->gadgets.end(); gadIt++)
				{
					if ((*gadIt)->name == name)
					{
						found = true;
						break;
					}
				}
				
				// No marker, leave without a sound
				if (!found)
				{
					break;
				}
				
				(*gadIt)->killMe = true;
				
				break;
			}
		
		// ROS has ADD and MODIFY have the same value...
		case visualization_msgs::Marker::ADD:
		//case visualization_msgs::Marker::MODIFY:
			
			// Make an appropriate name based on the namespace and marker ID
			name = marker.ns + boost::lexical_cast<std::string>(marker.id);

			// Get the associated frame
			frameNo = Frame::findFrame(marker.header.frame_id);

			// If we can't find the frame, or it is invalid leave
			if (frameNo < 0)
			{
				return;
			}
			if (!availableFrames[frameNo].valid)
			{
				return;
			}

			// Look for an existing Gadget with this name
			found = false;
			for (gadIt = boss->gadgets.begin(); gadIt != boss->gadgets.end(); gadIt++)
			{
				if ((*gadIt)->name == name)
				{
					found = true;
					break;
				}
			}

			if (found)
			{
				// We're modifying an existing marker
				tAM = (GActiveMarker * )*gadIt;
			}
			else // !found
			{
				// Create a new marker
				tAM = new GActiveMarker(name);
				
				// Create the gadget for this marker
				boss->addGadget(tAM);
				
				// Have the active marker create a scene node (graphicNode)
				tAM->show(true);
			}

			// Set the Gadget's frame
			tAM->sourceFrame = frameNo;

			// If the marker's nature changes, free up all its allocated graphic memory
			if (found)
			{
				if (tAM->markerType != marker.type)
				{
					tAM->cleanup();
					
					renew = true;

					tAM->markerType = marker.type;
				}
				else 
				{
					renew = false;
				}
			}
			else 
			{
				renew = true;
				
				tAM->markerType = marker.type;
			}
			
			switch (marker.type)
			{
				case visualization_msgs::Marker::ARROW:
					{
						if (renew)
						{
							Shape * shape;
						
							if (!tAM->subGraphicNode)
							{
								tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							}
						
							shape = new Shape(Shape::Cone, tAM->scene, tAM->subGraphicNode);
							tAM->shapes.push_back(shape);
							
							shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
							tAM->shapes.push_back(shape);
						}
						
						Ogre::Vector3 startPoint;
						Ogre::Vector3 endPoint;
						
						if (marker.points.size() > 1)
						{
							startPoint[0] = marker.points[0].x;
							startPoint[1] = marker.points[0].y,
							startPoint[2] = marker.points[0].z;
									
							endPoint[0] = marker.points[1].x;
							endPoint[1] = marker.points[1].y;
							endPoint[2]	= marker.points[1].z;
						}
						else
						{
							if (marker.points.size() == 1)
							{
								tAM->publishStatus(Gadget::WARNING, "To few points to specify an arrow direction, 2 needed");
							}
							
							startPoint[0] = 0;
							startPoint[1] = 0,
							startPoint[2] = 0;
									
							endPoint[0] = 1;
							endPoint[1] = 0;
							endPoint[2]	= 0;
						}
							
						tAM->shapes[0]->alignToLineSegment(startPoint + (endPoint - startPoint) * 0.9,
							endPoint,
							1);
						tAM->shapes[0]->setScale(Ogre::Vector3(marker.scale.y, 
							marker.scale.x * 0.2, 
							marker.scale.y));
							
						tAM->shapes[1]->alignToLineSegment(startPoint,
							endPoint,
							1);
						tAM->shapes[1]->setScale(Ogre::Vector3(marker.scale.y * 0.1, 
							marker.scale.x * 0.8, 
							marker.scale.y * 0.1));
						
						// Set shape properties
						
						tAM->shapes[0]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
							marker.color.b, marker.color.a));

						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added arrow marker");
						}
						
						break;
					}
					
				case visualization_msgs::Marker::CUBE:
				case visualization_msgs::Marker::SPHERE:
				case visualization_msgs::Marker::CYLINDER:
					{
						if (renew)
						{
							Shape * shape;
												
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE:
									shape = new Shape(Shape::Cube, tAM->scene, tAM->graphicNode);
									break;
								case visualization_msgs::Marker::SPHERE:
									shape = new Shape(Shape::Sphere, tAM->scene, tAM->graphicNode);
									break;
								case visualization_msgs::Marker::CYLINDER:
									shape = new Shape(Shape::Cylinder, tAM->scene, tAM->graphicNode);
									break;
							}
							
							tAM->shapes.push_back(shape);
						}
						
						// Set shape properties
						tAM->shapes[0]->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->shapes[0]->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->shapes[0]->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
							marker.scale.z));
						tAM->shapes[0]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
							marker.color.b, marker.color.a));
						
						if (renew)
						{	
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cube marker");
									break;
								case visualization_msgs::Marker::SPHERE:
									tAM->publishStatus(Gadget::OKAY, "Successfully added sphere marker");
									break;
								case visualization_msgs::Marker::CYLINDER:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cylinder marker");
									break;
							}
						}
						break;
					}
				
				case visualization_msgs::Marker::LINE_STRIP:
					{
						unsigned int N;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						// Line count
						N = marker.points.size() - 1;
						
						if (N < 1)
						{
							tAM->publishStatus(Gadget::ERROR, "Insufficient data to draw lines");
							return;
						}
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > N)
						{
							while (tAM->shapes.size() > N)
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < N)
						{
							while (tAM->shapes.size() < N)
							{
								Shape * shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						// Set shapes' properties
						for (i = 0; i < N; i++)
						{
							tAM->shapes[i]->alignToLineSegment(Ogre::Vector3(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z),
								Ogre::Vector3(marker.points[i + 1].x, 
									marker.points[i + 1].y,
									marker.points[i + 1].z),
								marker.scale.x);
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i].r, 
									marker.colors[i].g,
									marker.colors[i].b, 
									marker.colors[i].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added line strip marker");
						}
						
						break;
					}
					
				case visualization_msgs::Marker::LINE_LIST:
					{
						unsigned int N;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						if (marker.points.size() % 2 != 0)
						{
							tAM->publishStatus(Gadget::ERROR, "Need 2xN points to draw N lines");
							return;
						}
						
						// Line count
						N = marker.points.size() / 2;
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > N)
						{
							while (tAM->shapes.size() > N)
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < N)
						{
							while (tAM->shapes.size() < N)
							{
								Shape * shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						
						// Set shapes' properties
						for (i = 0; i < N; i++)
						{
							tAM->shapes[i]->alignToLineSegment(Ogre::Vector3(marker.points[i * 2].x, 
									marker.points[i * 2].y,
									marker.points[i * 2].z),
								Ogre::Vector3(marker.points[i * 2 + 1].x, 
									marker.points[i * 2 + 1].y,
									marker.points[i * 2 + 1].z),
								marker.scale.x);
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i * 2].r, 
									marker.colors[i * 2].g,
									marker.colors[i * 2].b, 
									marker.colors[i * 2].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));	
	
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added line list marker");
						}
						
						break;
					}
				
				case visualization_msgs::Marker::SPHERE_LIST:
				case visualization_msgs::Marker::CUBE_LIST:
					{
						int shapeType;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						switch (marker.type)
						{
							case visualization_msgs::Marker::SPHERE_LIST:
								shapeType = Shape::Sphere;
								break;
								
							case visualization_msgs::Marker::CUBE_LIST:
								shapeType = Shape::Cube;
								break;
						}
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > marker.points.size())
						{
							while (tAM->shapes.size() > marker.points.size())
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < marker.points.size())
						{
							while (tAM->shapes.size() < marker.points.size())
							{
								Shape * shape = new Shape(shapeType, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						// Set shapes' properties
						for (i = 0; i < marker.points.size(); i++)
						{
							tAM->shapes[i]->setPosition(Ogre::Vector3(marker.points[i].x, 
								marker.points[i].y, marker.points[i].z));
								
							tAM->shapes[i]->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
								marker.pose.orientation.x, marker.pose.orientation.y,
								marker.pose.orientation.z));
							
							tAM->shapes[i]->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
								marker.scale.z));
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i].r, marker.colors[i].g,
									marker.colors[i].b, marker.colors[i].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
							
						if (renew)
						{
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE_LIST:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cube list marker");
									break;
								case visualization_msgs::Marker::SPHERE_LIST:
									tAM->publishStatus(Gadget::OKAY, "Successfully added sphere list marker");
									break;
							}
						}
					}
					
					break;
					
				case visualization_msgs::Marker::POINTS:
					{
						
						unsigned int i;
						unsigned int N;
						
						if (renew)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							
							if (marker.points.size() > 0)
							{
								string materialName = name + "PointMat";

								tAM->material = Ogre::MaterialManager::getSingleton().create(materialName.c_str(), 
									Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
								tAM->material->setPointSize(marker.scale.x);
								Ogre::Technique* pT = tAM->material->getTechnique( 0 );
									if( NULL == pT ) pT = tAM->material->createTechnique();
								Ogre::Pass* pP = pT->getPass( 0 );
								if( NULL == pP ) pP = pT->createPass();

								// set parameters
								pP->setVertexColourTracking(Ogre::TVC_AMBIENT);
								pP->setLightingEnabled(false);
								//pP->setDepthCheckEnabled(true);
								//pP->setDepthWriteEnabled(false);
								//pP->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
							
								tAM->manual = tAM->scene->createManualObject(tAM->name + "_manual");
								
								tAM->subGraphicNode->attachObject(tAM->manual);
								
								tAM->manual->setDynamic(true);
								tAM->manual->estimateVertexCount(1000);
								tAM->manual->begin(materialName.c_str(), Ogre::RenderOperation::OT_POINT_LIST);
							}
							else
							{
								tAM->publishStatus(Gadget::WARNING, "No data in message");
							}
						}
						else
						{
							if (marker.points.size() > 0)
							{
								tAM->material->setPointSize(marker.scale.x);
								tAM->manual->beginUpdate(0);
							}
							else
							{
								tAM->publishStatus(Gadget::WARNING, "No data in message");
							}
						}
						
						N = marker.points.size();
						
						// Setting each point's color independently or not?
						if (marker.colors.size() == marker.points.size())
						{
							for (i = 0; i < N; i++)
							{
								tAM->manual->position(marker.points[i].x,
									marker.points[i].y,
									marker.points[i].z);
								tAM->manual->colour(Ogre::ColourValue(marker.colors[i].r,
									marker.colors[i].g,
									marker.colors[i].b,
									marker.colors[i].a));
							}
						}
						else
						{
							tAM->manual->colour(Ogre::ColourValue(marker.color.r,
									marker.color.g,
									marker.color.b,
									marker.color.a));
									
							for (i = 0; i < N; i++)
							{
								tAM->manual->position(marker.points[i].x,
									marker.points[i].y,
									marker.points[i].z);
							}
						}
						
						tAM->manual->end();
						
						//tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
						//	marker.scale.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
					}
					
					if (renew)
					{
						tAM->publishStatus(Gadget::OKAY, "Successfully added points marker");
					}
					
					break;
						
				case visualization_msgs::Marker::TEXT_VIEW_FACING:
					{
						// If we must abandon all of our preallocated data
						if (renew)
						{
							tAM->text = new Ogre::MovableText("TextLabel" + boost::lexical_cast<std::string>(textNameNum),
								marker.text);
							
							// Create host scene nodes
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							tAM->subGraphicNode->attachObject(tAM->text);
						}
						
						// Update movable text properties
						tAM->text->setCaption(marker.text);
						tAM->text->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->text->setCharacterHeight(marker.scale.z);
					
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added view facing text marker");
						}
					
						break;
					}
				
				case visualization_msgs::Marker::TRIANGLE_LIST:
					{
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						// Make sure we 3xN points to make triangles
						if (marker.points.size() % 3 == 0)
						{
							if (marker.points.size() > 0)
							{
								if (renew)
								{			
									tAM->manual = tAM->scene->createManualObject(name + "_manual");
		
									tAM->subGraphicNode->attachObject(tAM->manual);
		
									tAM->manual->setDynamic(true);
									tAM->manual->estimateVertexCount(1000);
									tAM->manual->begin("Surfaces/FlatVertexColour", Ogre::RenderOperation::OT_TRIANGLE_LIST);
								}
								else 
								{
									tAM->manual->beginUpdate(0);
								}
							}
							else 
							{
								tAM->publishStatus(Gadget::WARNING, "No point data");
								return;
							}
						}
						else
						{
							tAM->publishStatus(Gadget::ERROR, "Need 3xN points to draw N triangles");
							return;
						}
	 
						// Handle the cases of colors being populated correctly and not, separately
						if (marker.colors.size() == marker.points.size())
						{
							for (i = 0; i < marker.points.size(); i++)
							{
								tAM->manual->position(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z);	
								tAM->manual->colour(Ogre::ColourValue(marker.colors[i].r,
									marker.colors[i].g,
									marker.colors[i].b,
									marker.colors[i].a));
							}
						}
						else
						{
							tAM->manual->colour(Ogre::ColourValue(marker.color.r,
								marker.color.g,
								marker.color.b,
								marker.color.a));
							for (i = 0; i < marker.points.size(); i++)
							{
								tAM->manual->position(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z);	
							}
						}
	 
						tAM->manual->end();
						
						tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
							marker.scale.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
					
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added triangle list marker");
						}
					
						break;
					}
				
				case visualization_msgs::Marker::MESH_RESOURCE:
					// If something has changed free up old resources
					
					if (!renew && (tAM->meshResource != marker.mesh_resource))
					{
						if (tAM->entity)
						{
							// TODO!! :  Need to destroy scene nodes
							
							tAM->scene->destroyEntity(tAM->entity);
							tAM->entity = NULL;
						}
						renew = true;
					}
					
					if (renew)
					{	
						// Load the mesh
						int gotMaterial;
						tAM->mesh = loadMesh(marker.mesh_resource, gotMaterial);
										
						if (tAM->mesh.isNull())
						{
							tAM->publishStatus(Gadget::ERROR, "Failed to load mesh " + marker.mesh_resource);
							return;
						}
						
						// Create Ogre entity to encapsulate it
						tAM->entity = tAM->scene->createEntity((name + "_Ent").c_str(), marker.mesh_resource);
						
						if (!gotMaterial)
						{
							Ogre::MaterialPtr templateMat = Ogre::MaterialManager::getSingleton().getByName("Template/WhiteNoBlend");
							tAM->entity->setMaterial(templateMat);
							
							tAM->publishStatus(Gadget::WARNING, "No material associated with mesh " + marker.mesh_resource);
						}
	
						tAM->meshResource = marker.mesh_resource;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						tAM->subGraphicNode->attachObject(tAM->entity);
					}
					
					// Update scale and position of the mesh
					
					tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
						marker.scale.z));
					tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
						marker.pose.orientation.x, marker.pose.orientation.y,
						marker.pose.orientation.z));
					tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
						marker.pose.position.y, marker.pose.position.z));
						
					// Update to ensure the graphic is placed at the correct location
					tAM->update();	
						
					if (renew)
					{
						tAM->publishStatus(Gadget::OKAY, "Successfully added mesh marker");
					}
					
					break;
					
			}
			
			if (tAM->boundsVisible)
			{
				tAM->calculateBounds();
				tAM->boundsChanged = true;
			}
			
			break;
	}	
}
Beispiel #10
0
int main(int argc, char** argv)
{
	--argc;
	++argv;

	const int WIDTH = 800;
	const int HEIGHT = 600;

	/*
	*	Create window
	*/
	sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Window", sf::Style::Default, sf::ContextSettings(32));
	
	/*
	*	Initialize GLEW
	*/
	GLenum status = glewInit();
	if(status != GLEW_OK)
	{
		std::cerr << "[F] GLEW NOT INITIALIZED: ";
		std::cerr << glewGetErrorString(status) << std::endl;
	
		window.close();
	
		return -1;
	}
	
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	//glFrontFace(GL_CW);
   	//glCullFace(GL_BACK);
	//glEnable(GL_CULL_FACE);
	glClearDepth(1.f);
	glShadeModel(GL_SMOOTH);

	/*
	*	Create GUI
	*/
	tgui::Gui gui(window);
	tgui::Gui gui2(window);
	gui.setGlobalFont("fonts/DejaVuSans.ttf");
	loadWidgets(gui, gui2, window);
	
	char* args[argc + 1];
	
	/*
	*	load geometry
	*/
	Model cube;
	getArgs(argc, argv, ".obj", args);
	
	if (!args[0])
	{
		std::cerr << "[F] MUST SUPPLY 1+ OBJ FILES IN COMMAND LINE ARGS <filename.obj>" << std::endl;
		exit(-1);
	} //if
	
	cube.mesh = loadMesh(args[0]);
	if (!cube.mesh)
	{
		exit(-1);
	} //if
	
	getArgs(argc, argv, ".scale", args);
	if (args[0])
	{
		cube.scale = glm::vec3(strtof(args[0], NULL));
	} //if
	else
	{
		cube.scale = glm::vec3(1.0f);
	} //else
	
	/*
	*	load shaders
	*/
	Shader vertexShader(GL_VERTEX_SHADER);
	getArgs(argc, argv, ".vs", args);
	vertexShader.loadFromFile(args[0]? args[0] : ".vs");
	vertexShader.compile();
	
	Shader fragmentShader(GL_FRAGMENT_SHADER);
	getArgs(argc, argv, ".fs", args);
	fragmentShader.loadFromFile(args[0]? args[0] : ".fs");
	fragmentShader.compile();
	
	/*
	*	create program
	*/
	ShaderProgram program;
	
	program.attachShader(vertexShader);
	program.attachShader(fragmentShader);
	program.linkProgram();
	
	program.addAttribute("vertexPosition_modelspace");
	program.addAttribute("vertexUV");
	//program.addAttribute("vertexNormal_modelspace");
	
	program.addUniform("MVP");
	program.addUniform("sampler");

	Camera camera;
	
	sf::Event event;
	tgui::Callback callback;
	
	Planet p(&cube);
	
	/*
	*	main loop
	*/
	
	while (window.isOpen())
	{
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					window.close();
				
					break;
				case sf::Event::Resized:
					glViewport(0, 0, event.size.width, event.size.height);
					camera.projection = glm::perspective(45.0f, float(event.size.width)/float(event.size.height), 0.01f, 100.0f);
					
					break;
				default:
					break;
			} //switch
			
			gui.handleEvent(event);
		} //if
		
		while (gui.pollCallback(callback))
		{
			gui.handleEvent(event);
		} //if
		
		window.clear();
		guiDraw(window, gui2);
		glClear(GL_DEPTH_BUFFER_BIT); 
		
		/*
		*	render OpenGL here
		*/
		//glValidateProgram(program.program);
		
		for (Planet* planet : planets)
		{
			render(*planet, camera, program);
		} //for
		
		guiDraw(window, gui);
		
		window.display();
	} //while

	// Clean up after ourselves
	if (window.isOpen())
	{
		window.close();
	} //if
	
	return EXIT_SUCCESS;
} //main
Beispiel #11
0
void Road::draw(VSShaderLib shader, GLint pvm_uniformId,
	GLint vm_uniformId, GLint normal_uniformId) {

	GameObject::drawTextures();

	//Draw Road
	loadMesh(_meshes.at(0), shader);
	pushMatrix(MODEL);

	//
	translate(MODEL, -2.5f, 0.50f, -2.5f);
	rotate(MODEL, 90, 0, 1, 0);
	scale(MODEL, 1.0f, 0.01f, 5.0f);


	renderMesh(_meshes.at(0), pvm_uniformId, vm_uniformId, normal_uniformId);
	popMatrix(MODEL);

	//bottom
	loadMesh(_meshes.at(0), shader);
	pushMatrix(MODEL);

	translate(MODEL, -2.5f, 0.50f, 3.6f);
	rotate(MODEL, 90, 0, 1, 0);
	scale(MODEL, 1.0f, 0.01f, 5.0f);

	renderMesh(_meshes.at(0), pvm_uniformId, vm_uniformId, normal_uniformId);
	popMatrix(MODEL);

	//left
	loadMesh(_meshes.at(0), shader);
	pushMatrix(MODEL);

	translate(MODEL, -3.5f, 0.5f, -3.5f);
	scale(MODEL, 1.0f, 0.01f, 7.1f);


	renderMesh(_meshes.at(0), pvm_uniformId, vm_uniformId, normal_uniformId);
	popMatrix(MODEL);

	//right
	loadMesh(_meshes.at(0), shader);
	pushMatrix(MODEL);

	translate(MODEL, 2.5f, 0.5f, -3.5f);
	scale(MODEL, 1.0f, 0.01f, 7.1f);


	renderMesh(_meshes.at(0), pvm_uniformId, vm_uniformId, normal_uniformId);
	popMatrix(MODEL);

	//Start Marker
	loadMesh(_meshes.at(1), shader);
	pushMatrix(MODEL);

	translate(MODEL, 0.0f, 0.51f, 2.6f);
	scale(MODEL, 0.1f, 0.01f, 1.0f);

	renderMesh(_meshes.at(1), pvm_uniformId, vm_uniformId, normal_uniformId);
	popMatrix(MODEL);

}
void
ThermalBlockMinimalVersion::initModel()
{

    gamma_dir=option(_name="gamma_dir").template as<double>();

    this->setFunctionSpaces( Pch<1>( loadMesh( _mesh=new Mesh<Simplex<2>> ) ) );

    auto mesh = Xh->mesh();

    if( Environment::worldComm().isMasterRank() )
    {
        std::cout << "Number of local dof " << Xh->nLocalDof() << "\n";
        std::cout << "Number of dof " << Xh->nDof() << "\n";
    }

    auto mu_min = Dmu->element();
    auto mu_max = Dmu->element();
    mu_min <<  0.1 , 0.1 , 0.1 , 0.1 , 0.1 , 0.1 , 0.1 , 0.1 ;
    mu_max <<  10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 ;
    Dmu->setMin( mu_min );
    Dmu->setMax( mu_max );

    auto u = Xh->element();
    auto v = Xh->element();

    auto M = backend()->newMatrix( Xh , Xh );

    double mu_min_coeff=0.1;
    // on boundary north we have u=0 so term from weak dirichlet condition
    // vanish in the right hand side
    //rhs
    auto f0 = form1( _test=Xh );
    f0 =  integrate( _range=markedfaces( mesh,"south_domain-1" ), _expr= id( v ) )
        + integrate( _range=markedfaces( mesh,"south_domain-2" ), _expr= id( v ) )
        + integrate( _range=markedfaces( mesh,"south_domain-3" ), _expr= id( v ) );
    this->addRhs( { f0, "1" } );

    //lhs
    auto a0 = form2( _trial=Xh, _test=Xh);
    a0 = integrate( markedelements( mesh, "domain-1" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a0 , "1" } );
    auto a1 = form2( _trial=Xh, _test=Xh);
    a1 = integrate( markedelements( mesh, "domain-2" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a1 , "mu0" } );
    auto a2 = form2( _trial=Xh, _test=Xh);
    a2 = integrate( markedelements( mesh, "domain-3" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a2 , "mu1" } );
    auto a3 = form2( _trial=Xh, _test=Xh);
    a3 = integrate( markedelements( mesh, "domain-4" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a3 , "mu2" } );
    auto a4 = form2( _trial=Xh, _test=Xh);
    a4 = integrate( markedelements( mesh, "domain-5" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a4 , "mu3" } );
    auto a5 = form2( _trial=Xh, _test=Xh);
    a5 = integrate( markedelements( mesh, "domain-6" ), gradt( u )*trans( grad( v ) ) );
    this->addLhs( { a5 , "mu4" } );
    auto a6 = form2( _trial=Xh, _test=Xh);
    a6 = integrate( markedelements( mesh, "domain-7" ), gradt( u )*trans( grad( v ) ) )
        +integrate( markedfaces( mesh, "north_domain-7" ),
                   -gradt( u )*vf::N()*id( v )
                   -grad( u )*vf::N()*idt( v )
                   );
    this->addLhs( { a6 , "mu5" } );
    auto a7 = form2( _trial=Xh, _test=Xh);
    a7 = integrate( markedelements( mesh, "domain-8" ), gradt( u )*trans( grad( v ) ) )
        +integrate( markedfaces( mesh, "north_domain-8" ),
                   -gradt( u )*vf::N()*id( v )
                   -grad( u )*vf::N()*idt( v )
                   );
    this->addLhs( { a7 , "mu6" } );
    auto a8 = form2( _trial=Xh, _test=Xh);
    a8 = integrate( markedelements( mesh, "domain-9" ), gradt( u )*trans( grad( v ) ) )
        +integrate( markedfaces( mesh, "north_domain-9" ),
                   -gradt( u )*vf::N()*id( v )
                   -grad( u )*vf::N()*idt( v )
                   );
    this->addLhs( { a8 , "mu7" } );
    auto a9 = form2( _trial=Xh, _test=Xh);
    a9 = integrate( markedfaces( mesh, "north_domain-7" ),gamma_dir*idt( u )*id( v )/h() )
        +integrate( markedfaces( mesh, "north_domain-8" ),gamma_dir*idt( u )*id( v )/h() )
        +integrate( markedfaces( mesh, "north_domain-9" ),gamma_dir*idt( u )*id( v )/h() );
    this->addLhs( { a9 , "1" } );


    form2( Xh, Xh, M ) = integrate( markedelements( mesh, "domain-1" ), gradt( u )*trans( grad( v ) )  );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-2" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-3" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-4" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-5" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-6" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-7" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-8" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) += integrate( markedelements( mesh, "domain-9" ), gradt( u )*trans( grad( v ) ) * mu_min_coeff );
    form2( Xh, Xh, M ) +=  integrate( markedfaces( mesh, "north_domain-7" ),
                                      -gradt( u )*vf::N()*id( v ) * mu_min_coeff
                                      -grad( u )*vf::N()*idt( v ) * mu_min_coeff
                                      );
    form2( Xh, Xh, M ) +=  integrate( markedfaces( mesh, "north_domain-8" ),
                                      -gradt( u )*vf::N()*id( v ) * mu_min_coeff
                                      -grad( u )*vf::N()*idt( v ) * mu_min_coeff
                                      );
    form2( Xh, Xh, M ) +=  integrate( markedfaces( mesh, "north_domain-9" ),
                                      -gradt( u )*vf::N()*id( v ) * mu_min_coeff
                                      -grad( u )*vf::N()*idt( v ) * mu_min_coeff
                                      );
    form2( Xh, Xh, M ) += integrate( markedfaces( mesh, "north_domain-7" ),gamma_dir*idt( u )*id( v )/h() );
    form2( Xh, Xh, M ) += integrate( markedfaces( mesh, "north_domain-8" ),gamma_dir*idt( u )*id( v )/h() );
    form2( Xh, Xh, M ) += integrate( markedfaces( mesh, "north_domain-9" ),gamma_dir*idt( u )*id( v )/h() );
    this->addEnergyMatrix( M );

}//initModel()
	void loadMeshes()
	{
		loadMesh("./../data/models/plane_z.3ds", &meshes.plane, vertexLayout, 0.4f);
		loadMesh("./../data/models/teapot.3ds", &meshes.teapot, vertexLayout, 0.3f);
		loadMesh("./../data/models/sphere.3ds", &meshes.sphere, vertexLayout, 0.3f);
	}
Beispiel #14
0
bool InputGeom::loadGeomSet(rcContext* ctx, const std::string& filepath)
{
	char* buf = 0;
	FILE* fp = fopen(filepath.c_str(), "rb");
	if (!fp)
		return false;
	fseek(fp, 0, SEEK_END);
	int bufSize = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	buf = new char[bufSize];
	if (!buf)
	{
		fclose(fp);
		return false;
	}
	size_t readLen = fread(buf, bufSize, 1, fp);
	fclose(fp);
	if (readLen != 1)
	{
		delete[] buf;
		return false;
	}
	
	m_offMeshConCount = 0;
	m_volumeCount = 0;
	delete m_mesh;
	m_mesh = 0;

	char* src = buf;
	char* srcEnd = buf + bufSize;
	char row[512];
	while (src < srcEnd)
	{
		// Parse one row
		row[0] = '\0';
		src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
		if (row[0] == 'f')
		{
			// File name.
			const char* name = row+1;
			// Skip white spaces
			while (*name && isspace(*name))
				name++;
			if (*name)
			{
				if (!loadMesh(ctx, name))
				{
					delete [] buf;
					return false;
				}
			}
		}
		else if (row[0] == 'c')
		{
			// Off-mesh connection
			if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS)
			{
				float* v = &m_offMeshConVerts[m_offMeshConCount*3*2];
				int bidir, area = 0, flags = 0;
				float rad;
				sscanf(row+1, "%f %f %f  %f %f %f %f %d %d %d",
					   &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
				m_offMeshConRads[m_offMeshConCount] = rad;
				m_offMeshConDirs[m_offMeshConCount] = (unsigned char)bidir;
				m_offMeshConAreas[m_offMeshConCount] = (unsigned char)area;
				m_offMeshConFlags[m_offMeshConCount] = (unsigned short)flags;
				m_offMeshConCount++;
			}
		}
		else if (row[0] == 'v')
		{
			// Convex volumes
			if (m_volumeCount < MAX_VOLUMES)
			{
				ConvexVolume* vol = &m_volumes[m_volumeCount++];
				sscanf(row+1, "%d %d %f %f", &vol->nverts, &vol->area, &vol->hmin, &vol->hmax);
				for (int i = 0; i < vol->nverts; ++i)
				{
					row[0] = '\0';
					src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
					sscanf(row, "%f %f %f", &vol->verts[i*3+0], &vol->verts[i*3+1], &vol->verts[i*3+2]);
				}
			}
		}
		else if (row[0] == 's')
		{
			// Settings
			m_hasBuildSettings = true;
			sscanf(row + 1, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d %f %f %f %f %f %f %f",
							&m_buildSettings.cellSize,
							&m_buildSettings.cellHeight,
							&m_buildSettings.agentHeight,
							&m_buildSettings.agentRadius,
							&m_buildSettings.agentMaxClimb,
							&m_buildSettings.agentMaxSlope,
							&m_buildSettings.regionMinSize,
							&m_buildSettings.regionMergeSize,
							&m_buildSettings.edgeMaxLen,
							&m_buildSettings.edgeMaxError,
							&m_buildSettings.vertsPerPoly,
							&m_buildSettings.detailSampleDist,
							&m_buildSettings.detailSampleMaxError,
							&m_buildSettings.partitionType,
							&m_buildSettings.navMeshBMin[0],
							&m_buildSettings.navMeshBMin[1],
							&m_buildSettings.navMeshBMin[2],
							&m_buildSettings.navMeshBMax[0],
							&m_buildSettings.navMeshBMax[1],
							&m_buildSettings.navMeshBMax[2],
							&m_buildSettings.tileSize);
		}
	}
	
	delete [] buf;
	
	return true;
}
Beispiel #15
0
ChOgreMeshBase::ChOgreMeshBase(Ogre::SceneManager* SceneManager, const std::string& MeshPath) {
    assignSceneManager(SceneManager);
    loadMesh(MeshPath);
}
/*! Loads the scene from a file and creates materials with textures, the 
meshes and the nodes for the scene graph. Materials, textures and meshes are
added to the according vectors of SLScene for later deallocation.
*/
SLNode* SLAssimpImporter::load(SLstring file,           //!< File with path or on default path
                               SLbool loadMeshesOnly,   //!< Only load nodes with meshes
                               SLuint flags)            //!< Import flags (see assimp/postprocess.h)
{
    // clear the intermediate data
    clear();

    // Check existance
    if (!SLFileSystem::fileExists(file))
    {   file = defaultPath + file;
        if (!SLFileSystem::fileExists(file))
        {   SLstring msg = "SLAssimpImporter: File not found: " + file + "\n";
            SL_WARN_MSG(msg.c_str());
            return nullptr;
        }
    }

    // Import file with assimp importer
    Assimp::Importer ai;
    const aiScene* scene = ai.ReadFile(file.c_str(), (SLuint)flags);
    if (!scene)
    {   SLstring msg = "Failed to load file: " + file + "\n" + ai.GetErrorString() + "\n";
        SL_WARN_MSG(msg.c_str());
        return nullptr;
    }

    // initial scan of the scene
    performInitialScan(scene);

    // load skeleton
    loadSkeleton(nullptr, _skeletonRoot);

    // load materials
    SLstring modelPath = SLUtils::getPath(file);
    SLVMaterial materials;
    for(SLint i = 0; i < (SLint)scene->mNumMaterials; i++)
        materials.push_back(loadMaterial(i, scene->mMaterials[i], modelPath));

    // load meshes & set their material
    std::map<int, SLMesh*> meshMap;  // map from the ai index to our mesh
    for(SLint i = 0; i < (SLint)scene->mNumMeshes; i++)
    {   SLMesh* mesh = loadMesh(scene->mMeshes[i]);
        if (mesh != 0)
        {   mesh->mat = materials[scene->mMeshes[i]->mMaterialIndex];
            _meshes.push_back(mesh);
            meshMap[i] = mesh;
        } else SL_LOG("SLAsssimpImporter::load failed: %s\nin path: %s\n", file.c_str(), modelPath.c_str());
    }

    // load the scene nodes recursively
    _sceneRoot = loadNodesRec(nullptr, scene->mRootNode, meshMap, loadMeshesOnly);

    // load animations
    vector<SLAnimation*> animations;
    for (SLint i = 0; i < (SLint)scene->mNumAnimations; i++)
        animations.push_back(loadAnimation(scene->mAnimations[i]));

    logMessage(LV_minimal, "\n---------------------------\n\n");

    return _sceneRoot;
}
Beispiel #17
0
	void loadMeshes()
	{
		loadMesh("./../data/models/sphere.obj", &meshes.object, vertexLayout, 0.05f);
		loadMesh("./../data/models/cube.obj", &meshes.skybox, vertexLayout, 0.05f);
	}
Beispiel #18
0
	void loadMeshes()
	{
		loadMesh(getAssetPath() + "models/lowpoly/bearmug.dae", &meshes.object, vertexLayout, 4.0f);
	}
	void loadAssets()
	{
		loadMesh(getAssetPath() + "models/tunnel_cylinder.dae", &meshes.tunnel, vertexLayout, 1.0f);
		loadTexture(getAssetPath() + "textures/metalplate_nomips_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, false);
	}
Beispiel #20
0
const aiScene* MeshShape::loadMesh(const std::string& _fileName)
{
    const auto retriever = std::make_shared<common::LocalResourceRetriever>();
    return loadMesh("file://" + _fileName, retriever);
}
Beispiel #21
0
Level1Part2::Level1Part2() : MapPart(2)
{
	loadMesh("GameResources\\Levels\\level1\\part2\\part.obj");	
	loadMaterial();
	initGameObjects();
}
Beispiel #22
0
int __cdecl buildMeshFromFile(int userId, const char* inputFilename, const char* navmeshFilename, BuildMeshCallback callback, int numCores) 
{
	WCellBuildContext ctx;
	dtNavMesh* mesh = NULL;

	if (navmeshFilename) {
		// load navmesh from file
		mesh = loadMesh(navmeshFilename);
	}
	
	if (!mesh) { 
		InputGeom geom;
		dtNavMeshQuery* navMeshQuery;

		// no navmesh has been loaded
		// Load input mesh
		if (!geom.loadMesh(&ctx, inputFilename)) {
			return 0;
		}

		// build nav-mesh
		mesh = buildMesh(&geom, &ctx, numCores);
		if (!mesh) {
			// building failed
			return 0;
		}

		if (navmeshFilename) {
			// save to file
			saveMesh(navmeshFilename, mesh);
		}
	}

	//int tileCount = 0;
	int vertCount = 0;
	int polyCount = 0;
	int totalPolyVertCount = 0;

	float* allVerts;
	unsigned char* polyVertCounts;
	unsigned int* polyVerts;
	unsigned int* polyNeighbors;
	unsigned short* polyFlags;
	unsigned char* polyAreasAndTypes;

	// count sizes and offsets
	unsigned int* tilePolyIndexOffsets = new unsigned int[mesh->getMaxTiles()];

	int maxTiles = mesh->getMaxTiles();
	//int maxTiles = 1;
	for (int i = 0; i < maxTiles; ++i)
	{
		const dtMeshTile* tile = ((const dtNavMesh*)mesh)->getTile(i);
		if (!tile || !tile->header || !tile->dataSize) continue;

		//tileCount++;
		tilePolyIndexOffsets[i] = polyCount;

		polyCount += tile->header->polyCount;
		vertCount += tile->header->vertCount;

		for (int j = 0; j < tile->header->polyCount; j++) {
			totalPolyVertCount += tile->polys[j].vertCount;
		}
	}

	// allocate arrays
	allVerts = new float[vertCount * 3];
	polyVertCounts = new unsigned char[polyCount];
	polyVerts = new unsigned int[totalPolyVertCount];
	polyNeighbors = new unsigned int[totalPolyVertCount];
	polyFlags = new unsigned short[polyCount];
	polyAreasAndTypes = new unsigned char[polyCount];

	int p = 0;
	int v = 0;
	int polyIndexOffset = 0;


	// copy data
	// iterate tiles
	for (int i = 0; i < maxTiles; ++i)
	{
		const dtMeshTile* tile = ((const dtNavMesh*)mesh)->getTile(i);
		if (!tile || !tile->header || !tile->dataSize) continue;

		memcpy(&allVerts[v], tile->verts, tile->header->vertCount * sizeof(float) * 3);

		int vc = v/3;

		// iterate polygons
		for (int j = 0; j < tile->header->polyCount; j++) {
			int absolutePolyIndex = p+j;
			dtPoly& poly = tile->polys[j];

			polyVertCounts[absolutePolyIndex] = poly.vertCount;

			// iterate polygon vertices and edges
			for (int k = 0; k < poly.vertCount; k++) {
				int absolutePolyVertIndex = polyIndexOffset + k;

				polyVerts[absolutePolyVertIndex] = vc + poly.verts[k];

				// find absolute index of neighbor poly
				unsigned short neiRef = poly.neis[k];
				unsigned int idx = (unsigned int)-1;
				if (neiRef & DT_EXT_LINK)
				{
					// Tile border edge -> find linked polygon
					for (unsigned int l = poly.firstLink; l != DT_NULL_LINK; l = tile->links[l].next)
					{
						const dtLink* link = &tile->links[l];
						if (link->ref != 0 && link->edge == k)
						{
							// lookup linked neighbor tile and poly
							unsigned int salt, neigTile, neiPoly;
							mesh->decodePolyId(link->ref, salt, neigTile, neiPoly);

							// absolute poly index
							idx = tilePolyIndexOffsets[neigTile] + neiPoly;

							//const dtMeshTile* t = ((const dtNavMesh*)mesh)->getTile(neigTile);
							assert(neigTile < maxTiles-1 || idx < tilePolyIndexOffsets[neigTile+1]);
							//idx = (unsigned int)-1;
						}
					}
				}
				else if (neiRef)
				{
					// Tile-internal edge
					idx = tilePolyIndexOffsets[i] + (unsigned int)(neiRef - 1);
				}

				assert((int)idx == -1 || idx < polyCount);

				polyNeighbors[absolutePolyVertIndex] = idx;
			}
			polyIndexOffset += poly.vertCount;
		}

		v += tile->header->vertCount * 3;
		p += tile->header->polyCount;
	}
	
	assert(v/3 == vertCount);

	printf("Preparing navmesh with %d vertices...\n", vertCount);

	callback(
		userId, 
		vertCount * 3, 
		polyCount,
		allVerts, 
		totalPolyVertCount, 
		polyVertCounts, 
		polyVerts, 
		polyNeighbors, 
		polyFlags,
		polyAreasAndTypes
		);
	
	delete[] allVerts;
	delete[] polyVertCounts;
	delete[] polyVerts;
	delete[] polyNeighbors;
	delete[] polyFlags;
	delete[] polyAreasAndTypes;
	delete[] tilePolyIndexOffsets;
	CleanupAfterBuild();

	return 1;
}
vector< shared_ptr<ModelData> > ModelLoader::loadModel(const string& filename,
                                                       const QOpenGLShaderProgramPtr& shader)
{
    m_shader = shader;

    Assimp::Importer Importer;
    const aiScene* scene = Importer.ReadFile(filename.c_str(),
                                             aiProcessPreset_TargetRealtime_MaxQuality |
                                             aiProcess_FlipUVs);

    if(scene == nullptr)
    {
        qFatal(qPrintable(QObject::tr("Error parsing : %1 -> %2").arg(filename.c_str()).arg(Importer.GetErrorString())));
        exit(1);
    }
    else if(scene->HasTextures())
    {
        qFatal("Support for meshes with embedded textures is not implemented");
        exit(1);
    }

    vector<shared_ptr<ModelData>> modelData = vector<shared_ptr<ModelData>>();
    modelData.resize(scene->mNumMeshes);

    qDebug() << "Model has" << modelData.size() << "meshes";

    unsigned int numVertices = 0;
    unsigned int numIndices  = 0;

    for(unsigned int i = 0; i < modelData.size(); i++)
    {
        numVertices += scene->mMeshes[i]->mNumVertices;
        numIndices  += scene->mMeshes[i]->mNumFaces * 3;
    }

    m_positions.reserve(numVertices);
    m_colors.reserve(numVertices);
    m_normals.reserve(numVertices);
    m_texCoords.reserve(numVertices);
    m_tangents.reserve(numVertices);
    m_indices.reserve(numIndices);

    numVertices = 0;
    numIndices  = 0;

    for(unsigned int i = 0; i < modelData.size(); i++)
    {
        modelData[i] = make_shared<ModelData>();

        modelData[i]->meshData     = loadMesh(i, numVertices, numIndices, scene->mMeshes[i]);
        modelData[i]->textureData  = loadTexture(filename, scene->mMaterials[scene->mMeshes[i]->mMaterialIndex]);
        modelData[i]->materialData = loadMaterial(i, scene->mMaterials[scene->mMeshes[i]->mMaterialIndex]);

        numVertices += scene->mMeshes[i]->mNumVertices;
        numIndices  += scene->mMeshes[i]->mNumFaces * 3;
    }

    prepareVertexBuffers();

    qDebug() << "Model has" << numVertices << "vertices";

    return modelData;
}
bool InputGeom::load(rcContext* ctx, string filePath)
{
	char* buf = 0;
	FILE* fp = fopen(filePath.c_str(), "rb");
	if (!fp)
		return false;
	fseek(fp, 0, SEEK_END);
	int bufSize = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	buf = new char[bufSize];
	if (!buf)
	{
		fclose(fp);
		return false;
	}
	size_t readLen = fread(buf, bufSize, 1, fp);
	fclose(fp);
	if (readLen != 1)
	{
		delete[] buf;
		return false;
	}
	
	m_offMeshConCount = 0;
	m_volumes.clear();
	delete m_mesh;
	m_mesh = nullptr;

	char* src = buf;
	char* srcEnd = buf + bufSize;
	char row[512];
	while (src < srcEnd)
	{
		// Parse one row
		row[0] = '\0';
		src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
		if (row[0] == 'f')
		{
			// File name.
			const char* name = row+1;
			// Skip white spaces
			while (*name && isspace(*name))
				name++;
			if (*name)
			{
				if (!loadMesh(ctx, name))
				{
					delete [] buf;
					return false;
				}
			}
		}
		else if (row[0] == 'c')
		{
			// Off-mesh connection
			if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS)
			{
				float* v = &m_offMeshConVerts[m_offMeshConCount*3*2];
				int bidir, area = 0, flags = 0;
				float rad;
				sscanf(row+1, "%f %f %f  %f %f %f %f %d %d",
					   &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
				m_offMeshConRads[m_offMeshConCount] = rad;
				m_offMeshConDirs[m_offMeshConCount] = (unsigned char)bidir;
				m_offMeshConAreaMask[m_offMeshConCount] = (navAreaMask)area;
				m_offMeshConCount++;
			}
		}
		else if (row[0] == 'v')
		{
			// Convex volumes
			m_volumes.emplace_back();
			ConvexVolume& vol = m_volumes.back();
			sscanf(row + 1, "%d %d %f %f", &vol.nverts, &vol.areaMask, &vol.hmin, &vol.hmax);
			for (int i = 0; i < vol.nverts; ++i)
			{
				row[0] = '\0';
				src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
				sscanf(row, "%f %f %f", &vol.verts[i * 3 + 0], &vol.verts[i * 3 + 1], &vol.verts[i * 3 + 2]);
				
			}
		}
	}
	
	delete [] buf;
	
	return true;
}
bool InputGeom::load(const char* filePath)
{
	char* buf = 0;
	FILE* fp = fopen(filePath, "rb");
	if (!fp)
		return false;
	fseek(fp, 0, SEEK_END);
	int bufSize = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	buf = new char[bufSize];
	if (!buf)
	{
		fclose(fp);
		return false;
	}
	fread(buf, bufSize, 1, fp);
	fclose(fp);
	
	m_offMeshConCount = 0;
	m_volumeCount = 0;
	delete m_mesh;
	m_mesh = 0;

	char* src = buf;
	char* srcEnd = buf + bufSize;
	char row[512];
	while (src < srcEnd)
	{
		// Parse one row
		row[0] = '\0';
		src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
		if (row[0] == 'f')
		{
			// File name.
			const char* name = row+1;
			// Skip white spaces
			while (*name && isspace(*name))
				name++;
			if (*name)
			{
				if (!loadMesh(name))
				{
					delete [] buf;
					return false;
				}
			}
		}
		else if (row[0] == 'c')
		{
			// Off-mesh connection
			if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS)
			{
				float* v = &m_offMeshConVerts[m_offMeshConCount*3*2];
				int bidir, area = 0, flags = 0;
				float rad;
				sscanf(row+1, "%f %f %f  %f %f %f %f %d %d %d",
					   &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
				m_offMeshConRads[m_offMeshConCount] = rad;
				m_offMeshConDirs[m_offMeshConCount] = (unsigned char)bidir;
				m_offMeshConAreas[m_offMeshConCount] = (unsigned char)area;
				m_offMeshConFlags[m_offMeshConCount] = (unsigned short)flags;
				m_offMeshConCount++;
			}
		}
		else if (row[0] == 'v')
		{
			// Convex volumes
			if (m_volumeCount < MAX_VOLUMES)
			{
				ConvexVolume* vol = &m_volumes[m_volumeCount++];
				sscanf(row+1, "%d %d %f %f", &vol->nverts, &vol->area, &vol->hmin, &vol->hmax);
				for (int i = 0; i < vol->nverts; ++i)
				{
					row[0] = '\0';
					src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
					sscanf(row, "%f %f %f", &vol->verts[i*3+0], &vol->verts[i*3+1], &vol->verts[i*3+2]);
				}
			}
		}
	}
	
	delete [] buf;
	
	return true;
}
Beispiel #26
0
	void loadMeshes()
	{
		loadMesh(getAssetPath() + "models/lowpoly/deer.dae", &meshes.object, vertexLayout, 1.0f);
	}
SWViewerInterface::SWViewerInterface(QApplication *parent) : m_uiViewer(new Ui::SWUI_Viewer), m_bDesactiveUpdateParameters(false), m_bGLFullScreen(false)
{
    // set absolute path
        m_absolutePath = QDir::currentPath() + "/";

    // init main widget
    m_uiViewer->setupUi(this);
    this->setWindowTitle(QString("SWoOz : Viewer"));
    this->setWindowIcon(QIcon(m_absolutePath + "../data/images/logos/icon_swooz_viewer.png"));

    // middle container
        QHBoxLayout *l_pGLContainerLayout = new QHBoxLayout();
        m_pGLContainer = new QWidget();
        QGLFormat l_glFormat;
        l_glFormat.setVersion( 4, 3 );
        l_glFormat.setProfile(  QGLFormat::CompatibilityProfile);
        l_glFormat.setSampleBuffers( true );
        QGLContext *l_glContext = new QGLContext(l_glFormat);
        m_pGLMultiObject = new SWGLMultiObjectWidget(l_glContext, m_pGLContainer);
        l_pGLContainerLayout->addWidget(m_pGLMultiObject);
        l_pGLContainerLayout->layout()->setContentsMargins(0,0,0,0);
        m_pGLContainer->setLayout(l_pGLContainerLayout);
        m_uiViewer->glScene->addWidget(m_pGLContainer);

    // init worker
        m_pWViewer = new SWViewerWorker();

    // init connections
        // menu
            QObject::connect(m_uiViewer->actionExit, SIGNAL(triggered()), parent, SLOT(quit()));
            QObject::connect(m_uiViewer->actionOnline_documentation, SIGNAL(triggered()), this, SLOT(openOnlineDocumentation()));
            QObject::connect(m_uiViewer->actionAbout, SIGNAL(triggered()), this, SLOT(openAboutWindow()));
        QObject::connect(m_uiViewer->pbLoadCloud, SIGNAL(clicked()), this, SLOT(loadCloud()));
        QObject::connect(m_uiViewer->pbLoadMesh, SIGNAL(clicked()), this, SLOT(loadMesh()));
        QObject::connect(m_uiViewer->pbDeleteCloud, SIGNAL(clicked()), this, SLOT(deleteCloud()));
        QObject::connect(m_uiViewer->pbDeleteMesh, SIGNAL(clicked()), this, SLOT(deleteMesh()));
        QObject::connect(m_uiViewer->pbSetTexture, SIGNAL(clicked()), this, SLOT(setTexture()));

        QObject::connect(m_uiViewer->lwClouds, SIGNAL(currentRowChanged(int)), this, SLOT(updateCloudInterfaceParameters()));
        QObject::connect(m_uiViewer->lwMeshes, SIGNAL(currentRowChanged(int)), this, SLOT(updateMeshInterfaceParameters()));
        QObject::connect(m_uiViewer->lwClouds, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(updateCloudInterfaceParameters(QListWidgetItem*)));
        QObject::connect(m_uiViewer->lwMeshes, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(updateMeshInterfaceParameters(QListWidgetItem*)));

        QObject::connect(m_uiViewer->lwClouds, SIGNAL(currentRowChanged(int)), m_pWViewer, SLOT(updateCloudAnimationPath(int)));
        QObject::connect(m_uiViewer->lwMeshes, SIGNAL(currentRowChanged(int)), m_pWViewer, SLOT(updateMeshAnimationPath(int)));
        QObject::connect(this, SIGNAL(cloudCurrentRowChanged(int)), m_pWViewer, SLOT(updateCloudAnimationPath(int)));
        QObject::connect(this, SIGNAL(meshCurrentRowChanged(int)), m_pWViewer, SLOT(updateMeshAnimationPath(int)));
        QObject::connect(m_uiViewer->lwClouds, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(updateCloudAnimationPath(QListWidgetItem*)));
        QObject::connect(m_uiViewer->lwMeshes, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(updateMeshAnimationPath(QListWidgetItem*)));


        // update interface
            QObject::connect(m_uiViewer->dsbRX, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbRY, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbRZ, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbTrX, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbTrY, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbTrZ, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbScaling, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));

            QObject::connect(m_uiViewer->cbDisplayLines, SIGNAL(clicked()), this, SLOT(updateParameters()));
            QObject::connect(m_uiViewer->cbVisible, SIGNAL(clicked()), this, SLOT(updateParameters()));
            QObject::connect(m_uiViewer->rbDisplayOriginalColor, SIGNAL(clicked()), this, SLOT(updateParameters()));
            QObject::connect(m_uiViewer->rbDisplayTexture, SIGNAL(clicked()), this, SLOT(updateParameters()));
            QObject::connect(m_uiViewer->rbDisplayUnicolor, SIGNAL(clicked()), this, SLOT(updateParameters()));

            QObject::connect(m_uiViewer->sbColorB, SIGNAL(valueChanged(int)), this, SLOT(updateParameters(int)));
            QObject::connect(m_uiViewer->sbColorG, SIGNAL(valueChanged(int)), this, SLOT(updateParameters(int)));
            QObject::connect(m_uiViewer->sbColorR, SIGNAL(valueChanged(int)), this, SLOT(updateParameters(int)));

            QObject::connect(m_uiViewer->dsbLightX, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbLightY, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbLightZ, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));

            QObject::connect(m_uiViewer->leTexturePath, SIGNAL(textChanged(QString)), this, SLOT(updateParameters(QString)));

            QObject::connect(m_uiViewer->dsbAmbiantLight1, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbAmbiantLight2, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbAmbiantLight3, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbDiffusLight1, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbDiffusLight2, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbDiffusLight3, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbSpecularLight1, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbSpecularLight2, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbSpecularLight3, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbAmbiantK, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbDiffusK, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbSpecularK, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
            QObject::connect(m_uiViewer->dsbSpecularP, SIGNAL(valueChanged(double)), this, SLOT(updateParameters(double)));
        // push buttons
            QObject::connect(m_uiViewer->pbSetCamera, SIGNAL(clicked()), this, SLOT(setCameraToCurrentItem()));
            QObject::connect(m_uiViewer->pbResetCamera, SIGNAL(clicked()), m_pGLMultiObject, SLOT(resetCamera()));
            QObject::connect(m_uiViewer->pbLaunchAllAnim, SIGNAL(clicked()), m_pWViewer, SLOT(startLoop()));
            QObject::connect(m_uiViewer->pbSetModFile, SIGNAL(clicked()), this, SLOT(loadModFile()));
            QObject::connect(m_uiViewer->pbSetSeqFile, SIGNAL(clicked()), this, SLOT(loadSeqFile()));
            QObject::connect(m_uiViewer->pbSetMeshCorr, SIGNAL(clicked()), this, SLOT(loadMeshCorrFile()));

        // fullscreen
            QObject::connect(m_pGLMultiObject, SIGNAL(enableFullScreen()), this, SLOT(enableGLFullScreen()));                        
            QObject::connect(m_pGLMultiObject, SIGNAL(disableFullScreen()), this, SLOT(disableGLFullScreen()));

        // worker
            QObject::connect(this,  SIGNAL(stopLoop()), m_pWViewer, SLOT(stopLoop()));
            QObject::connect(this, SIGNAL(setModFilePath(bool,int,QString)), m_pWViewer, SLOT(setModFile(bool,int,QString)));
            QObject::connect(this, SIGNAL(setSeqFilePath(bool,int,QString)), m_pWViewer, SLOT(setSeqFile(bool,int,QString)));
            QObject::connect(this, SIGNAL(setCorrFilePath(bool,int,QString)), m_pWViewer, SLOT(setCorrFilePath(bool,int,QString)));
            QObject::connect(m_pWViewer, SIGNAL(sendAnimationPathFile(QString,QString,QString)), this, SLOT(updateAnimationPathFileDisplay(QString,QString,QString)));
            QObject::connect(this, SIGNAL(deleteAnimation(bool,int)), m_pWViewer, SLOT(deleteAnimation(bool,int)));
            QObject::connect(this, SIGNAL(addAnimation(bool)), m_pWViewer, SLOT(addAnimation(bool)));
            QObject::connect(m_pWViewer, SIGNAL(sendOffsetAnimation(SWAnimationSendDataPtr)),m_pGLMultiObject, SLOT(setAnimationOffset(SWAnimationSendDataPtr)),Qt::DirectConnection);
//            QObject::connect(m_pWViewer, SIGNAL(sendOffsetAnimation(SWAnimationSendDataPtr)),m_pGLMultiObject, SLOT(setAnimationOffset(SWAnimationSendDataPtr)));
            QObject::connect(m_pWViewer, SIGNAL(startAnimation(bool,int)), m_pGLMultiObject, SLOT(beginAnimation(bool,int)));

            QObject::connect(m_pWViewer, SIGNAL(drawSceneSignal()), m_pGLMultiObject, SLOT(updateGL()));


            setStyleSheet("QGroupBox { padding: 10 0px 0 0px; color: blue; border: 1px solid gray; border-radius: 5px; margin-top: 1ex; /* leave space at the top for the title */}");


    // init thread
        m_pWViewer->moveToThread(&m_TViewer);
        m_TViewer.start();
}
Beispiel #28
0
EMIModel::EMIModel(const Common::String &filename, Common::SeekableReadStream *data, EMIModel *parent) : _fname(filename) {
	loadMesh(data);
	delete data;
}
Beispiel #29
0
	void loadMeshes()
	{
		loadMesh("./../data/models/plane_z.obj", &meshes.quad, vertexLayout, 0.1f);
	}
Beispiel #30
0
	void loadMeshes()
	{
		loadMesh(getAssetPath() + "models/plane_z.3ds", &meshes.plane, vertexLayout, 0.4f);
		loadMesh(getAssetPath() + "models/teapot.3ds", &meshes.teapot, vertexLayout, 0.3f);
		loadMesh(getAssetPath() + "models/sphere.3ds", &meshes.sphere, vertexLayout, 0.3f);
	}