Example #1
0
    private Vector3 rotateVector(Vector3 vec, TransformNodeChunk transformNodeChunk)
    {
        Vector3 current = new Vector3(vec.x, vec.y, vec.z);

        while (transformNodeChunk != null)
        {
            Vector3[] matrix = getRotationMatrix(transformNodeChunk);

            float x = current.x * matrix[0].x + current.y * matrix[0].y + current.z * matrix[0].z;
            float y = current.x * matrix[1].x + current.y * matrix[1].y + current.z * matrix[1].z;
            float z = current.x * matrix[2].x + current.y * matrix[2].y + current.z * matrix[2].z;

            current = new Vector3(x, y, z);
            if (transformNodeChunk.group != null)
            {
                transformNodeChunk = transformNodeChunk.group.transform;
            }
            else
            {
                transformNodeChunk = null;
            }
        }

        return(current);
    }
Example #2
0
    public override Chunk parse(BinaryReader reader)
    {
        TransformNodeChunk chunk = new TransformNodeChunk();

        chunk.bytesInChunk    = reader.ReadInt32();
        chunk.bytesInChildren = reader.ReadInt32();
        chunk.nodeId          = reader.ReadInt32();
        chunk.attributes      = MagicaDictionary.readDictionary(reader);
        chunk.childNodeId     = reader.ReadInt32();
        chunk.reservedId      = reader.ReadInt32();
        chunk.layerId         = reader.ReadInt32();
        chunk.numberOfFrames  = reader.ReadInt32();

        if (chunk.numberOfFrames == 1)
        {
            chunk.frameAttributes.Add(MagicaDictionary.readDictionary(reader));
        }

        long currentPosition = reader.BaseStream.Position;

        while (reader.BaseStream.Position < currentPosition + chunk.bytesInChildren)
        {
            chunk.children.Add(Chunk.createChunk(reader));
        }

        return(chunk);
    }
Example #3
0
        private TransformNodeChunk ReadTransformNodeChunk(BinaryReader chunkReader)
        {
            var transformNodeChunk = new TransformNodeChunk()
            {
                id              = chunkReader.ReadInt32(),
                attributes      = ReadDICT(chunkReader),
                childId         = chunkReader.ReadInt32(),
                reservedId      = chunkReader.ReadInt32(),
                layerId         = chunkReader.ReadInt32(),
                frameAttributes = ReadArray(chunkReader, r => new DICT(ReadDICT(r)))
            };

            return(transformNodeChunk);
        }
Example #4
0
        /// <summary>
        /// Write nTRN chunk
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="index"></param>
        private int WriteTransformChunk(BinaryWriter writer, TransformNodeChunk transformNode, int id, int childId)
        {
            int byteWritten = 0;

            writer.Write(Encoding.UTF8.GetBytes(nTRN));
            byteWritten += Encoding.UTF8.GetByteCount(nTRN);

            Vector3 worldPosition = transformNode.TranslationAt();
            string  pos           = worldPosition.X + " " + worldPosition.Y + " " + worldPosition.Z;

            writer.Write(48 + Encoding.UTF8.GetByteCount(pos)
                         + Encoding.UTF8.GetByteCount(Convert.ToString((byte)transformNode.RotationAt()))); //nTRN chunk size
            writer.Write(0);                                                                                //nTRN child chunk size
            writer.Write(id);                                                                               //ID
            writer.Write(0);                                                                                //ReadDICT size for attributes (none)
            writer.Write(childId);                                                                          //Child ID
            writer.Write(-1);                                                                               //Reserved ID
            writer.Write(transformNode.layerId);                                                            //Layer ID
            writer.Write(1);                                                                                //Read Array Size
            writer.Write(2);                                                                                //Read DICT Size (previously 1)

            writer.Write(2);                                                                                //Read STRING size
            byteWritten += 40;

            writer.Write(Encoding.UTF8.GetBytes("_r"));
            writer.Write(Encoding.UTF8.GetByteCount(Convert.ToString((byte)transformNode.RotationAt())));
            writer.Write(Encoding.UTF8.GetBytes(Convert.ToString((byte)transformNode.RotationAt())));

            byteWritten += Encoding.UTF8.GetByteCount("_r");
            byteWritten += 4;
            byteWritten += Encoding.UTF8.GetByteCount(Convert.ToString((byte)transformNode.RotationAt()));


            writer.Write(2); //Read STRING Size
            writer.Write(Encoding.UTF8.GetBytes("_t"));
            writer.Write(Encoding.UTF8.GetByteCount(pos));
            writer.Write(Encoding.UTF8.GetBytes(pos));

            byteWritten += 4 + Encoding.UTF8.GetByteCount("_t") + 4 + Encoding.UTF8.GetByteCount(pos);
            return(byteWritten);
        }
