LIB3MFMETHODIMP CCOMModelMeshObject::GetVertex(_In_ DWORD nIndex, _Out_ MODELMESHVERTEX * pVertex)
	{
		UINT j;

		try {
			if (!pVertex)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CMesh * pMesh = getMesh();
			__NMRASSERT(pMesh);

			// retrieve node and return position
			MESHNODE * pNode = pMesh->getNode(nIndex);
			for (j = 0; j < 3; j++)
				pVertex->m_fPosition[j] = pNode->m_position.m_fields[j];

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}
	}
	LIB3MFMETHODIMP CCOMModelMeshObject::GetTriangle(_In_ DWORD nIndex, _Out_ MODELMESHTRIANGLE * pTriangle)
	{
		UINT j;

		try {
			if (!pTriangle)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CMesh * pMesh = getMesh();
			__NMRASSERT(pMesh);

			// retrieve node and return position
			MESHFACE * pFace = pMesh->getFace(nIndex);
			for (j = 0; j < 3; j++)
				pTriangle->m_nIndices[j] = pFace->m_nodeindices[j];

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}
	}
	LIB3MFMETHODIMP CCOMModelMeshObject::AddVertex(_In_ MODELMESHVERTEX * pVertex, _Out_opt_ DWORD * pnIndex)
	{
		UINT j;

		try {
			if (!pVertex)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CMesh * pMesh = getMesh();
			__NMRASSERT(pMesh);

			// Create Position Vector and check input
			NVEC3 vPosition;
			for (j = 0; j < 3; j++) {
				FLOAT fCoord = pVertex->m_fPosition[j];
				if (fabs(fCoord) > NMR_MESH_MAXCOORDINATE)
					throw CNMRException_Windows(NMR_ERROR_INVALIDCOORDINATES, LIB3MF_INVALIDARG);
				vPosition.m_fields[j] = fCoord;
			}

			// Set position to node
			MESHNODE * pNode = pMesh->addNode(vPosition);
			if (pnIndex) {
				*pnIndex = pNode->m_index;
			}

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}
	}
	LIB3MFMETHODIMP CCOMModelMeshObject::SetGeometry(_In_ MODELMESHVERTEX * pVertices, _In_ DWORD nVertexCount, _In_ MODELMESHTRIANGLE * pTriangles, _In_ DWORD nTriangleCount)
	{
		UINT j, nIndex;


		try {
			if ((!pVertices) || (!pTriangles))
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CMesh * pMesh = getMesh();
			__NMRASSERT(pMesh);

			// Clear old mesh
			pMesh->clear();

			// Rebuild Mesh Coordinates
			MODELMESHVERTEX * pVertex = pVertices;
			for (nIndex = 0; nIndex < nVertexCount; nIndex++) {
				NVEC3 vPosition;
				for (j = 0; j < 3; j++) {
					FLOAT fCoord = pVertex->m_fPosition[j];
					if (fabs(fCoord) > NMR_MESH_MAXCOORDINATE)
						throw CNMRException_Windows(NMR_ERROR_INVALIDCOORDINATES, LIB3MF_INVALIDARG);
					vPosition.m_fields[j] = fCoord;
				}
				pMesh->addNode(vPosition);

				pVertex++;
			}

			// Rebuild Mesh Faces
			MODELMESHTRIANGLE * pTriangle = pTriangles;
			for (nIndex = 0; nIndex < nTriangleCount; nIndex++) {
				MESHNODE * pNodes[3];

				for (j = 0; j < 3; j++) {
					if (pTriangle->m_nIndices[j] >= nVertexCount)
						throw CNMRException_Windows(NMR_ERROR_INVALIDINDEX, LIB3MF_INVALIDARG);
					pNodes[j] = pMesh->getNode(pTriangle->m_nIndices[j]);
				}

				if ((pTriangle->m_nIndices[0] == pTriangle->m_nIndices[1]) ||
					(pTriangle->m_nIndices[0] == pTriangle->m_nIndices[2]) ||
					(pTriangle->m_nIndices[1] == pTriangle->m_nIndices[2]))
					throw CNMRException_Windows(NMR_ERROR_INVALIDINDEX, LIB3MF_INVALIDARG);

				pMesh->addFace(pNodes[0], pNodes[1], pNodes[2]);

				pTriangle++;
			}

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}
	}
	LIB3MFMETHODIMP CCOMModelMeshObject::SetTriangle(_In_ DWORD nIndex, _In_ MODELMESHTRIANGLE * pTriangle)
	{
		UINT j;

		try {
			if (!pTriangle)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CMesh * pMesh = getMesh();
			__NMRASSERT(pMesh);

			// Check for input validity
			UINT nNodeCount = pMesh->getNodeCount();
			for (j = 0; j < 3; j++)
				if (pTriangle->m_nIndices[j] >= nNodeCount)
					throw CNMRException_Windows(NMR_ERROR_INVALIDINDEX, LIB3MF_INVALIDARG);
			if ((pTriangle->m_nIndices[0] == pTriangle->m_nIndices[1]) ||
				(pTriangle->m_nIndices[0] == pTriangle->m_nIndices[2]) ||
				(pTriangle->m_nIndices[1] == pTriangle->m_nIndices[2]))
				throw CNMRException_Windows(NMR_ERROR_INVALIDINDEX, LIB3MF_INVALIDARG);

			// retrieve node and return position
			MESHFACE * pFace = pMesh->getFace(nIndex);
			for (j = 0; j < 3; j++)
				pFace->m_nodeindices[j] = pTriangle->m_nIndices[j];

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}
	}
