Пример #1
0
        /// <summary>
        ///     Carga la escena a partir de un objeto TgcSceneData ya parseado
        /// </summary>
        /// <param name="sceneData">Objeto con datos de la escena ya parseados</param>
        /// <param name="mediaPath">Path a partir del cual hay que buscar los recursos de escena (Texturas, LightMaps, etc.)</param>
        /// <returns></returns>
        public TgcScene loadScene(TgcSceneData sceneData, string mediaPath)
        {
            var tgcScene = new TgcScene(sceneData.name, null);

            //Cargar Texturas
            var materialsArray = new TgcSceneLoaderMaterialAux[sceneData.materialsData.Length];

            for (var i = 0; i < sceneData.materialsData.Length; i++)
            {
                var materialData = sceneData.materialsData[i];
                var texturesPath = mediaPath + sceneData.texturesDir + "\\";

                //Crear StandardMaterial
                if (materialData.type.Equals(TgcMaterialData.StandardMaterial))
                {
                    materialsArray[i] = createTextureAndMaterial(materialData, texturesPath);
                }

                //Crear MultiMaterial
                else if (materialData.type.Equals(TgcMaterialData.MultiMaterial))
                {
                    var matAux = new TgcSceneLoaderMaterialAux();
                    materialsArray[i]   = matAux;
                    matAux.subMaterials = new TgcSceneLoaderMaterialAux[materialData.subMaterials.Length];
                    for (var j = 0; j < materialData.subMaterials.Length; j++)
                    {
                        matAux.subMaterials[j] = createTextureAndMaterial(materialData.subMaterials[j], texturesPath);
                    }
                }
            }

            //Cargar Meshes
            for (var i = 0; i < sceneData.meshesData.Length; i++)
            {
                var     meshData = sceneData.meshesData[i];
                TgcMesh tgcMesh  = null;

                //Crear malla original
                if (meshData.instanceType.Equals(TgcMeshData.ORIGINAL))
                {
                    //Crear mesh que no tiene Material, con un color simple
                    if (meshData.materialId == -1)
                    {
                        tgcMesh = crearMeshSoloColor(meshData);
                    }

                    //Para los que si tienen Material
                    else
                    {
                        //Crear MeshFormat que soporte LightMaps
                        if (meshData.lightmapEnabled)
                        {
                            tgcMesh = crearMeshDiffuseMapLightmap(sceneData, mediaPath, materialsArray, meshData);
                        }

                        //Formato de Mesh con Textura pero sin Lightmap
                        else
                        {
                            tgcMesh = crearMeshDiffuseMap(materialsArray, meshData);
                        }
                    }
                }

                //Crear malla instancia
                else if (meshData.instanceType.Equals(TgcMeshData.INSTANCE))
                {
                    tgcMesh = crearMeshInstance(meshData, tgcScene.Meshes);
                }

                //Crear BoundingBox, aprovechar lo que viene del XML o crear uno por nuestra cuenta
                if (meshData.pMin != null && meshData.pMax != null)
                {
                    tgcMesh.BoundingBox = new TgcBoundingBox(
                        TgcParserUtils.float3ArrayToVector3(meshData.pMin),
                        TgcParserUtils.float3ArrayToVector3(meshData.pMax),
                        tgcMesh.Position,
                        tgcMesh.Scale
                        );
                }
                else
                {
                    tgcMesh.createBoundingBox();
                }

                //Cargar layer
                tgcMesh.Layer = meshData.layerName;

                //Cargar AlphaBlending
                tgcMesh.AlphaBlendEnable = meshData.alphaBlending;

                //agregar mesh a escena
                tgcMesh.Enabled = true;
                tgcScene.Meshes.Add(tgcMesh);

                //Cargar userProperties, si hay
                tgcMesh.UserProperties = meshData.userProperties;
            }

            //BoundingBox del escenario, utilizar el que viene del XML o crearlo nosotros
            if (sceneData.pMin != null && sceneData.pMax != null)
            {
                tgcScene.BoundingBox = new TgcBoundingBox(
                    new Vector3(sceneData.pMin[0], sceneData.pMin[1], sceneData.pMin[2]),
                    new Vector3(sceneData.pMax[0], sceneData.pMax[1], sceneData.pMax[2])
                    );
            }
            else
            {
                var boundingBoxes = new List <TgcBoundingBox>();
                foreach (var mesh in tgcScene.Meshes)
                {
                    boundingBoxes.Add(mesh.BoundingBox);
                }
                tgcScene.BoundingBox = TgcBoundingBox.computeFromBoundingBoxes(boundingBoxes);
            }

            //Cargar parte de PortalRendering, solo hay información
            if (sceneData.portalData != null)
            {
                var portalLoader = new TgcPortalRenderingLoader();
                tgcScene.PortalRendering = portalLoader.loadFromData(tgcScene, sceneData.portalData);
            }

            return(tgcScene);
        }