Example #5
0
    public string[] GetObjectNames(string path)
    {
        Chunk mainChunk = MagicaVoxelReader.ReadMagicaChunks(path);

        HashSet <string> names = new HashSet <string>();

        for (int i = 0; i < mainChunk.children.Count; i++)
        {
            Chunk chunk = mainChunk.children[i];
            if (chunk is TransformNodeChunk)
            {
                TransformNodeChunk transformNodeChunk = (TransformNodeChunk)chunk;
                if (transformNodeChunk.attributes.Keys.Contains("_name"))
                {
                    names.Add(transformNodeChunk.attributes["_name"]);
                }
            }
        }

        return(names.ToArray <string>());
    }
Example #6
0
        ///<summary>
        ///Initializes all the chunk classes and adds them to a hashtable
        ///for lookup and retrieval based on their chunk ID;
        ///</summary>
        private void initializeChunks()
        {
            Chunk meshChunk                     = new MeshChunk();
            Chunk hierarchyChunk                = new HierarchyChunk();
            Chunk hierarchyHeaderChunk          = new HierarchyHeaderChunk();
            Chunk pivotsChunk                   = new PivotsChunk();
            Chunk pivotFixupsChunk              = new PivotFixupsChunk();
            Chunk hlodChunk                     = new HlodChunk();
            Chunk hlodHeaderChunk               = new HlodHeaderChunk();
            Chunk hlodLodArrayChunk             = new HlodLodArrayChunk();
            Chunk hlodSubObjectArrayHeaderChunk = new HlodSubObjectArrayHeaderChunk();
            Chunk hlodSubObjectChunk            = new HlodSubObjectChunk();
            Chunk hlodProxyArrayChunk           = new HLodProxyArrayChunk();
            Chunk meshHeader3Chunk              = new MeshHeader3Chunk();
            Chunk verticesChunk                 = new VerticesChunk();
            Chunk vertexNormalsChunk            = new VertexNormalsChunk();
            Chunk trianglesChunk                = new TrianglesChunk();
            Chunk vertexShadeIndicesChunk       = new VertexShadeIndicesChunk();
            Chunk materialInfoChunk             = new MaterialInfoChunk();
            Chunk vertexMaterialsChunk          = new VertexMaterialsChunk();
            Chunk vertexMaterialChunk           = new VertexMaterialChunk();
            Chunk vertexMaterialNameChunk       = new VertexMaterialNameChunk();
            Chunk vertexMaterialInfoChunk       = new VertexMaterialInfoChunk();
            Chunk shadersChunk                  = new ShadersChunk();
            Chunk texturesChunk                 = new TexturesChunk();
            Chunk textureChunk                  = new TextureChunk();
            Chunk textureNameChunk              = new TextureNameChunk();
            Chunk textureInfoChunk              = new TextureInfoChunk();
            Chunk materialPassChunk             = new MaterialPassChunk();
            Chunk vertexMaterialIdsChunk        = new VertexMaterialIdsChunk();
            Chunk shaderIdsChunk                = new ShaderIdsChunk();
            Chunk textureStageChunk             = new TextureStageChunk();
            Chunk textureIdsChunk               = new TextureIdsChunk();
            Chunk stageTexCoordsChunk           = new StageTexCoordsChunk();
            Chunk aabTreeChunk                  = new AabTreeChunk();
            Chunk aabTreeHeaderChunk            = new AabTreeHeaderChunk();
            Chunk aabTreePolyIndicesChunk       = new AabTreePolyIndicesChunk();
            Chunk aabTreeNodesChunk             = new AabTreeNodesChunk();
            Chunk aggregateChunk                = new AggregateChunk();
            Chunk aggregateHeaderChunk          = new AggregateHeaderChunk();
            Chunk aggregateInfoChunk            = new AggregateInfoChunk();
            Chunk aggregateClassInfoChunk       = new AggregateClassInfoChunk();
            Chunk textureReplacerChunk          = new TextureReplacerChunk();
            Chunk vertexMapperArgs0Chunk        = new VertexMapperArgs0Chunk();
            Chunk vertexMapperArgs1Chunk        = new VertexMapperArgs1Chunk();
            Chunk animationChunk                = new AnimationChunk();
            Chunk animationHeaderChunk          = new AnimationHeaderChunk();
            Chunk animationChannelChunk         = new AnimationChannelChunk();
            Chunk bitChannelChunk               = new BitChannelChunk();
            Chunk emitterChunk                  = new EmitterChunk();
            Chunk emitterHeaderChunk            = new EmitterHeaderChunk();
            Chunk emitterUserDataChunk          = new EmitterUserDataChunk();
            Chunk emitterInfoChunk              = new EmitterInfoChunk();
            Chunk emitterInfo2Chunk             = new EmitterInfo2Chunk();
            Chunk emitterPropsChunk             = new EmitterPropsChunk();
            Chunk emitterRotationKeyframesChunk = new EmitterRotationKeyFramesChunk();
            Chunk emitterFrameKeyFramesChunk    = new EmitterFrameKeyFramesChunk();
            Chunk emitterBlurTimeKeyFramesChunk = new EmitterBlurTimeKeyFramesChunk();
            Chunk emitterLinePropertiesChunk    = new EmitterLinePropertiesChunk();
            Chunk vertexInfluencesChunk         = new VertexInfluencesChunk();
            Chunk dcgChunk                        = new DcgChunk();
            Chunk hModelChunk                     = new HModelChunk();
            Chunk hModelHeaderChunk               = new HModelHeaderChunk();
            Chunk hModelAuxDataChunk              = new HModelAuxDataChunk();
            Chunk nodeChunk                       = new NodeChunk();
            Chunk compressedAnimationChunk        = new CompressedAnimationChunk();
            Chunk compressedAnimationHeaderChunk  = new CompressedAnimationHeaderChunk();
            Chunk compressedAnimationChannelChunk = new CompressedAnimationChannelChunk();
            Chunk compressedBitChannelChunk       = new CompressedBitChannelChunk();
            Chunk hLodAggregateArrayChunk         = new HLodAggregateArrayChunk();
            Chunk prelitUnlitChunk                = new PrelitUnlitChunk();
            Chunk prelitVertexChunk               = new PrelitVertexChunk();
            Chunk prelitLightMultiPassChunk       = new PrelitLightMultiPassChunk();
            Chunk prelitLightMultiTextureChunk    = new PrelitLightMultiTextureChunk();
            Chunk meshUserTextChunk               = new MeshUserTextChunk();
            Chunk collectionChunk                 = new CollectionChunk();
            Chunk collectionHeaderChunk           = new CollectionHeaderChunk();
            Chunk collectionObjectNameChunk       = new CollectionObjectNameChunk();
            Chunk placeholderChunk                = new PlaceholderChunk();
            Chunk transformNodeChunk              = new TransformNodeChunk();
            Chunk dazzleChunk                     = new DazzleChunk();
            Chunk dazzleNameChunk                 = new DazzleNameChunk();
            Chunk dazzleTypeNameChunk             = new DazzleTypeNameChunk();
            Chunk boxChunk                        = new BoxChunk();
            Chunk deformChunk                     = new DeformChunk();
            Chunk deformSetChunk                  = new DeformSetChunk();
            Chunk deformKeyframeChunk             = new DeformKeyframeChunk();
            Chunk deformDataChunk                 = new DeformDataChunk();

            //Animation
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_ANIMATION, animationChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_ANIMATION_HEADER, animationHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_ANIMATION_CHANNEL, animationChannelChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_BIT_CHANNEL, bitChannelChunk);

            // Aggregate
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AGGREGATE, aggregateChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AGGREGATE_HEADER, aggregateHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AGGREGATE_INFO, aggregateInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AGGREGATE_CLASS_INFO, aggregateClassInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE_REPLACER_INFO, textureReplacerChunk);

            //Collection
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COLLECTION, collectionChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COLLECTION_HEADER, collectionHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COLLECTION_OBJ_NAME, collectionObjectNameChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PLACEHOLDER, placeholderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TRANSFORM_NODE, transformNodeChunk);

            //Compressed Animation
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COMPRESSED_ANIMATION, compressedAnimationChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COMPRESSED_ANIMATION_HEADER, compressedAnimationHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COMPRESSED_ANIMATION_CHANNEL, compressedAnimationChannelChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_COMPRESSED_BIT_CHANNEL, compressedBitChannelChunk);

            //Dazzle
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DAZZLE, dazzleChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DAZZLE_NAME, dazzleNameChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DAZZLE_TYPENAME, dazzleTypeNameChunk);

            //Deform
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DEFORM, deformChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DEFORM_SET, deformSetChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DEFORM_KEYFRAME, deformKeyframeChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DEFORM_DATA, deformDataChunk);

            //Emitter
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER, emitterChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_HEADER, emitterHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_USER_DATA, emitterUserDataChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_INFO, emitterInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_INFOV2, emitterInfo2Chunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_PROPS, emitterPropsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_LINE_PROPERTIES, emitterLinePropertiesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_ROTATION_KEYFRAMES, emitterRotationKeyframesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_FRAME_KEYFRAMES, emitterFrameKeyFramesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_EMITTER_BLUR_TIME_KEYFRAMES, emitterBlurTimeKeyFramesChunk);

            // Mesh
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_MESH, meshChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_MESH_HEADER3, meshHeader3Chunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTICES, verticesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_NORMALS, vertexNormalsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TRIANGLES, trianglesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_SHADE_INDICES, vertexShadeIndicesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_MATERIAL_INFO, materialInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_MESH_USER_TEXT, meshUserTextChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MATERIALS, vertexMaterialsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MATERIAL, vertexMaterialChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MATERIAL_NAME, vertexMaterialNameChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MATERIAL_INFO, vertexMaterialInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_SHADERS, shadersChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURES, texturesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE, textureChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE_NAME, textureNameChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE_INFO, textureInfoChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_MATERIAL_PASS, materialPassChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE_STAGE, textureStageChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_TEXTURE_IDS, textureIdsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_STAGE_TEXCOORDS, stageTexCoordsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MATERIAL_IDS, vertexMaterialIdsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MAPPER_ARGS0, vertexMapperArgs0Chunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_MAPPER_ARGS1, vertexMapperArgs1Chunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_SHADER_IDS, shaderIdsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_VERTEX_INFLUENCES, vertexInfluencesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AABTREE, aabTreeChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AABTREE_HEADER, aabTreeHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AABTREE_POLYINDICES, aabTreePolyIndicesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_AABTREE_NODES, aabTreeNodesChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_DCG, dcgChunk);

            //Primitives
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_BOX, boxChunk);

            //Hierarchy
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HIERARCHY, hierarchyChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HIERARCHY_HEADER, hierarchyHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PIVOTS, pivotsChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PIVOT_FIXUPS, pivotFixupsChunk);

            //HLod
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD, hlodChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_HEADER, hlodHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_LOD_ARRAY, hlodLodArrayChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_SUB_OBJECT_ARRAY_HEADER, hlodSubObjectArrayHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_SUB_OBJECT, hlodSubObjectChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_AGGREGATE_ARRAY, hLodAggregateArrayChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HLOD_PROXY_ARRAY, hlodProxyArrayChunk);

            //HModel
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HMODEL, hModelChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HMODEL_HEADER, hModelHeaderChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_HMODEL_AUX_DATA, hModelAuxDataChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_NODE, nodeChunk);

            //Optional
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PRELIT_UNLIT, prelitUnlitChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PRELIT_VERTEX, prelitVertexChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PRELIT_LIGHTMAP_MULTI_PASS, prelitLightMultiPassChunk);
            chunkMap.Add((int)ChunkHeader.W3D_CHUNK_PRELIT_LIGHTMAP_MULTI_TEXTURE, prelitLightMultiTextureChunk);
        }
