void MainWindow::TriangulateMesh() {
    if (baseMesh == NULL || triangleMesh != NULL) return;

    if (!triangleMesh) {
        try {
            delete triangleMesh;
        } catch(...) {
            QMessageBox::information(this, tr("Error"), "Invalid Pointer for triangleMesh");
        }
        triangleMesh = NULL;
    }

    triangleMesh = CreateTriangleMesh(baseMesh);
    if (triangleMesh == NULL) {
        QMessageBox::information(this, tr("Error"), "Triangulate the base mesh is incompleted!");
        return;
    }
    mainwidget->SetTriangleMesh(triangleMesh);
    mainwidget->updateGL();
    return;
}
Exemple #2
0
std::vector<std::shared_ptr<Shape>> CreateNURBS(const Transform *o2w,
                                                const Transform *w2o,
                                                bool reverseOrientation,
                                                const ParamSet &params) {
    int nu = params.FindOneInt("nu", -1);
    if (nu == -1) {
        Error("Must provide number of control points \"nu\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }

    int uorder = params.FindOneInt("uorder", -1);
    if (uorder == -1) {
        Error("Must provide u order \"uorder\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }
    int nuknots, nvknots;
    const Float *uknots = params.FindFloat("uknots", &nuknots);
    if (uknots == nullptr) {
        Error("Must provide u knot vector \"uknots\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }

    if (nuknots != nu + uorder) {
        Error(
            "Number of knots in u knot vector %d doesn't match sum of "
            "number of u control points %d and u order %d.",
            nuknots, nu, uorder);
        return std::vector<std::shared_ptr<Shape>>();
    }

    Float u0 = params.FindOneFloat("u0", uknots[uorder - 1]);
    Float u1 = params.FindOneFloat("u1", uknots[nu]);

    int nv = params.FindOneInt("nv", -1);
    if (nv == -1) {
        Error("Must provide number of control points \"nv\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }

    int vorder = params.FindOneInt("vorder", -1);
    if (vorder == -1) {
        Error("Must provide v order \"vorder\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }

    const Float *vknots = params.FindFloat("vknots", &nvknots);
    if (vknots == nullptr) {
        Error("Must provide v knot vector \"vknots\" with NURBS shape.");
        return std::vector<std::shared_ptr<Shape>>();
    }

    if (nvknots != nv + vorder) {
        Error(
            "Number of knots in v knot vector %d doesn't match sum of "
            "number of v control points %d and v order %d.",
            nvknots, nv, vorder);
        return std::vector<std::shared_ptr<Shape>>();
    }

    Float v0 = params.FindOneFloat("v0", vknots[vorder - 1]);
    Float v1 = params.FindOneFloat("v1", vknots[nv]);

    bool isHomogeneous = false;
    int npts;
    const Float *P = (const Float *)params.FindPoint3f("P", &npts);
    if (!P) {
        P = params.FindFloat("Pw", &npts);
        if (!P) {
            Error(
                "Must provide control points via \"P\" or \"Pw\" parameter to "
                "NURBS shape.");
            return std::vector<std::shared_ptr<Shape>>();
        }
        if ((npts % 4) != 0) {
            Error(
                "Number of \"Pw\" control points provided to NURBS shape must "
                "be "
                "multiple of four");
            return std::vector<std::shared_ptr<Shape>>();
        }
        npts /= 4;
        isHomogeneous = true;
    }
    if (npts != nu * nv) {
        Error("NURBS shape was expecting %dx%d=%d control points, was given %d",
              nu, nv, nu * nv, npts);
        return std::vector<std::shared_ptr<Shape>>();
    }

    // Compute NURBS dicing rates
    int diceu = 30, dicev = 30;
    std::unique_ptr<Float[]> ueval(new Float[diceu]);
    std::unique_ptr<Float[]> veval(new Float[dicev]);
    std::unique_ptr<Point3f[]> evalPs(new Point3f[diceu * dicev]);
    std::unique_ptr<Normal3f[]> evalNs(new Normal3f[diceu * dicev]);
    int i;
    for (i = 0; i < diceu; ++i)
        ueval[i] = Lerp((float)i / (float)(diceu - 1), u0, u1);
    for (i = 0; i < dicev; ++i)
        veval[i] = Lerp((float)i / (float)(dicev - 1), v0, v1);

    // Evaluate NURBS over grid of points
    memset(evalPs.get(), 0, diceu * dicev * sizeof(Point3f));
    memset(evalNs.get(), 0, diceu * dicev * sizeof(Point3f));
    std::unique_ptr<Point2f[]> uvs(new Point2f[diceu * dicev]);

    // Turn NURBS into triangles
    std::unique_ptr<Homogeneous3[]> Pw(new Homogeneous3[nu * nv]);
    if (isHomogeneous) {
        for (int i = 0; i < nu * nv; ++i) {
            Pw[i].x = P[4 * i];
            Pw[i].y = P[4 * i + 1];
            Pw[i].z = P[4 * i + 2];
            Pw[i].w = P[4 * i + 3];
        }
    } else {
        for (int i = 0; i < nu * nv; ++i) {
            Pw[i].x = P[3 * i];
            Pw[i].y = P[3 * i + 1];
            Pw[i].z = P[3 * i + 2];
            Pw[i].w = 1.;
        }
    }

    for (int v = 0; v < dicev; ++v) {
        for (int u = 0; u < diceu; ++u) {
            uvs[(v * diceu + u)].x = ueval[u];
            uvs[(v * diceu + u)].y = veval[v];

            Vector3f dpdu, dpdv;
            Point3f pt = NURBSEvaluateSurface(uorder, uknots, nu, ueval[u],
                                              vorder, vknots, nv, veval[v],
                                              Pw.get(), &dpdu, &dpdv);
            evalPs[v * diceu + u].x = pt.x;
            evalPs[v * diceu + u].y = pt.y;
            evalPs[v * diceu + u].z = pt.z;
            evalNs[v * diceu + u] = Normal3f(Normalize(Cross(dpdu, dpdv)));
        }
    }

    // Generate points-polygons mesh
    int nTris = 2 * (diceu - 1) * (dicev - 1);
    std::unique_ptr<int[]> vertices(new int[3 * nTris]);
    int *vertp = vertices.get();
    // Compute the vertex offset numbers for the triangles
    for (int v = 0; v < dicev - 1; ++v) {
        for (int u = 0; u < diceu - 1; ++u) {
#define VN(u, v) ((v)*diceu + (u))
            *vertp++ = VN(u, v);
            *vertp++ = VN(u + 1, v);
            *vertp++ = VN(u + 1, v + 1);

            *vertp++ = VN(u, v);
            *vertp++ = VN(u + 1, v + 1);
            *vertp++ = VN(u, v + 1);
#undef VN
        }
    }
    int nVerts = diceu * dicev;

    return CreateTriangleMesh(o2w, w2o, reverseOrientation, nTris,
                              vertices.get(), nVerts, evalPs.get(), nullptr,
                              evalNs.get(), uvs.get(), nullptr);
}
Exemple #3
0
std::vector<std::shared_ptr<Shape>> CreatePLYMesh(
    const Transform *o2w, const Transform *w2o, bool reverseOrientation,
    const ParamSet &params,
    std::map<std::string, std::shared_ptr<Texture<Float>>> *floatTextures) {
    const std::string filename = params.FindOneFilename("filename", "");
    p_ply ply = ply_open(filename.c_str(), rply_message_callback, 0, nullptr);
    if (!ply) {
        Error("Couldn't open PLY file \"%s\"", filename.c_str());
        return std::vector<std::shared_ptr<Shape>>();
    }

    if (!ply_read_header(ply)) {
        Error("Unable to read the header of PLY file \"%s\"", filename.c_str());
        return std::vector<std::shared_ptr<Shape>>();
    }

    p_ply_element element = nullptr;
    long vertexCount = 0, faceCount = 0;

    /* Inspect the structure of the PLY file */
    while ((element = ply_get_next_element(ply, element)) != nullptr) {
        const char *name;
        long nInstances;

        ply_get_element_info(element, &name, &nInstances);
        if (!strcmp(name, "vertex"))
            vertexCount = nInstances;
        else if (!strcmp(name, "face"))
            faceCount = nInstances;
    }

    if (vertexCount == 0 || faceCount == 0) {
        Error("PLY file \"%s\" is invalid! No face/vertex elements found!",
              filename.c_str());
        return std::vector<std::shared_ptr<Shape>>();
    }

    CallbackContext context;

    if (ply_set_read_cb(ply, "vertex", "x", rply_vertex_callback, &context,
                        0x030) &&
        ply_set_read_cb(ply, "vertex", "y", rply_vertex_callback, &context,
                        0x031) &&
        ply_set_read_cb(ply, "vertex", "z", rply_vertex_callback, &context,
                        0x032)) {
        context.p = new Point3f[vertexCount];
    } else {
        Error("PLY file \"%s\": Vertex coordinate property not found!",
              filename.c_str());
        return std::vector<std::shared_ptr<Shape>>();
    }

    if (ply_set_read_cb(ply, "vertex", "nx", rply_vertex_callback, &context,
                        0x130) &&
        ply_set_read_cb(ply, "vertex", "ny", rply_vertex_callback, &context,
                        0x131) &&
        ply_set_read_cb(ply, "vertex", "nz", rply_vertex_callback, &context,
                        0x132))
        context.n = new Normal3f[vertexCount];

    /* There seem to be lots of different conventions regarding UV coordinate
     * names */
    if ((ply_set_read_cb(ply, "vertex", "u", rply_vertex_callback, &context,
                         0x220) &&
         ply_set_read_cb(ply, "vertex", "v", rply_vertex_callback, &context,
                         0x221)) ||
        (ply_set_read_cb(ply, "vertex", "s", rply_vertex_callback, &context,
                         0x220) &&
         ply_set_read_cb(ply, "vertex", "t", rply_vertex_callback, &context,
                         0x221)) ||
        (ply_set_read_cb(ply, "vertex", "texture_u", rply_vertex_callback,
                         &context, 0x220) &&
         ply_set_read_cb(ply, "vertex", "texture_v", rply_vertex_callback,
                         &context, 0x221)) ||
        (ply_set_read_cb(ply, "vertex", "texture_s", rply_vertex_callback,
                         &context, 0x220) &&
         ply_set_read_cb(ply, "vertex", "texture_t", rply_vertex_callback,
                         &context, 0x221)))
        context.uv = new Point2f[vertexCount];

    /* Allocate enough space in case all faces are quads */
    context.indices = new int[faceCount * 6];
    context.vertexCount = vertexCount;

    ply_set_read_cb(ply, "face", "vertex_indices", rply_face_callback, &context,
                    0);

    if (!ply_read(ply)) {
        Error("Unable to read the contents of PLY file \"%s\"",
              filename.c_str());
        ply_close(ply);
        return std::vector<std::shared_ptr<Shape>>();
    }

    ply_close(ply);

    if (context.error) return std::vector<std::shared_ptr<Shape>>();

    // Look up an alpha texture, if applicable
    std::shared_ptr<Texture<Float>> alphaTex;
    std::string alphaTexName = params.FindTexture("alpha");
    if (alphaTexName != "") {
        if (floatTextures->find(alphaTexName) != floatTextures->end())
            alphaTex = (*floatTextures)[alphaTexName];
        else
            Error("Couldn't find float texture \"%s\" for \"alpha\" parameter",
                  alphaTexName.c_str());
    } else if (params.FindOneFloat("alpha", 1.f) == 0.f) {
        alphaTex.reset(new ConstantTexture<Float>(0.f));
    }

    std::shared_ptr<Texture<Float>> shadowAlphaTex;
    std::string shadowAlphaTexName = params.FindTexture("shadowalpha");
    if (shadowAlphaTexName != "") {
        if (floatTextures->find(shadowAlphaTexName) != floatTextures->end())
            shadowAlphaTex = (*floatTextures)[shadowAlphaTexName];
        else
            Error(
                "Couldn't find float texture \"%s\" for \"shadowalpha\" "
                "parameter",
                shadowAlphaTexName.c_str());
    } else if (params.FindOneFloat("shadowalpha", 1.f) == 0.f)
        shadowAlphaTex.reset(new ConstantTexture<Float>(0.f));

    return CreateTriangleMesh(o2w, w2o, reverseOrientation,
                              context.indexCtr / 3, context.indices,
                              vertexCount, context.p, nullptr, context.n,
                              context.uv, alphaTex, shadowAlphaTex);
}
int CBSPMapData_LW::LoadSpecificMapDataFromFile( const char *pFilename )
{
	int i;
	bool bResult = false;
	CLightWaveSceneLoader lightwave_scene;

	// load the LightWave scene file
	lightwave_scene.LoadFromFile( pFilename );

//	MessageBox(NULL, "LW scene file has been loaded", "progress report", MB_OK);


	//First, we have to get the name of the mapfile in this "*.lws" file
	//The name of the mapfile has to be "_MAP_*.lwo" (* is can be an arbitrary string)

	// find the object file that has the filename starting with "_MAP_"
	CLWS_ObjectLayer* pObjectLayer = NULL;
//	char* pLWOFileName;
//	string strBodyFilename;
	char acBodyFilename[512];
	for( i=0; i<lightwave_scene.GetNumObjectLayers(); i++ )
	{
		pObjectLayer = lightwave_scene.GetObjectLayer(i);

		if( !pObjectLayer )
			MessageBox(NULL, "invalid object layer", "error", MB_OK|MB_ICONWARNING);

//		pLWOFileName = pObjectLayer->GetObjectFilename().c_str();
		string& strLWOFilename = pObjectLayer->GetObjectFilename();

		CFileNameOperation::GetBodyFilenameBySlash( acBodyFilename, strLWOFilename.c_str() );

		//find lwo2 file that represents the map object.
		if( strncmp( acBodyFilename, "_MAP_", 5 ) == 0 )
		{
			// load the object
			bResult = m_LWO2Object.LoadLWO2Object(acBodyFilename);
			break;
		}
	}

	// compute normals on each face(polygon) in the LightWave object 
//	m_LWO2Object.ComputeFaceNormals();


	string log_filename = "DebugInfoFile\\lwo2_loaded_data.txt";
	m_LWO2Object.WriteDebug(log_filename.c_str());

	list<LWO2_Layer>::iterator itrLayer;

	this->m_aPlane.reserve(DEFAULT_NUM_PLANES);
	this->m_aMainFace.reserve(DEFAULT_NUM_MAINFACES);
	this->m_aInteriorFace.reserve(DEFAULT_NUM_MAINFACES);

//	itrLayer = m_LWO2Object.m_layer.begin();
	list<LWO2_Layer>& lstLayer = m_LWO2Object.GetLayer();
	itrLayer = lstLayer.begin();
	for(; itrLayer != lstLayer.end() ; itrLayer++)
	{
		if( itrLayer->GetName() == "LYR_Slag" )
			continue;

		if( itrLayer->GetName() == "LYR_Main" )
			SetFace(&m_aMainFace, itrLayer);

		if( itrLayer->GetName() == "LYR_Interior" )
			SetFace(&m_aInteriorFace, itrLayer);

		if( itrLayer->GetName() == "LYR_Skybox" )
			SetFace(&m_aSkyboxFace, itrLayer);

		if( itrLayer->GetName() == "LYR_EnvLight" )
		{
			C3DMeshModelBuilder_LW mesh_builder( &m_LWO2Object );
			mesh_builder.BuildMeshFromLayer( *itrLayer );
			m_EnvLightMesh = mesh_builder.GetArchive();
		}
/*		if( itrLayer->GetName() == "LYR_BoundingVolume" )
			SetFace;
		if( itrLayer->GetName() == "LYR_NoClip" )
			SetFace;*/
	}

	// Sort textures and others
	SetTextureFilename();

	// set texture indices
	SetSurface();

	// create additional filenames to support fake bumpy textures
	SetFakeBumpTextures();

	//convert lightwave fog into generic fog
	CLWS_Fog* pLWSFog = lightwave_scene.GetFog();
	if( pLWSFog )
	{
		m_pFog = new SFog;
		m_pFog->cFogType = (char)pLWSFog->iType;
		m_pFog->fMinDist = pLWSFog->fMinDist;
		m_pFog->fMaxDist = pLWSFog->fMaxDist;
		m_pFog->fMinAmount = pLWSFog->fMinAmount;
		m_pFog->fMaxAmount = pLWSFog->fMaxAmount;
		m_pFog->color.fRed   = pLWSFog->afColor[0];	// red
		m_pFog->color.fGreen = pLWSFog->afColor[1];	// green
		m_pFog->color.fBlue  = pLWSFog->afColor[2];	// blue
	}

	// convert lightwave lights into generic lights
	SetLight( lightwave_scene );

	// for occlusion testing
	CreateTriangleMesh();

//	SetUVsForLightmaps();

	return 1;

}
Exemple #5
0
std::vector<std::shared_ptr<Shape>> CreateTriangleMeshShape(
    const Transform *o2w, const Transform *w2o, bool reverseOrientation,
    const ParamSet &params,
    std::map<std::string, std::shared_ptr<Texture<Float>>> *floatTextures) {
    int nvi, npi, nuvi, nsi, nni;
    const int *vi = params.FindInt("indices", &nvi);
    const Point3f *P = params.FindPoint3f("P", &npi);
    const Point2f *uvs = params.FindPoint2f("uv", &nuvi);
    if (!uvs) uvs = params.FindPoint2f("st", &nuvi);
    std::vector<Point2f> tempUVs;
    if (!uvs) {
        const Float *fuv = params.FindFloat("uv", &nuvi);
        if (!fuv) fuv = params.FindFloat("st", &nuvi);
        if (fuv) {
            nuvi /= 2;
            tempUVs.reserve(nuvi);
            for (int i = 0; i < nuvi; ++i)
                tempUVs.push_back(Point2f(fuv[2 * i], fuv[2 * i + 1]));
            uvs = &tempUVs[0];
        }
    }
    bool discardDegenerateUVs =
        params.FindOneBool("discarddegenerateUVs", false);
    if (uvs) {
        if (nuvi < npi) {
            Error(
                "Not enough of \"uv\"s for triangle mesh.  Expencted %d, "
                "found %d.  Discarding.",
                npi, nuvi);
            uvs = nullptr;
        } else if (nuvi > npi)
            Warning(
                "More \"uv\"s provided than will be used for triangle "
                "mesh.  (%d expcted, %d found)",
                npi, nuvi);
    }
    if (!vi) {
        Error(
            "Vertex indices \"indices\" not provided with triangle mesh shape");
        return std::vector<std::shared_ptr<Shape>>();
    }
    if (!P) {
        Error("Vertex positions \"P\" not provided with triangle mesh shape");
        return std::vector<std::shared_ptr<Shape>>();
    }
    const Vector3f *S = params.FindVector3f("S", &nsi);
    if (S && nsi != npi) {
        Error("Number of \"S\"s for triangle mesh must match \"P\"s");
        S = nullptr;
    }
    const Normal3f *N = params.FindNormal3f("N", &nni);
    if (N && nni != npi) {
        Error("Number of \"N\"s for triangle mesh must match \"P\"s");
        N = nullptr;
    }
    if (discardDegenerateUVs && uvs && N) {
        // if there are normals, check for bad uv's that
        // give degenerate mappings; discard them if so
        const int *vp = vi;
        for (int i = 0; i < nvi; i += 3, vp += 3) {
            Float area =
                .5f * Cross(P[vp[0]] - P[vp[1]], P[vp[2]] - P[vp[1]]).Length();
            if (area < 1e-7) continue;  // ignore degenerate tris.
            if ((uvs[vp[0]].x == uvs[vp[1]].x &&
                 uvs[vp[0]].y == uvs[vp[1]].y) ||
                (uvs[vp[1]].x == uvs[vp[2]].x &&
                 uvs[vp[1]].y == uvs[vp[2]].y) ||
                (uvs[vp[2]].x == uvs[vp[0]].x &&
                 uvs[vp[2]].y == uvs[vp[0]].y)) {
                Warning(
                    "Degenerate uv coordinates in triangle mesh.  Discarding "
                    "all uvs.");
                uvs = nullptr;
                break;
            }
        }
    }
    for (int i = 0; i < nvi; ++i)
        if (vi[i] >= npi) {
            Error(
                "trianglemesh has out of-bounds vertex index %d (%d \"P\" "
                "values were given",
                vi[i], npi);
            return std::vector<std::shared_ptr<Shape>>();
        }

    std::shared_ptr<Texture<Float>> alphaTex;
    std::string alphaTexName = params.FindTexture("alpha");
    if (alphaTexName != "") {
        if (floatTextures->find(alphaTexName) != floatTextures->end())
            alphaTex = (*floatTextures)[alphaTexName];
        else
            Error("Couldn't find float texture \"%s\" for \"alpha\" parameter",
                  alphaTexName.c_str());
    } else if (params.FindOneFloat("alpha", 1.f) == 0.f)
        alphaTex.reset(new ConstantTexture<Float>(0.f));

    std::shared_ptr<Texture<Float>> shadowAlphaTex;
    std::string shadowAlphaTexName = params.FindTexture("shadowalpha");
    if (shadowAlphaTexName != "") {
        if (floatTextures->find(shadowAlphaTexName) != floatTextures->end())
            shadowAlphaTex = (*floatTextures)[shadowAlphaTexName];
        else
            Error(
                "Couldn't find float texture \"%s\" for \"shadowalpha\" "
                "parameter",
                shadowAlphaTexName.c_str());
    } else if (params.FindOneFloat("shadowalpha", 1.f) == 0.f)
        shadowAlphaTex.reset(new ConstantTexture<Float>(0.f));

    return CreateTriangleMesh(o2w, w2o, reverseOrientation, nvi / 3, vi, npi, P,
                              S, N, uvs, alphaTex, shadowAlphaTex);
}