Пример #2
0
        /// <summary>
        ///     Crea un mesh con uno o varios DiffuseMap y un Lightmap
        /// </summary>
        /// <returns></returns>
        private TgcMesh crearMeshDiffuseMapLightmap(TgcSceneData sceneData, string mediaPath,
                                                    TgcSceneLoaderMaterialAux[] materialsArray, TgcMeshData meshData)
        {
            //Crear Mesh
            var mesh = new Mesh(meshData.coordinatesIndices.Length / 3, meshData.coordinatesIndices.Length,
                                MeshFlags.Managed, DiffuseMapAndLightmapVertexElements, D3DDevice.Instance.Device);

            //Cargar vertexBuffer
            using (var vb = mesh.VertexBuffer)
            {
                var data = vb.Lock(0, 0, LockFlags.None);
                for (var j = 0; j < meshData.coordinatesIndices.Length; j++)
                {
                    var v = new DiffuseMapAndLightmapVertex();

                    //vertices
                    var coordIdx = meshData.coordinatesIndices[j] * 3;
                    v.Position = new Vector3(
                        meshData.verticesCoordinates[coordIdx],
                        meshData.verticesCoordinates[coordIdx + 1],
                        meshData.verticesCoordinates[coordIdx + 2]
                        );

                    //normals
                    //puede haber una normal compartida para cada vertice del mesh
                    if (meshData.verticesNormals.Length == meshData.verticesCoordinates.Length)
                    {
                        v.Normal = new Vector3(
                            meshData.verticesNormals[coordIdx],
                            meshData.verticesNormals[coordIdx + 1],
                            meshData.verticesNormals[coordIdx + 2]
                            );
                    }
                    //o una normal propia por cada vertice de cada triangulo (version mejorada del exporter)
                    else
                    {
                        var normalIdx = j * 3;
                        v.Normal = new Vector3(
                            meshData.verticesNormals[normalIdx],
                            meshData.verticesNormals[normalIdx + 1],
                            meshData.verticesNormals[normalIdx + 2]
                            );
                    }

                    //texture coordinates diffuseMap
                    var texCoordIdx = meshData.texCoordinatesIndices[j] * 2;
                    v.Tu0 = meshData.textureCoordinates[texCoordIdx];
                    v.Tv0 = meshData.textureCoordinates[texCoordIdx + 1];

                    //texture coordinates LightMap
                    var texCoordIdxLM = meshData.texCoordinatesIndicesLightMap[j] * 2;
                    v.Tu1 = meshData.textureCoordinatesLightMap[texCoordIdxLM];
                    v.Tv1 = meshData.textureCoordinatesLightMap[texCoordIdxLM + 1];

                    //color
                    var colorIdx = meshData.colorIndices[j];
                    v.Color = meshData.verticesColors[colorIdx];

                    data.Write(v);
                }
                vb.Unlock();
            }

            //Cargar IndexBuffer
            using (var ib = mesh.IndexBuffer)
            {
                var indices = new short[meshData.coordinatesIndices.Length];
                for (var j = 0; j < indices.Length; j++)
                {
                    indices[j] = (short)j;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Configurar Material y Textura para un solo SubSet
            var matAux = materialsArray[meshData.materialId];

            Material[]   meshMaterials;
            TgcTexture[] meshTextures;
            if (matAux.subMaterials == null)
            {
                meshMaterials = new[] { matAux.materialId };
                meshTextures  = new[]
                { TgcTexture.createTexture(D3DDevice.Instance.Device, matAux.textureFileName, matAux.texturePath) };
            }

            //Configurar Material y Textura para varios SubSet
            else
            {
                //Cargar attributeBuffer con los id de las texturas de cada triángulo
                var attributeBuffer = mesh.LockAttributeBufferArray(LockFlags.None);
                Array.Copy(meshData.materialsIds, attributeBuffer, attributeBuffer.Length);
                mesh.UnlockAttributeBuffer(attributeBuffer);

                //Cargar array de Materials y Texturas
                meshMaterials = new Material[matAux.subMaterials.Length];
                meshTextures  = new TgcTexture[matAux.subMaterials.Length];
                for (var m = 0; m < matAux.subMaterials.Length; m++)
                {
                    meshMaterials[m] = matAux.subMaterials[m].materialId;
                    meshTextures[m]  = TgcTexture.createTexture(D3DDevice.Instance.Device,
                                                                matAux.subMaterials[m].textureFileName,
                                                                matAux.subMaterials[m].texturePath);
                }
            }

            //Cargar lightMap
            var lightMap = TgcTexture.createTexture(D3DDevice.Instance.Device, meshData.lightmap,
                                                    mediaPath + sceneData.lightmapsDir + "\\" + meshData.lightmap);

            //Crear mesh de TGC
            var tgcMesh = MeshFactory.createNewMesh(mesh, meshData.name, TgcMesh.MeshRenderType.DIFFUSE_MAP_AND_LIGHTMAP);

            tgcMesh.Materials   = meshMaterials;
            tgcMesh.DiffuseMaps = meshTextures;
            tgcMesh.LightMap    = lightMap;
            return(tgcMesh);
        }
Пример #3
0
        /// <summary>
        ///     Levanta la informacion del XML
        /// </summary>
        /// <param name="xmlString">contenido del XML</param>
        /// <returns></returns>
        public TgcSceneData parseSceneFromString(string xmlString)
        {
            var dom = new XmlDocument();

            dom.LoadXml(xmlString);
            var root = dom.DocumentElement;

            var sceneName    = root.GetElementsByTagName("name")[0].InnerText;
            var tgcSceneData = new TgcSceneData();

            tgcSceneData.name = sceneName;

            //Ver si tiene exportacion de texturas
            var texturesExportNode    = root.GetElementsByTagName("texturesExport")[0];
            var texturesExportEnabled = bool.Parse(texturesExportNode.Attributes["enabled"].InnerText);

            if (texturesExportEnabled)
            {
                tgcSceneData.texturesDir = texturesExportNode.Attributes["dir"].InnerText;
            }

            //Ver si tiene LightMaps
            var lightmapsExportNode = root.GetElementsByTagName("lightmapExport")[0];

            tgcSceneData.lightmapsEnabled = bool.Parse(lightmapsExportNode.Attributes["enabled"].InnerText);
            if (tgcSceneData.lightmapsEnabled)
            {
                tgcSceneData.lightmapsDir = lightmapsExportNode.Attributes["dir"].InnerText;
            }

            //sceneBoundingBox, si está
            var sceneBoundingBoxNodes = root.GetElementsByTagName("sceneBoundingBox");

            if (sceneBoundingBoxNodes != null && sceneBoundingBoxNodes.Count == 1)
            {
                var sceneBoundingBoxNode = sceneBoundingBoxNodes[0];
                tgcSceneData.pMin = TgcParserUtils.parseFloat3Array(sceneBoundingBoxNode.Attributes["min"].InnerText);
                tgcSceneData.pMax = TgcParserUtils.parseFloat3Array(sceneBoundingBoxNode.Attributes["max"].InnerText);
            }

            //Parsear Texturas
            var materialNodes = root.GetElementsByTagName("materials")[0].ChildNodes;

            tgcSceneData.materialsData = new TgcMaterialData[materialNodes.Count];
            var i = 0;

            foreach (XmlElement matNode in materialNodes)
            {
                //determinar tipo de Material
                var material = new TgcMaterialData();
                material.type = matNode.Attributes["type"].InnerText;

                //Standard Material
                if (material.type.Equals(TgcMaterialData.StandardMaterial))
                {
                    parseStandardMaterial(material, matNode);
                }

                //Multi Material
                else if (material.type.Equals(TgcMaterialData.MultiMaterial))
                {
                    material.name = matNode.Attributes["name"].InnerText;
                    var subMaterialsNodes = matNode.GetElementsByTagName("subM");
                    material.subMaterials = new TgcMaterialData[subMaterialsNodes.Count];
                    for (var j = 0; j < subMaterialsNodes.Count; j++)
                    {
                        var subMaterial = new TgcMaterialData();
                        parseStandardMaterial(subMaterial, (XmlElement)subMaterialsNodes[j]);
                        material.subMaterials[j] = subMaterial;
                    }
                }

                tgcSceneData.materialsData[i++] = material;
            }

            //Parsear Meshes
            var meshesNodes = root.GetElementsByTagName("meshes")[0].ChildNodes;

            tgcSceneData.meshesData = new TgcMeshData[meshesNodes.Count];
            i = 0;
            int count;

            foreach (XmlElement meshNode in meshesNodes)
            {
                var meshData = new TgcMeshData();
                tgcSceneData.meshesData[i++] = meshData;

                //parser y convertir valores
                meshData.name       = meshNode.Attributes["name"].InnerText;
                meshData.materialId = int.Parse(meshNode.Attributes["matId"].InnerText);
                meshData.color      = TgcParserUtils.parseFloat3Array(meshNode.Attributes["color"].InnerText);
                meshData.lightmap   = meshNode.Attributes["lightmap"].InnerText;

                //type
                var typeAttr = meshNode.Attributes["type"];
                meshData.instanceType = TgcMeshData.ORIGINAL;
                if (typeAttr != null)
                {
                    meshData.instanceType = typeAttr.InnerText;
                }

                //layer
                var layerAttr = meshNode.Attributes["layer"];
                if (layerAttr != null)
                {
                    meshData.layerName = layerAttr.InnerText;
                }

                //visibility
                var visibility = TgcParserUtils.parseFloat(meshNode.Attributes["visibility"].InnerText);
                meshData.alphaBlending = visibility != 1.0f ? true : false;

                //parsear boundingBox
                var boundingBoxNodes = meshNode.GetElementsByTagName("boundingBox");
                if (boundingBoxNodes != null && boundingBoxNodes.Count == 1)
                {
                    var boundingBoxNode = boundingBoxNodes[0];
                    meshData.pMin = TgcParserUtils.parseFloat3Array(boundingBoxNode.Attributes["min"].InnerText);
                    meshData.pMax = TgcParserUtils.parseFloat3Array(boundingBoxNode.Attributes["max"].InnerText);
                }

                //parsear datos de mesh Original
                if (meshData.instanceType.Equals(TgcMeshData.ORIGINAL))
                {
                    //parsear coordinatesIdx
                    var coordinatesIdxNode = meshNode.GetElementsByTagName("coordinatesIdx")[0];
                    count = int.Parse(coordinatesIdxNode.Attributes["count"].InnerText);
                    meshData.coordinatesIndices = TgcParserUtils.parseIntStream(coordinatesIdxNode.InnerText, count);

                    //parsear textCoordsIdx
                    var textCoordsIdxNode = meshNode.GetElementsByTagName("textCoordsIdx")[0];
                    count = int.Parse(textCoordsIdxNode.Attributes["count"].InnerText);
                    meshData.texCoordinatesIndices = TgcParserUtils.parseIntStream(textCoordsIdxNode.InnerText, count);

                    //parsear colorsIdx
                    var colorsIdxNode = meshNode.GetElementsByTagName("colorsIdx")[0];
                    count = int.Parse(colorsIdxNode.Attributes["count"].InnerText);
                    meshData.colorIndices = TgcParserUtils.parseIntStream(colorsIdxNode.InnerText, count);

                    //parsear matIds
                    //TODO: ver bien como calcula esto el SCRIPT de Exportacion
                    if (meshData.materialId != -1)
                    {
                        var matIdsNode = meshNode.GetElementsByTagName("matIds")[0];
                        count = int.Parse(matIdsNode.Attributes["count"].InnerText);
                        meshData.materialsIds = TgcParserUtils.parseIntStream(matIdsNode.InnerText, count);
                    }

                    //parsear textCoordsLightMapIdx
                    meshData.lightmapEnabled = tgcSceneData.lightmapsEnabled && meshData.lightmap.Trim().Length > 0;
                    if (meshData.lightmapEnabled)
                    {
                        var textCoordsLightMapIdxNode = meshNode.GetElementsByTagName("textCoordsLightMapIdx")[0];
                        count = int.Parse(textCoordsLightMapIdxNode.Attributes["count"].InnerText);
                        meshData.texCoordinatesIndicesLightMap =
                            TgcParserUtils.parseIntStream(textCoordsLightMapIdxNode.InnerText, count);
                    }

                    //parsear vertices
                    var verticesNode = meshNode.GetElementsByTagName("vertices")[0];
                    count = int.Parse(verticesNode.Attributes["count"].InnerText);
                    meshData.verticesCoordinates = TgcParserUtils.parseFloatStream(verticesNode.InnerText, count);

                    //parsear normals
                    var normalsNode = meshNode.GetElementsByTagName("normals")[0];
                    count = int.Parse(normalsNode.Attributes["count"].InnerText);
                    meshData.verticesNormals = TgcParserUtils.parseFloatStream(normalsNode.InnerText, count);

                    //parsear tangents, si hay
                    var tangentsNodes = meshNode.GetElementsByTagName("tangents");
                    if (tangentsNodes != null && tangentsNodes.Count == 1)
                    {
                        var tangentsNode = tangentsNodes[0];
                        count = int.Parse(tangentsNode.Attributes["count"].InnerText);
                        meshData.verticesTangents = TgcParserUtils.parseFloatStream(tangentsNode.InnerText, count);
                    }

                    //parsear binormals, si hay
                    var binormalsNodes = meshNode.GetElementsByTagName("binormals");
                    if (binormalsNodes != null && binormalsNodes.Count == 1)
                    {
                        var binormalsNode = binormalsNodes[0];
                        count = int.Parse(binormalsNode.Attributes["count"].InnerText);
                        meshData.verticesBinormals = TgcParserUtils.parseFloatStream(binormalsNode.InnerText, count);
                    }

                    //parsear texCoords
                    var texCoordsNode = meshNode.GetElementsByTagName("texCoords")[0];
                    count = int.Parse(texCoordsNode.Attributes["count"].InnerText);
                    meshData.textureCoordinates = TgcParserUtils.parseFloatStream(texCoordsNode.InnerText, count);

                    //parsear colors
                    var colorsNode = meshNode.GetElementsByTagName("colors")[0];
                    count = int.Parse(colorsNode.Attributes["count"].InnerText);
                    var colorsArray = TgcParserUtils.parseFloatStream(colorsNode.InnerText, count);
                    //convertir a formato DirectX
                    meshData.verticesColors = new int[count / 3];
                    for (var j = 0; j < meshData.verticesColors.Length; j++)
                    {
                        meshData.verticesColors[j] = Color.FromArgb(
                            (int)colorsArray[j * 3],
                            (int)colorsArray[j * 3 + 1],
                            (int)colorsArray[j * 3 + 2]).ToArgb();
                    }

                    //parsear texCoordsLightMap
                    if (meshData.lightmapEnabled)
                    {
                        var texCoordsLightMapNode = meshNode.GetElementsByTagName("texCoordsLightMap")[0];
                        count = int.Parse(texCoordsLightMapNode.Attributes["count"].InnerText);
                        meshData.textureCoordinatesLightMap =
                            TgcParserUtils.parseFloatStream(texCoordsLightMapNode.InnerText, count);
                    }
                }

                //parsear datos de mesh Instancia
                else if (meshData.instanceType.Equals(TgcMeshData.INSTANCE))
                {
                    //originalMesh
                    var originalMeshNode = meshNode.GetElementsByTagName("originalMesh")[0];
                    meshData.originalMesh = TgcParserUtils.parseInt(originalMeshNode.InnerText);

                    //transform
                    var transformNode = meshNode.GetElementsByTagName("transform")[0];
                    meshData.position = TgcParserUtils.parseFloat3Array(transformNode.Attributes["pos"].InnerText);
                    meshData.rotation = TgcParserUtils.parseFloat4Array(transformNode.Attributes["rotQuat"].InnerText);
                    meshData.scale    = TgcParserUtils.parseFloat3Array(transformNode.Attributes["scale"].InnerText);
                }

                //Parsear userProperties, si hay
                var userPropsNodes = meshNode.GetElementsByTagName("userProps");
                if (userPropsNodes != null && userPropsNodes.Count == 1)
                {
                    meshData.userProperties = new Dictionary <string, string>();
                    var userPropsNode = (XmlElement)userPropsNodes[0];
                    foreach (XmlElement prop in userPropsNode.ChildNodes)
                    {
                        meshData.userProperties.Add(prop.Name, prop.InnerText);
                    }
                }
            }

            //Parsear PortalRendering, si hay información
            var portalRenderingNodes = root.GetElementsByTagName("portalRendering");

            if (portalRenderingNodes != null && portalRenderingNodes.Count == 1)
            {
                var portalRenderingNode = (XmlElement)portalRenderingNodes[0];
                var portalParser        = new TgcPortalRenderingParser();
                tgcSceneData.portalData = portalParser.parseFromXmlNode(portalRenderingNode);
            }

            return(tgcSceneData);
        }