Example #7
0
    public GameObject ImportMagicaVoxelFileAssets(string path)
    {
        GameObject levelGo = new GameObject(Path.GetFileName(path));

        string fileName = Path.GetFileName(path);

        List <GameObject> gameObjects = new List <GameObject>();
        Dictionary <string, GameObject> namedGameObjects = new Dictionary <string, GameObject>();

        Chunk           mainChunk      = MagicaVoxelReader.ReadMagicaChunks(path);
        List <Material> colorMaterials = ImportColors(mainChunk);
        List <string>   names          = new List <string>();
        List <string>   doubleNames    = new List <string>();

        string localPath      = AssetDatabase.GenerateUniqueAssetPath(Path.Combine("Assets", "ImportedPrefabs", fileName));
        string materialFolder = Path.Combine("Assets", "ImportedPrefabs", fileName, "Materials");
        string meshFolder     = Path.Combine("Assets", "ImportedPrefabs", fileName, "Meshes");

        if (!AssetDatabase.IsValidFolder(localPath))
        {
            AssetDatabase.CreateFolder(Path.Combine("Assets", "ImportedPrefabs"), fileName);
        }
        if (!AssetDatabase.IsValidFolder(materialFolder))
        {
            AssetDatabase.CreateFolder(localPath, "Materials");
        }
        if (!AssetDatabase.IsValidFolder(meshFolder))
        {
            AssetDatabase.CreateFolder(localPath, "Meshes");
        }

        for (int m = 0; m < colorMaterials.Count; m++)
        {
            AssetDatabase.CreateAsset(colorMaterials[m], Path.Combine(materialFolder, "Color_" + m + ".mat"));
        }

        for (int i = 0; i < mainChunk.children.Count; i++)
        {
            Chunk chunk = mainChunk.children[i];
            if (chunk is VoxelModelChunk)
            {
                VoxelModelChunk voxelChunk = (VoxelModelChunk)chunk;

                foreach (ShapeNodeChunk shape in voxelChunk.shapes)
                {
                    TransformNodeChunk transformNodeChunk = shape.transform;

                    bool isPotentialAsset = false;
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            isPotentialAsset = true;
                            break;
                        }
                    }
                    if (!isPotentialAsset)
                    {
                        continue;
                    }

                    MeshAndColors   meshAndColors = createMesh(voxelChunk, shape);
                    List <Material> materials     = new List <Material>();
                    foreach (int color in meshAndColors.colors)
                    {
                        materials.Add(colorMaterials[color - 1]);
                    }

                    GameObject go = new GameObject();
                    gameObjects.Add(go);
                    ObjectAttributes script = go.AddComponent <ObjectAttributes>();

                    MeshRenderer renderer = go.AddComponent <MeshRenderer>();
                    renderer.materials = materials.ToArray();
                    MeshFilter filter = go.AddComponent <MeshFilter>();
                    filter.mesh = meshAndColors.mesh;

                    Vector3 shift = Vector3.zero; //new Vector3(script.singleCenter.x, 0, script.singleCenter.y);
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            string name = transformNodeChunk.attributes["_name"];
                            script.names.Add(name);

                            if (names.Contains(name))
                            {
                                if (!doubleNames.Contains(name))
                                {
                                    doubleNames.Add(name);
                                }
                            }
                            else
                            {
                                names.Add(name);
                                namedGameObjects.Add(name, go);
                            }
                        }

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_r"))
                        {
                            script.rotations.Add(transformNodeChunk.frameAttributes[0]["_r"]);
                        }

                        Vector3[] rotationMatrix = getRotationMatrix(transformNodeChunk);
                        script.rotationMatrices.Add(rotationMatrix);

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_t"))
                        {
                            string[] coords       = transformNodeChunk.frameAttributes[0]["_t"].Split(' ');
                            Vector3  currentShift = new Vector3(float.Parse(coords[0]) / 10f, float.Parse(coords[2]) / 10f, float.Parse(coords[1]) / 10f);;
                            script.magicaTransitions.Add(currentShift);
                            shift += currentShift;
                        }
                        if (transformNodeChunk.group != null && transformNodeChunk.group.transform != null)
                        {
                            transformNodeChunk = transformNodeChunk.group.transform;
                        }
                        else
                        {
                            transformNodeChunk = null;
                        }
                    }

                    Vector3 ve = rotateVector(new Vector3(voxelChunk.sizeChunk.sizeX, voxelChunk.sizeChunk.sizeY, voxelChunk.sizeChunk.sizeZ), shape.transform);

                    script.magicaTotalSize = new Vector3(Math.Abs(ve.x), Math.Abs(ve.z), Math.Abs(ve.y));

                    script.bottomCenterOfVoxelMass = shape.singleCenter / 10f;

                    script.centerOfMagicaMass = new Vector3((float)Math.Floor((double)(Math.Abs(ve.x) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.z) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.y) / 2f)) / 10f);
                    script.parentVoxFile      = Path.GetFileName(path);
                    //shift -= script.trans;
                    shift += new Vector3(script.bottomCenterOfVoxelMass.x - script.centerOfMagicaMass.x, script.bottomCenterOfVoxelMass.y - script.centerOfMagicaMass.y, script.bottomCenterOfVoxelMass.z - script.centerOfMagicaMass.z);
                    //shift += (script.bottomCenterOfVoxelMass - script.centerOfMagicaMass);

                    go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                    go.transform.position   = shift;
                    go.name             = script.names[0];
                    go.transform.parent = levelGo.transform;
                }
            }
        }

        // remove double named objects since we cannot insert them properly
        foreach (string name in doubleNames)
        {
            namedGameObjects.Remove(name);
        }

        foreach (GameObject g in namedGameObjects.Values)
        {
            TeardownProperties teardownProperties = g.AddComponent <TeardownProperties>();

            // Create the new Prefab.
            AssetDatabase.CreateAsset(g.GetComponent <MeshFilter>().sharedMesh, Path.Combine(meshFolder, g.name.Replace(" ", "_") + ".mesh"));
            AssetDatabase.SaveAssets();
            PrefabUtility.SaveAsPrefabAssetAndConnect(g, Path.Combine("Assets", "ImportedPrefabs", fileName, g.name.Replace(" ", "_") + ".prefab"), InteractionMode.UserAction);
        }

        PrefabUtility.SaveAsPrefabAssetAndConnect(levelGo, Path.Combine("Assets", "ImportedPrefabs", fileName, fileName + ".prefab"), InteractionMode.UserAction);

        return(levelGo);
    }