Example #6
0
MeshCoordinates thin_plate_energy_hole_inpainting(CMesh& mesh, const ZGeom::MeshRegion& hole_region, int nIter, double eps)
{
    const vector<int> anchor_verts = ZGeom::vertSurroundingVerts(mesh, hole_region.vert_inside, 2);
    vector<int> submesh_verts;
    int inside_vert_count = (int)hole_region.vert_inside.size();
    int anchor_vert_count = (int)anchor_verts.size();

    vector<int> newVert2oldVert(inside_vert_count);
    for (int i = 0; i < inside_vert_count; ++i) {
        int vi = hole_region.vert_inside[i];
        submesh_verts.push_back(vi);
        newVert2oldVert[i] = vi;
    }
    for (int vi : anchor_verts) submesh_verts.push_back(vi);

    CMesh submesh;
    mesh.getSubMesh(submesh_verts, "hole_mesh", submesh);

    MeshCoordinates faired_sub_coord = thin_plate_energy_fairing(submesh, inside_vert_count);

    MeshCoordinates result(mesh.getVertCoordinates());
    for (int sub_vIdx = 0; sub_vIdx < inside_vert_count; ++sub_vIdx) {
        result.setVertCoord(newVert2oldVert[sub_vIdx], faired_sub_coord[sub_vIdx]);
    }
    return result;
}
Example #7
0
MeshCoordinates l1_ls_inpainting(CMesh& mesh, const std::vector<int>& missing_idx, ParaL1LsInpainting& para)
{
    const int totalVertCount = mesh.vertCount();
    MeshLaplacian graphLaplacian;
    graphLaplacian.constructUmbrella(&mesh);
    int eigenCount = para.eigen_count;    // -1 means full decomposition
    if (eigenCount == -1) eigenCount = totalVertCount - 1;

    ZGeom::EigenSystem es;
    graphLaplacian.meshEigenDecompose(eigenCount, &g_engineWrapper, es);

    ZGeom::Dictionary dictMHB;
    computeDictionary(DT_Fourier, es, dictMHB);

    ZGeom::DenseMatrixd matCoordOld = mesh.getVertCoordinates().toDenseMatrix();
    ZGeom::DenseMatrixd matDict = dictMHB.toDenseMatrix();

    CStopWatch timer;
    timer.startTimer();
    ZGeom::DenseMatrixd matCoordInpainted = matlab_inpaintL1LS(matCoordOld, matDict, missing_idx, para.lambda, para.tol);
    timer.stopTimer("-- L1_Ls inpainting time: ");

    MeshCoordinates coordInpainted;
    coordInpainted.fromDenseMatrix(matCoordInpainted);
    return coordInpainted;
}
Example #8
0
//-----------------------------------------------------------------------------------------
CMesh* CGeometryInstancer::getAnAvailableMesh()
{
    if (!m_MeshList.isEmpty())
    {
        int i = 0;
        while (true)
        {
            CMesh* pMesh = m_MeshList[i];
            if (!pMesh->isLocked())
            {
                QMutexLocker locker(&m_Mutex);
                m_MeshList.removeAt(i);
                return pMesh;
            }
            else
            {
                msleep(s_iWaitTime);
            }

            if (++i == m_MeshList.size()) i = 0;
        }
    }

    return 0;
}
Example #9
0
CPressurePlate::CPressurePlate( XMFLOAT3 _location, bool _used ) : IObject( "PressurePlate" )
{
	AudioSystemWwise::Get()->RegisterEntity( this, "PressurePlate" );
	XMFLOAT3 newLocation = _location;
	newLocation.y = 1;
	SetPosition( newLocation );

	CMesh* vPressureMesh = CAssetManager::GetInstance()->GetPrefabMesh("PressurePlate");

	SetRenderMesh( new CRenderMesh( vPressureMesh, GRAPHICS->GetVertexShader(), GRAPHICS->GetNormalMapPS(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Bricks.dds" ) );
	m_cpRenderMesh->SetNormals(L"../Game/Assets/Art/2D/Normal Maps/Bricks.dds");
	m_cpRenderMesh->GetSpecular() = 1.5f;
	GRAPHICS->AddRenderMesh( m_cpRenderMesh );

	//tempFloor->SetRenderMesh( new CRenderMesh( tempMesh->GetIndices(), tempMesh->GetVertices(), GRAPHICS->GetVertexShader(), GRAPHICS->GetNormalMapPS(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Maze_Ground.dds" ) );
	//tempFloor->GetRenderMesh()->SetNormals( L"../Game/Assets/Art/2D/Normal Maps/Rocky.dds" );
	//tempFloor->GetRenderMesh()->GetSpecular() = 1.5f;

	//if (_used)
	{
		AddCollider( new CCollider( false, Bounds::AABB, vPressureMesh->GetVertices(), _used,false ) );

		for( size_t i = 0; i < m_pvColliders.size(); i++ )
		{
			( (CAABB*)m_pvColliders[i]->GetBounds() )->SetCenter( { m_mWorld._41, m_mWorld._42, m_mWorld._43 } );
		}

	}

	CAddObjectMessage* addObj = new CAddObjectMessage( this, CObjectManager::Static );
	addObj->Send();
}
Example #10
0
NewtonBody* AddSphere(CScene *pScene, NewtonWorld *pWorld, Vector3 pos, float radius, float mass)
{
	static map<float, CGeometry*> geometries;
	static CMaterial *material = NULL;

	if (!material)
	{
		material = new CMaterial();
		material->features = EShaderFeature::LIGHT | EShaderFeature::FOG | EShaderFeature::SHADOW;
	}

	if (geometries.find(radius) == geometries.end())
	{
		CGeometry *g = new CSphereGeometry(radius);
		g->materials.AddToTail(material);
		geometries[radius] = g;
	}

	CMesh *sphere = new CMesh( geometries[radius] );
	sphere->SetPosition(pos);
	NewtonBody *body = CPhysics::CreateSphere(pWorld, sphere, radius, mass);
	pScene->Add(sphere);
	NewtonBodySetForceAndTorqueCallback(body, BoxGravityCallback);
	return body;
}
Example #11
0
void compressMesh(const std::vector<std::string>& mesh_filenames) {
    string mesh_file = mesh_filenames.front();
    CMesh mesh;
    mesh.load(mesh_file);
    string mesh_name = mesh.getMeshName();    
    ofstream ofs(mesh_name + ".compress.log");

    // what to do:
    // 1. partition mesh with each mesh of size 300, 500, 1000, 1500, 2000
    // 2. For each submesh, do eigendecomposition
    // 3. Compute SGW dictionary
    // 4. S-OMP approximation
    // 5. Output total approximation error

    // 
    // what to output:
    // 1. eigendecomposition time
    // 2. S-OMP time
    // 3. Approximation error

    vector<int> max_sizes{ 300, 600, 1000, 1500, 2000 };
    for (int max_size : max_sizes) {
        int nPart = std::round(mesh.vertCount() / max_size);
        vector<int> part_idx = MetisMeshPartition(&mesh, nPart);
        // TODO

    }

}
Example #12
0
void CMainWindow::LoadModel()
{
    std::string modelPath = QFileDialog::getOpenFileName(this,
                                                         "Open Model",
                                                         "",
                                                         g_GetSupported3DFormats()).toStdString();
    if(modelPath.empty())
        return;

    try
    {
        CMesh *newModel = new CMesh();

        newModel->LoadMesh(modelPath);

        AskToSaveChanges();
        m_openedModel = "";
        m_rw2->SetModel(newModel);
        m_rw3->SetModel(newModel);
        if(m_model)
            delete m_model;
        m_model = newModel;
        ClearTextures();

        m_rw2->ZoomFit();
        m_rw3->ZoomFit();
        UpdateView();
    } catch(std::exception& e)
    {
        ClearModel();
        QMessageBox::information(this, "Error", e.what());
    }
}
Example #13
0
void myDisplay() {
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0, 30, 40, 0, 30, 0, 0, 1, 0);

	LightPosition();

	glDisable(GL_LIGHTING);
	glLineWidth(5);
	drawAxes();

	static float angle = 0.0;
	glRotatef(angle, 0, 1, 0);
	angle += 0.5;
	glLineWidth(1);
	myMesh.drawMesh();
	clothMesh.drawMesh();

	glEnable(GL_LIGHTING);


	glutSwapBuffers();
}
Example #14
0
void computeMeshesFeaturePoints(const std::vector<std::string>& mesh_filenames, std::string eigen_path, std::string output_path)
{
    ZGeom::MatlabEngineWrapper eng;
    eng.open();
    auto pwd = initial_path<path>();
    eng.eval("cd " + pwd.string());
    eng.eval("mkdir " + output_path);
    eng.eval("cd " + output_path);
    cout << "# Total meshes: " << mesh_filenames.size() << "\n" << endl;

    CStopWatch timer;
    timer.startTimer();

    int count = 0;
    for (string mesh_file : mesh_filenames)
    {
        count++;
        cout << count << ": " << mesh_file << endl;
        try {
            if (!fileExist(mesh_file)) {
                throw runtime_error("File not exist!");
            }
            CMesh mesh;
            mesh.load(mesh_file);

            string mesh_name = mesh.getMeshName();
            string eigen_file_path = eigen_path + "/" + mesh_name + ".eigen.mat";

            EigenSystem es;
            es.loadFromMat(&eng, eigen_file_path);

            double t_min = 4 * std::log(10.0) / es.getAllEigVals().back(), t_max = 4 * std::log(10.0) / es.getEigVal(1);
            int nScales = 4;
            const double tMultiplier = std::pow(t_max / t_min, 1.0 / double(nScales - 1));
            std::vector<double> hks_scales(nScales);
            for (int s = 0; s < nScales; ++s) {
                hks_scales[s] = t_min * std::pow(tMultiplier, s);
            }

            set<int> all_features;
            for (int s = 0; s < nScales; ++s) {
                vector<double> values = calHeatKernelSignature(es, hks_scales[s]);
                vector<int> features = extractMeshExtrema(mesh, values, 2);
                for (int fi : features) all_features.insert(fi);
            }

            string out_file_path = output_path + "/" + mesh_name + ".feature";
            ofstream ofs(output_path.c_str());

        }
        catch (runtime_error* e){
            cerr << "Fail to process " + mesh_file << ": " << e->what() << endl;
        }
    } 

    cout << "\n";
    timer.stopTimer("Total time: ");
}
Example #15
0
CMesh* CMesh::CreateMesh(
    IMemoryAllocator* pAllocator,
    graph::CGraphicsDevice* pDevice,
    IInputStream* pIn)
{
    S_MSH_HEADER sHeader;
    IZ_INPUT_READ_VRETURN(pIn, &sHeader, 0, sizeof(sHeader));

    IZ_BOOL result = IZ_FALSE;

    // Compute buffer size.
    IZ_UINT nSize = sizeof(CMesh);
    nSize += sizeof(graph::CVertexBuffer*) * sHeader.numVB;
    nSize += sizeof(CMeshGroup*) * sHeader.numMeshGroup;
    nSize += sizeof(CMeshGroup) * sHeader.numMeshGroup;
    nSize += sizeof(CMeshSet*) * sHeader.numMeshSet;
    nSize += sizeof(CMeshSet) * sHeader.numMeshSet;
    nSize += sizeof(CPrimitiveSet*) * sHeader.numMeshSubset;
    nSize += sizeof(CPrimitiveSet) * sHeader.numMeshSubset;
    nSize += sizeof(IZ_UINT16) * sHeader.numAllJointIndices;

    IZ_UINT8* pBuf = reinterpret_cast<IZ_UINT8*>(ALLOC_ZERO(pAllocator, nSize));
    VRETURN_NULL(pBuf != IZ_NULL);

    IZ_UINT8* pTop = pBuf;

    CMesh* pInstance = new(pBuf) CMesh;
    {
        pBuf += sizeof(CMesh);

        pInstance->AddRef();
        pInstance->m_Allocator = pAllocator;

        memcpy(&pInstance->m_Header, &sHeader, sizeof(sHeader));

        pInstance->m_pMeshGroup = reinterpret_cast<CMeshGroup**>(pBuf);
        pBuf += sizeof(CMeshGroup*) * sHeader.numMeshGroup;

        for (IZ_UINT i = 0; i < sHeader.numMeshGroup; ++i) {
            pInstance->m_pMeshGroup[i] = new(pBuf) CMeshGroup;
            pInstance->m_pMeshGroup[i]->AddRef();

            pBuf += sizeof(CMeshGroup);
            
            pBuf = pInstance->m_pMeshGroup[i]->Read(pBuf, pDevice, pIn);
            VGOTO(result = (pBuf != IZ_NULL), __EXIT__);
        }
    }

    IZ_ASSERT(CStdUtil::GetPtrDistance(pBuf, pTop) == nSize);

__EXIT__:
    if (!result) {
        SAFE_RELEASE(pInstance);
    }

    return pInstance;
}
Example #16
0
void CMinotaurSpawn::AddColliders()
{
	for (size_t currMesh = 0; currMesh < meshes.size(); currMesh++)
	{
		CMesh* mesh = meshes[currMesh];
		XMFLOAT3 posOffset = XMFLOAT3(meshLocalMatricies[currMesh]._41, meshLocalMatricies[currMesh]._42, meshLocalMatricies[currMesh]._43);

		int startIndex = 0;
		if (mesh->IsPlane())
		{
			int index = 0;

			for (index = 0; index < (int)mesh->GetAABBs().size(); index++)
			{
				CMesh::TAABB aabb = mesh->GetAABBs()[index];
				aabb.center.x += posOffset.x;
				aabb.center.y += posOffset.y;
				aabb.center.z += posOffset.z;

				AddCollider(new CCollider(false, new CAABB(aabb.center, aabb.extents)));
			}
			index = 0;
			if (m_pvColliders[0]->GetType() == Bounds::Plane)
				index = 1;
			for (index; index < mesh->GetPlanes().size(); index++)
			{
				CMesh::TPlane plane = mesh->GetPlanes()[index];
				plane.center.x += posOffset.x;
				plane.center.y += posOffset.y;
				plane.center.z += posOffset.z;
				AddCollider(new CCollider(false, new CPlane(plane.distance, plane.normal, plane.center, plane.extents)));
			}
		}
		else
		{
			int index = 0;
			if (m_pvColliders[0]->GetType() == Bounds::AABB)
				index = 1;

			for (index; index < mesh->GetAABBs().size(); index++)
			{
				CMesh::TAABB aabb = mesh->GetAABBs()[index];
				aabb.center.x += posOffset.x;
				aabb.center.y += posOffset.y;
				aabb.center.z += posOffset.z;
				AddCollider(new CCollider(false, new CAABB(aabb.center, aabb.extents)));
			}
			for (index = 0; index < mesh->GetPlanes().size(); index++)
			{
				CMesh::TPlane plane = mesh->GetPlanes()[index];
				plane.center.x += posOffset.x;
				plane.center.y += posOffset.y;
				plane.center.z += posOffset.z;
				AddCollider(new CCollider(false, new CPlane(plane.distance, plane.normal, plane.center, plane.extents)));
			}
		}
	}
}
Example #17
0
void GLInit(void) {

	glEnable(GL_DEPTH_TEST);
	glClearColor(1.0, 1.0, 1.0, 1.0);

	LightSet();
	myMesh.loadMesh("female1.sms");
	clothMesh.loadMesh("cloth.txt");
}
Example #18
0
bool CMeshVertex::Stretch(const double *p, const double* shift, void* data) {
    // stretch the vertex at "p" by a vector "shift"
    Point vp(p);

    Point vt = vertex();
    if(vp == vt) {
        Point vshift(shift);
        Point new_vertex = vp + vshift;
        CMesh* mesh = (CMesh*)Owner();
        if(mesh)mesh->ChangeVertex(this, new_vertex);

        // stretch all the edges nearest control points
        {
            std::set<CMeshEdge*>::iterator It;
            for(It = m_edges.begin(); It != m_edges.end(); It++) {
                CMeshEdge* edge = *It;
                CMeshPosition& c = edge->GetControlPointNearVertex(this);
                c.set_vertex(c.vertex() + vshift);
            }
        }

        // stretch the faces centre points
        {
            Point partial_vshift = vshift * 0.5;
            std::set<CMeshFace*>::iterator It;
            for(It = m_faces.begin(); It != m_faces.end(); It++) {
                CMeshFace* face = *It;
                face->m_centre.set_vertex(face->m_centre.vertex() + partial_vshift);
            }
        }

        return false;
    }

    for(std::set<CMeshEdge*>::iterator It = m_edges.begin(); It != m_edges.end(); It++)
    {
        CMeshEdge* edge = *It;
        CMeshPosition& p = edge->GetControlPointNearVertex(this);
        vt = p.vertex();
        if(vp == vt) {
            Point new_vertex = vp + Point(shift);
            p.set_vertex(new_vertex);
            //edge->KillGLLists();
            //edge->InvalidateBothFacesDisplayLists();
            Point dir = new_vertex - vertex();
            Point side_vector = dir ^ m_norm;
            m_norm = (side_vector ^ dir).norm();
            NormalizeAllEdgeDirections();
            return false;
        }
    }

    return false;
}
Example #19
0
MeshCoordinates meshDLRS(CMesh& mesh, double lambda)
{
    int totalVertCount = mesh.vertCount();
    MeshCoordinates coordCurrent = mesh.getVertCoordinates();

    MeshLaplacian graphLaplacian;
    graphLaplacian.constructUmbrella(&mesh);
    vector<VecNd> vDenoisedCoord = DLRS(graphLaplacian.getLS(), lambda, coordCurrent.to3Vec());
    MeshCoordinates coordDenoised(totalVertCount, vDenoisedCoord);

    return coordDenoised;
}
Example #20
0
CRenderResource * ModelSystem::CModelLoader::AllocResource(ResourceDesc * Desc)
{	
	CMesh * Mesh;
	int ID = m_Pool.AllocResource(&Mesh);
	Mesh->m_ResourceID = ID;
	if (Desc)
	{
		Mesh->Bind(Desc->File, Desc->Name, Desc->SubIndex);
		Mesh->m_Desc = *Desc;
	}
	return Mesh;
}
Example #21
0
	void CWeapon::setup() {
		std::string trailName = getOwnerObject()->getID();
		mTrail = new WeaponTrail(trailName);
		//mTrail = NULL;

		CMesh* mesh = static_cast<CMesh*>(getOwnerObject()->getComponent("CMesh"));

		if(mesh) {
			mTrail->setWeaponEntity(mesh->getEntity());
			mTrail->setActive(false);
		}

	}
Example #22
0
void Dlg_EditPrim::ClickedLoadMesh(void)
{
	QString TmpPath = QFileDialog::getOpenFileName(NULL, "Load STL", "", "Stereolithography Files (*.stl)");
	CMesh tmp;
	tmp.LoadSTL(TmpPath.toStdString());
	tmp.CalcFaceNormals();
	tmp.DrawSmooth = false;

	pVXRegion->CreateMeshRegion(&tmp, Vec3D<>(0,0,0), Vec3D<>(1.0, 1.0, 1.0));

	UpdateUI();
	emit RequestUpdateGL();
}
Example #23
0
bool CMeshLoader::loadVertexBufferObjectFromMesh(std::string const & fileName, int & TriangleCount, GLuint & PositionBufferHandle, GLuint & ColorBufferHandle, GLuint & NormalBufferHandle)
{
	CMesh * Mesh = loadASCIIMesh(fileName);
	if (! Mesh)
		return false;
   
	Mesh->resizeMesh(SVector3(1));
	Mesh->centerMeshByExtents(SVector3(0));
   Mesh->computeNormals();
   
	createVertexBufferObject(* Mesh, TriangleCount, PositionBufferHandle, ColorBufferHandle, NormalBufferHandle);
	
	return true;
}
Example #24
0
MeshCoordinates thin_plate_energy_fairing(CMesh& mesh, int free_vert_count)
{
    const int totalVertCount = mesh.vertCount();

    const MeshCoordinates coordOld = mesh.getVertCoordinates();
    vector<VecNd> vOriginalCoords = coordOld.to3Vec();
    MeshLaplacian mesh_laplacian;
    mesh_laplacian.constructCotFormula(&mesh);
    SparseMatrixd matL = mesh_laplacian.getSparseMatrix();
    SparseMatrixd matL2;
    mulMatMat(matL, matL, matL2);

    vector<int> rowIdxL2, colIdxL2;
    vector<double> valsL2;
    matL2.convertToCOO(rowIdxL2, colIdxL2, valsL2, ZGeom::MAT_FULL);

    vector<int> rowIdxA, colIdxA; vector<double> valsA;
    for (int i = 0; i < (int)rowIdxL2.size(); ++i) {
        if (rowIdxL2[i] < free_vert_count && colIdxL2[i] < free_vert_count) {
            rowIdxA.push_back(rowIdxL2[i]);
            colIdxA.push_back(colIdxL2[i]);
            valsA.push_back(valsL2[i]);
        }
    }
    SparseMatrixd matA;
    matA.convertFromCOO(free_vert_count, free_vert_count, rowIdxA, colIdxA, valsA);

    DenseMatrixd matB(free_vert_count, 3);
    for (int m = 0; m < 3; ++m) {
        for (int i = 0; i < free_vert_count; ++i) {
            for (int j = free_vert_count; j < totalVertCount; ++j)
                matB(i, m) -= matL2(i, j) * vOriginalCoords[m][j];
        }
    }

    g_engineWrapper.addSparseMat(matA, "matA");
    g_engineWrapper.addDenseMat(matB, "matB");
    g_engineWrapper.eval("matX=matA\\matB;");
    DenseMatrixd matX = g_engineWrapper.getDenseMat("matX");

    vector<VecNd> vNewCoord = vOriginalCoords;
    for (int m = 0; m < 3; ++m)
        for (int i = 0; i < free_vert_count; ++i)
            vNewCoord[m][i] = matX(i, m);
    
    MeshCoordinates result(totalVertCount, vNewCoord);
    return result;
}
Example #25
0
MeshCoordinates least_square_hole_inpainting(CMesh& mesh, const std::vector<ZGeom::MeshRegion>& hole_regions, int anchor_ring, double anchor_weight)
{
    ZGeom::logic_assert(anchor_weight >= 0, "Illegal parameter!");
    MeshCoordinates result(mesh.getVertCoordinates());

    if (anchor_ring <= 0)
    {
        vector<int> hole_verts = getMeshRegionsInsideVerts(hole_regions);
        set<int> set_hole_verts(hole_verts.begin(), hole_verts.end());
        set<int> anchor_verts;
        for (int vi = 0; vi < (int)mesh.vertCount(); ++vi) {
            if (!setHas(set_hole_verts, vi)) anchor_verts.insert(vi);
        }
        
        MeshCoordinates faired_coord = least_square_inpainting(mesh, vector<int>(anchor_verts.begin(),anchor_verts.end()), anchor_weight);
        for (int vi : hole_verts)
            result.setVertCoord(vi, faired_coord[vi]);
        return result;
    }

    for (const MeshRegion& mr : hole_regions) {
        const vector<int> anchor_verts = ZGeom::vertSurroundingVerts(mesh, mr.vert_inside, anchor_ring);
        vector<int> submesh_verts;
        int inside_vert_count = (int)mr.vert_inside.size();
        int anchor_vert_count = (int)anchor_verts.size();
        vector<int> newVert2oldVert(inside_vert_count);
        int newVertIdx(0);
        for (int vi : mr.vert_inside) {
            submesh_verts.push_back(vi);
            newVert2oldVert[newVertIdx++] = vi;
        }
        for (int vi : anchor_verts) submesh_verts.push_back(vi);

        CMesh submesh;
        mesh.getSubMesh(submesh_verts, "hole_mesh", submesh);
        vector<int> control_verts;
        for (int i = inside_vert_count; i < (int)submesh_verts.size(); ++i)
            control_verts.push_back(i);

        MeshCoordinates faired_sub_coord = least_square_inpainting(submesh, control_verts, anchor_weight);
        for (int sub_vIdx = 0; sub_vIdx < inside_vert_count; ++sub_vIdx) {
            result.setVertCoord(newVert2oldVert[sub_vIdx], faired_sub_coord[sub_vIdx]);
        }
    }

    return result;
}
// convert ascii mesh into binary 
BOOL CSeriousSkaStudioApp::ConvertMesh(CTFileName fnMesh)
{
  CMesh mesh;
  _yy_pMesh = &mesh;
  // parse fnMesh
  if(!StartParser(fnMesh))
  {
    // if failed clear mesh and return
    mesh.Clear();              
    return FALSE;
  }
  // count optimization results
  int ctmlods = mesh.msh_aMeshLODs.Count();
  int imlod=0;
  for(;imlod<ctmlods;imlod++)
  {
    ctMeshVxBeforeOpt += mesh.msh_aMeshLODs[imlod].mlod_aVertices.Count();
  }
  // optimize mesh
  mesh.Optimize();
  mesh.NormalizeWeights();
  // count optimization results
  for(imlod=0;imlod<ctmlods;imlod++)
  {
    ctMeshVxAfterOpt += mesh.msh_aMeshLODs[imlod].mlod_aVertices.Count();
  }
  // save binary mesh
  try
  {
    mesh.Save_t(fnMesh.NoExt() + ".bm");
  }
  catch(char *strErr)
  {
    ErrorMessage(strErr);
  }
  // clear from memory
  mesh.Clear();
  _yy_pMesh = NULL;
  
  // reload mesh in stock
  CMesh *pMesh;
  try
  {
    // load mesh
    pMesh = _pMeshStock->Obtain_t(fnMesh.NoExt() + ".bm");
    // reload it
    pMesh->Reload();
    // release mesh
    _pMeshStock->Release(pMesh);
  }
  catch(char *strError)
  {
    if(strError != NULL) ErrorMessage(strError);
    return FALSE;
  }
  return TRUE;
}
Example #27
0
void CShader_GBuffer::Update()
{
    CMesh* mesh = GetGame()->GetRenderSystem()->GetCurMesh();
    CMaterial mat = mesh->GetMaterial();

    if (GetGame()->GetRenderSystem()->GetCurMaterial() != 0)
        mat = *GetGame()->GetRenderSystem()->GetCurMaterial();

    // Pass material data to shader
    GLuint textureCountID = glGetUniformLocation(GetGame()->GetRenderSystem()->GetCurShader()->GetID(), "matTextureCount");
    if (textureCountID != -1)
        glUniform1f(textureCountID, (float)mat.m_TextureCount);

    GLuint diffuseID = glGetUniformLocation(GetGame()->GetRenderSystem()->GetCurShader()->GetID(), "matDiffuse");
    if (diffuseID != -1)
        glUniform4f(diffuseID, mat.m_Diffuse.r, mat.m_Diffuse.g, mat.m_Diffuse.b, mat.m_Diffuse.a);
}
Example #28
0
void computeMeshesSpectrum(const std::vector<std::string>& mesh_filenames, int eigen_num, std::string output_path)
{
    ZGeom::MatlabEngineWrapper eng;
    eng.open();
    auto pwd = initial_path<path>();
    eng.eval("cd " + pwd.string());
    eng.eval("mkdir " + output_path);
    eng.eval("cd " + output_path);
    cout << "# Total meshes: " << mesh_filenames.size() << "\n" << endl;

    CStopWatch timer;
    timer.startTimer();

    int count = 0;
    for (string mesh_file : mesh_filenames)
    {
        count++;
        cout << count << ": " << mesh_file << endl;
        try {
            if (!fileExist(mesh_file)) {
                throw runtime_error("File not exist!");
            }
            CMesh mesh;
            mesh.load(mesh_file);
            Laplacian cot_form_lap;
            cot_form_lap.constructCotFormula(&mesh);
            EigenSystem es;
            cot_form_lap.decompose(eigen_num, &eng, es, true);

            string mesh_name = mesh.getMeshName();
            string eigen_file_path = mesh_name + ".eigen.mat";            
            es.saveToMat(&eng, eigen_file_path);
            cout << eigen_file_path << " saved!" << endl;
        }
        catch (runtime_error* e){
            cerr << "Fail to process " + mesh_file << ": " << e->what() << endl;
        }
        catch (exception* e) {
            cerr << "Unknown error in processing " + mesh_file << endl;
        }
    }

    cout << "\n";
    timer.stopTimer("Total time: ");
}
Example #29
0
void LinearSolver::mesh_loaded(CMesh& mesh)
{
  CSimpleSolver::mesh_loaded(mesh);
  
  // Set the region of all children to the root region of the mesh
  std::vector<URI> root_regions;
  root_regions.push_back(mesh.topology().uri());
  configure_option_recursively(Solver::Tags::regions(), root_regions);
}
Example #30
0
//////////////////////////////////////////////////////////////////////////
// format: zmesh_operator [mesh_file_name] 
// currently, just output three types of Laplacian operator in .mat Matlab file
int main(int argc, char *argv[])
{
    using namespace std;
    using namespace ZGeom;
    using namespace std::tr2::sys;

    if (argc < 2) {
        std::cerr << "Lack argument!" << std::endl;
        std::exit(-1);
    }

    string meshfile = argv[1];
    if (!fileExist(meshfile)) {
        std::cerr << "Mesh file not existent!" << std::endl;
        std::exit(-1);
    }

    CMesh mesh;    
    mesh.load(meshfile);
    mesh.scaleToUnitBox();
    int N = mesh.vertCount();
    mesh.scaleAndTranslate(-mesh.calMeshCenter(), 1.0);
    Laplacian umbrella, goemUmbrella, cotformula;
    umbrella.constructUmbrella(&mesh);
    cotformula.constructCotFormula(&mesh);

    auto coord = mesh.getVertCoordinates();
    DenseMatrixd matCoord = coord.toDenseMatrix();

    ZGeom::calMeshAttrVertNormals(mesh, ZGeom::VN_AREA_WEIGHT);
    auto normals = ZGeom::getMeshVertNormals(mesh);
    DenseMatrixd matNormal(N, 3);
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < 3; ++j)
            matNormal(i, j) = normals[i][j];
    }

    calMeshAttrMixedVertAreas(mesh);
    ZGeom::computeMeshCurvatures(mesh, true);
    Laplacian anisoLap;
    anisoLap.constructAniso(&mesh);

    MatlabEngineWrapper eng;
    eng.open();
    auto pwd = initial_path<path>();
    eng.eval("cd " + pwd.string()); 

    eng.addDenseMat(matCoord, "mat_coord");
    eng.addDenseMat(matNormal, "mat_normal");
    eng.addSparseMat(umbrella.getLS(), "mat_umbrella");
    eng.addSparseMat(cotformula.getW(), "mat_weight");
    eng.addSparseMat(cotformula.getLS(), "mat_cot");
    eng.addSparseMat(anisoLap.getLS(), "mat_aniso");

    eng.eval("save meshlaplace.mat mat_coord mat_normal mat_umbrella mat_weight mat_cot mat_aniso");
    eng.close();
    cout << "Mesh and Laplace .mat file saved!" << endl;
    exit(0);
}