Example #8
0
    public GameObject ImportMagicaVoxelFile(string path)
    {
        Material vertexMaterial = Resources.Load("VertexShading", typeof(Material)) as Material;

        GameObject levelGo = new GameObject(Path.GetFileName(path));

        levelGo.AddComponent <TeardownProperties>();
        MagicaImportedFile magicaImportedFile = levelGo.AddComponent <MagicaImportedFile>();

        magicaImportedFile.voxFile = Path.GetFileName(path);

        List <GameObject> gameObjects = new List <GameObject>();
        Dictionary <string, GameObject> namedGameObjects = new Dictionary <string, GameObject>();

        Chunk           mainChunk      = MagicaVoxelReader.ReadMagicaChunks(path);
        List <Material> colorMaterials = ImportColors(mainChunk);
        List <string>   names          = new List <string>();
        List <string>   doubleNames    = new List <string>();

        for (int i = 0; i < mainChunk.children.Count; i++)
        {
            Chunk chunk = mainChunk.children[i];
            if (chunk is VoxelModelChunk)
            {
                VoxelModelChunk voxelChunk = (VoxelModelChunk)chunk;

                foreach (ShapeNodeChunk shape in voxelChunk.shapes)
                {
                    MeshAndColors meshAndColors = createMesh(voxelChunk, shape);
                    Color[]       colors        = new Color[meshAndColors.colors.Count];
                    for (int c = 0; c < meshAndColors.colors.Count; c++)
                    {
                        colors[c] = colorMaterials[meshAndColors.colors[c] - 1].color;
                    }
                    meshAndColors.mesh.colors = colors;

                    TransformNodeChunk transformNodeChunk = shape.transform;
                    GameObject         go = new GameObject();
                    gameObjects.Add(go);
                    ObjectAttributes script   = go.AddComponent <ObjectAttributes>();
                    MeshRenderer     renderer = go.AddComponent <MeshRenderer>();
                    renderer.material = vertexMaterial;
                    MeshFilter filter = go.AddComponent <MeshFilter>();
                    filter.mesh = meshAndColors.mesh;

                    Vector3 shift = Vector3.zero; //new Vector3(script.singleCenter.x, 0, script.singleCenter.y);
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            string name = transformNodeChunk.attributes["_name"];
                            script.names.Add(name);

                            if (names.Contains(name))
                            {
                                if (!doubleNames.Contains(name))
                                {
                                    doubleNames.Add(name);
                                }
                            }
                            else
                            {
                                names.Add(name);
                                namedGameObjects.Add(name, go);
                            }
                        }

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_r"))
                        {
                            script.rotations.Add(transformNodeChunk.frameAttributes[0]["_r"]);
                        }

                        Vector3[] rotationMatrix = getRotationMatrix(transformNodeChunk);
                        script.rotationMatrices.Add(rotationMatrix);

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_t"))
                        {
                            string[] coords       = transformNodeChunk.frameAttributes[0]["_t"].Split(' ');
                            Vector3  currentShift = new Vector3(float.Parse(coords[0]) / 10f, float.Parse(coords[2]) / 10f, float.Parse(coords[1]) / 10f);;
                            script.magicaTransitions.Add(currentShift);
                            shift += currentShift;
                        }
                        if (transformNodeChunk.group != null && transformNodeChunk.group.transform != null)
                        {
                            transformNodeChunk = transformNodeChunk.group.transform;
                        }
                        else
                        {
                            transformNodeChunk = null;
                        }
                    }

                    Vector3 ve = rotateVector(new Vector3(voxelChunk.sizeChunk.sizeX, voxelChunk.sizeChunk.sizeY, voxelChunk.sizeChunk.sizeZ), shape.transform);

                    script.magicaTotalSize = new Vector3(Math.Abs(ve.x), Math.Abs(ve.z), Math.Abs(ve.y));

                    script.bottomCenterOfVoxelMass = shape.singleCenter / 10f;

                    script.centerOfMagicaMass = new Vector3((float)Math.Floor((double)(Math.Abs(ve.x) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.z) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.y) / 2f)) / 10f);
                    script.parentVoxFile      = Path.GetFileName(path);
                    //shift -= script.trans;
                    shift += new Vector3(script.bottomCenterOfVoxelMass.x - script.centerOfMagicaMass.x, script.bottomCenterOfVoxelMass.y - script.centerOfMagicaMass.y, script.bottomCenterOfVoxelMass.z - script.centerOfMagicaMass.z);
                    //shift += (script.bottomCenterOfVoxelMass - script.centerOfMagicaMass);

                    go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                    go.transform.position   = shift;

                    go.transform.parent = levelGo.transform;

                    if (script.names.Count > 0)
                    {
                        go.name = script.names[0];
                    }
                }
            }
        }

        // remove double named objects since we cannot insert them properly
        foreach (string name in doubleNames)
        {
            namedGameObjects.Remove(name);
        }

        foreach (GameObject g in gameObjects)
        {
            if (namedGameObjects.Values.Contains(g))
            {
                TeardownProperties teardownProperties = g.AddComponent <TeardownProperties>();
            }
        }

        return(levelGo);
    }
Example #9
0
    public static Vector3[] getRotationMatrix(TransformNodeChunk transformNodeChunk)
    {
        Vector3[] matrix   = new Vector3[3];
        int       rotation = 0;

        if (transformNodeChunk.frameAttributes.Count > 0 && transformNodeChunk.frameAttributes[0].ContainsKey("_r"))
        {
            rotation = int.Parse(transformNodeChunk.frameAttributes[0]["_r"]);
        }
        else
        {
            matrix[0] = new Vector3(1, 0, 0);
            matrix[1] = new Vector3(0, 1, 0);
            matrix[2] = new Vector3(0, 0, 1);
            return(matrix);
        }

        Vector3 aRot = Vector3.zero;
        Vector3 bRot = Vector3.zero;
        Vector3 cRot = Vector3.zero;

        if ((rotation & 2) != 0)
        {
            if ((rotation & 16) != 0)
            {
                aRot = new Vector3(0, 0, -1f);
            }
            else
            {
                aRot = new Vector3(0, 0, 1f);
            }
        }
        else if ((rotation & 1) != 0)
        {
            if ((rotation & 16) != 0)
            {
                aRot = new Vector3(0, -1f, 0);
            }
            else
            {
                aRot = new Vector3(0, 1f, 0);
            }
        }
        else
        {
            if ((rotation & 16) != 0)
            {
                aRot = new Vector3(-1f, 0, 0);
            }
            else
            {
                aRot = new Vector3(1f, 0, 0);
            }
        }

        if ((rotation & 8) != 0)
        {
            if ((rotation & 32) != 0)
            {
                bRot = new Vector3(0, 0, -1f);
            }
            else
            {
                bRot = new Vector3(0, 0, 1f);
            }
        }
        else if ((rotation & 4) != 0)
        {
            if ((rotation & 32) != 0)
            {
                bRot = new Vector3(0, -1f, 0);
            }
            else
            {
                bRot = new Vector3(0, 1f, 0);
            }
        }
        else
        {
            if ((rotation & 32) != 0)
            {
                bRot = new Vector3(-1f, 0, 0);
            }
            else
            {
                bRot = new Vector3(1f, 0, 0);
            }
        }

        float xR  = 0;
        float yR  = 0;
        float zR  = 0;
        float sgn = 1;

        if ((rotation & 64) != 0)
        {
            sgn = -1;
        }
        if (aRot.x == 0 && bRot.x == 0)
        {
            xR = 1f * sgn;
        }
        else if (aRot.y == 0 && bRot.y == 0)
        {
            yR = 1f * sgn;
        }
        else if (aRot.z == 0 && bRot.z == 0)
        {
            zR = 1f * sgn;
        }
        cRot = new Vector3(xR, yR, zR);

        matrix[0] = aRot;
        matrix[1] = bRot;
        matrix[2] = cRot;

        return(matrix);
    }