// Update is called once per frame
        public void VoxelPhysicUpdate()
        {
            this.container = this.gameObject.GetComponent <VoxelContainer>();
            if (this.container == null)
            {
                return;
            }

            switch (this.currentState)
            {
            case PhysicsState.WaitingForTask:
                this.DoWaitForTask();
                return;

            case PhysicsState.Fragmanatation:
                //Fragmantation started by the waiting for Aggregation
                return;

            case PhysicsState.ObjectCreation:
                this.DoObjectCreation();
                return;

            case PhysicsState.MovingDataToObjects:
                return;

            case PhysicsState.Finalisation:
                this.DoFinalization();
                return;
            }
        }
        private void ShootArray(Vector3 aPosition, Vector3 adirection, VoxelContainer aContainer, MeshCollider aCollider, Texture2D aObjectTexture)
        {
            //Physics.SphereCastAll(aPosition, 0.05f, adirection, Mathf.Infinity);
            RaycastHit[] hits = Physics.RaycastAll(aPosition, adirection, Mathf.Infinity);
            foreach (RaycastHit hit in hits)
            {
                if (hit.collider == aCollider)
                {
                    Vector3 newPosition = hit.point - aCollider.gameObject.transform.position;
                    newPosition.x = (int)Mathf.RoundToInt(newPosition.x);
                    newPosition.y = (int)Mathf.RoundToInt(newPosition.y);
                    newPosition.z = (int)Mathf.RoundToInt(newPosition.z);

                    Voxel newVoxel;
                    if (!aContainer.voxels.ContainsKey(newPosition))
                    {
                        newVoxel = this.AddVoxelAtPosition(newPosition, aContainer, aCollider);
                        if (aObjectTexture != null)
                        {
                            Color palettedColor = this.GetColorByTolerance(aObjectTexture.GetPixel((int)(hit.textureCoord.x * aObjectTexture.width), (int)(hit.textureCoord.y * aObjectTexture.height)));
                            newVoxel.color = palettedColor;
                        }
                    }
                }
            }
        }
Beispiel #3
0
    public void PlaceDamage(int x, int y, int z, float amount)
    {
        int cx, cy, cz;

        Utils.CoordVoxelToChunk(x, y, z, out cx, out cy, out cz, ChunkSize);
        int vx, vy, vz;

        Utils.CoordChunkToVoxel(cx, cy, cz, out vx, out vy, out vz);
        VoxelContainer vc = null;

        if (VoxelContainer.Containers.TryGetValue(Utils.VoxelCoordToLong(cx, cy, cz), out vc))
        {
            var key = Utils.VoxelCoordToLong(x - vx, y - vy, z - vz);

            if (vc.Damages.ContainsKey(key))
            {
                vc.Damages[key] += amount;
            }
            else
            {
                vc.Damages.Add(key, amount);
            }
            vc.BreaksProcessingNeeded = true;
            if (vc.Damages[key] > 1)
            {
                PlaceVoxel(x, y, z, 0, true);
            }
        }
    }
    List<TexturedVertex> GenerateVertsFor(VoxelContainer data, IntVector3 start, IntVector3 end)
    {
        var verts = new List<TexturedVertex>();
        var here = new IntVector3(data.Start);
        //Voxel currentVoxel;
        Vector3[] currentVerts;
        Vector2[] currentUVs;

        for (here.X = start.X; here.X <= end.X; here.X++)
            for (here.Z = start.Z; here.Z <= end.Z; here.Z++)
                for (here.Y = start.Y; here.Y <= end.Y; here.Y++)
                {
                    //currentVoxel = data.GetVoxel(here);
                    foreach (var face in VoxelHelper.VisibleFacesFor(data, here))
                    {
                        currentVerts = VoxelHelper.FaceVerts(here, face).ToArray();
                        currentUVs = VoxelHelper.UVCoords(data.GetVoxel(here).Type, face, Atlas).ToArray();

                        verts.AddRange(new []{
                            new TexturedVertex(currentVerts[0], currentUVs[0]),
                            new TexturedVertex(currentVerts[1], currentUVs[1]),
                            new TexturedVertex(currentVerts[2], currentUVs[2]),
                            new TexturedVertex(currentVerts[3], currentUVs[3])
                        });
                    }
                }

        return verts;
    }
        private GameObject ConvertSprite(Sprite aSprite)
        {
            Texture2D editableTexture = this.GetReadableTexture(aSprite.texture);

            //Create simple container object
            GameObject rootObject = new GameObject();

            rootObject.transform.position = new Vector3(0f, 0f, 0f);
            rootObject.name = StaticValues.baseObjectNamePrefix + aSprite.name;
            //Create Voxel container component for the root object
            VoxelContainer voxelContainer = rootObject.AddComponent <VoxelContainer>();

            voxelContainer.ConvertTexture(editableTexture, aSprite.textureRect.min, aSprite.textureRect.max, this.alphaColor, this.alphaTolerance);
            voxelContainer.BuildOptimizedMesh(false);

            string assetPath = "Assets/" + StaticValues.voxelizerRootFolder + "/" + StaticValues.animationPrefabsFolder + "/" + rootObject.name + ".prefab";

            PrefabUtility.CreatePrefab(assetPath, rootObject);
            DestroyImmediate(rootObject);
#if UNITY_5_0
            return((GameObject)AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)));
#else
            return(AssetDatabase.LoadAssetAtPath <GameObject>(assetPath));
#endif
        }
Beispiel #6
0
        public static void Explode(VoxelContainer voxelContainer)
        {
            var vc = voxelContainer;
            var cd = vc.ContainerData;

            for (var x = 1; x < cd.Size - 1; x += 2)
            {
                for (var y = 1; y < cd.Size - 1; y += 2)
                {
                    for (var z = 1; z < cd.Size - 1; z += 2)
                    {
                        if (cd.Voxels[x, y, z] == null)
                        {
                            continue;
                        }
                        if (cd.Voxels[x, y, z].IsActive)
                        {
                            var pos = new Vector3(cd.Position.x + x, cd.Position.y + y, cd.Position.z + z);
                            var go  = ObjectPool.Instance.GetObjectForType <Fraction>(parent: voxelContainer.transform.parent);
                            go.Init(pos, 2.0f, MaterialRegistry.Instance.MaterialFromId(cd.Voxels[x, y, z].BlockType).Color, voxelContainer.GetCenter());
                        }
                    }
                }
            }
            DestroyImmediate(voxelContainer.gameObject);
        }
Beispiel #7
0
 public void NewVoxelStructure()
 {
     GameObject newGameObject = new GameObject();
     VoxelContainer newVoxelContainer = newGameObject.AddComponent<VoxelContainer>();
     for (int i = 0; i < this.sizeVector.x; i++)
     {
         for (int j = 0; j < this.sizeVector.y; j++)
         {
             for (int z = 0; z < this.sizeVector.z; z++)
             {
                 Voxel newVoxel = new Voxel();
                 newVoxel.position.x = i;
                 newVoxel.position.y = j;
                 newVoxel.position.z = z;
                 newVoxelContainer.AddVoxel(newVoxel);
             }
         }
     }
     newVoxelContainer.BuildMesh(false, true, true, true);         
   
     if (SceneView.lastActiveSceneView != null)
     {
         UnityEditor.Selection.activeGameObject = newGameObject;
         SceneView.lastActiveSceneView.pivot = newGameObject.transform.position;
         SceneView.lastActiveSceneView.Repaint();                
     }
 }
Beispiel #8
0
 public void SetContainer(VoxelContainer acontainer)
 {
     this.container = acontainer;
     if (this.voxelList == null)
     {
         this.voxelList = new List <Voxel>();
     }
 }
Beispiel #9
0
    public void PlaceVoxel(int x, int y, int z, int type, bool overwrite = true)
    {
        //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        //cube.transform.position = new Vector3(x, y, z) + Vector3.one * 0.5f;
        //cube.renderer.material.color = Color.red;

        int cx, cy, cz;

        Utils.CoordVoxelToChunk(x, y, z, out cx, out cy, out cz, ChunkSize);
        int vx, vy, vz;

        Utils.CoordChunkToVoxel(cx, cy, cz, out vx, out vy, out vz);
        VoxelContainer vc = null;

        if (!VoxelContainer.Containers.TryGetValue(Utils.VoxelCoordToLong(cx, cy, cz), out vc))
        {
            GameObject go = new GameObject("Voxel Container");
            go.transform.parent = WorldManager.Active.transform;
            vc               = go.AddComponent <VoxelContainer>();
            vc.SideTexture   = WorldManager.Active.SideTexture;
            vc.TopTexture    = WorldManager.Active.TopTexture;
            vc.BottomTexture = WorldManager.Active.BottomTexture;
            vc.Shader        = WorldManager.Active.VoxelShader;
            vc.LiquidShader  = WorldManager.Active.LiquidShader;
            vc.BreakTexture  = WorldManager.Active.BreakTexture;

            vc.X = cx;
            vc.Y = cy;
            vc.Z = cz;
            vc.Register();
            go.isStatic           = true;
            go.transform.position = new Vector3(vx, vy, vz);
        }
        lock (vc.Voxels)
        {
            var key = Utils.VoxelCoordToLong(x - vx, y - vy, z - vz);
            if (type == 0)
            {
                vc.Voxels.Remove(key);
                if (sygnalize)
                {
                    vc.ProcessingNeeded = true;
                }
            }
            else if (overwrite || !vc.Voxels.ContainsKey(key))
            {
                bool changed = vc.Voxels.AddOrReplace(key, type);
                if (changed && sygnalize)
                {
                    vc.ProcessingNeeded = true;
                }
            }
        }
    }
Beispiel #10
0
        private void ExtrudePart(Texture2D curTexture, Vector2 startPos, Vector2 endPos)
        {
            //Create simple container object
            GameObject rootObject = new GameObject();

            rootObject.transform.position = new Vector3(0f, 0f, 0f);
            rootObject.name = StaticValues.baseObjectNamePrefix + curTexture.name;
            //Create Voxel container component for the root object
            VoxelContainer voxelContainer = rootObject.AddComponent <VoxelContainer>();

            voxelContainer.ConvertTexture(curTexture, startPos, endPos, this.alphaColor, this.alphaTolerance);
        }
Beispiel #11
0
        /*
         * Instantiate and fix the frame list if neccesary
         */
        private void InstantiatePrefabs()
        {
            bool matchingAlreadyInstaniated = true;

            if (this.voxelContainerPrefabs.Count != this.frames.Count)
            {
                matchingAlreadyInstaniated = false;
            }
            else
            {
                for (int i = 0; i < this.voxelContainerPrefabs.Count; i++)
                {
                    GameObject curPrefab = this.voxelContainerPrefabs[i];
                    GameObject curFrame  = this.frames[i];
                    if (curFrame == null)
                    {
                        matchingAlreadyInstaniated = false;
                        break;
                    }
                    VoxelContainer prefabContainer     = curPrefab.GetComponent <VoxelContainer>();
                    VoxelContainer frameVoxelContainer = curFrame.GetComponent <VoxelContainer>();
                    if (prefabContainer == null)
                    {
                        Debug.LogError("One of the prefab in the animation '" + this.animationName + "' is does not have VoxelContainer!");
                        return;
                    }

                    if (prefabContainer.modelFilename != frameVoxelContainer.modelFilename)
                    {
                        matchingAlreadyInstaniated = false;
                        break;
                    }
                }
            }
            if (!matchingAlreadyInstaniated)
            {
                foreach (GameObject curFrame in this.frames)
                {
                    DestroyImmediate(curFrame);
                }
                this.frames.Clear();

                foreach (GameObject curPrefab in this.voxelContainerPrefabs)
                {
                    GameObject newObject = Instantiate(curPrefab);
                    newObject.transform.parent = this.transform;
                    newObject.SetActive(false);
                    this.frames.Add(newObject);
                }
            }
        }
        private Voxel AddVoxelAtPosition(Vector3 aPosition, VoxelContainer aVoxelContainer, MeshCollider aMeshCollider)
        {
            if (aVoxelContainer.voxels.ContainsKey(aPosition))
            {
                return(aVoxelContainer.voxels[aPosition]);
            }

            Voxel newVoxel = new Voxel();

            newVoxel.position = aPosition;
            newVoxel.SetContainer(aVoxelContainer);
            aVoxelContainer.AddVoxel(newVoxel);
            return(newVoxel);
        }
Beispiel #13
0
 // Use this for initialization
 void Start()
 {
     this.container = this.gameObject.GetComponent <VoxelContainer>();
     if (this.container == null)
     {
         Debug.LogError("VoxelPhysics need a voxelcontainer on the same gameobject to work.");
     }
     else
     {
         lock (this.container.voxels)
         {
             this.lastVoxelCount = container.voxels.Count;
         }
     }
 }
    public override Mesh GenerateMesh(VoxelContainer data, IntVector3 start, IntVector3 end)
    {
        var verts = GenerateVertsFor(data, start, end);

        if (!verts.Any())
            return null;

        var result = new Mesh()
        {
            vertices = verts.Select(v => v.Position).ToArray(),
            uv = verts.Select(v => v.Uv).ToArray()
        };
        result.SetTriangles(GenerateIndicesFor(verts).ToArray(), 0);
        return result;
    }
Beispiel #15
0
    public Voxel getSubVoxelAt(int layer, int columnID, string subID)
    {
        // v should be a voxel container for this to be a valid call to destroy subvoxel
        Voxel v = MapManager.manager.voxels[layer][columnID];

        if (subID.ToCharArray()[0] == ',')
        {
            subID = subID.Substring(1);
        }

        int shatterLevel = subID.Split(',').Length - 1;

        for (int i = 0; i <= shatterLevel; i++)
        {
            if (v == null)
            {
                Debug.LogError("found null voxel looking for subvoxel: " + layer + "," + columnID + "," + subID + " ; failed at level: " + i);
                break;
            }
            VoxelContainer vc = v.gameObject.GetComponent <VoxelContainer>();
            if (vc.subVoxels == null)
            {
                Debug.LogError("vox cont " + vc + " has a null subvoxels array");
                return(null);
            }
            int id = -1;
            try
            {
                id = int.Parse(subID.Split(',')[i]);
            }
            catch (Exception e)
            {
                Debug.LogError("trying to parse " + subID + " index " + i + "into an int, which failed\t" + e.Message);
                return(null);
            }
            try
            {
                v = (Voxel)vc.subVoxels[id]; // TODO try catch, this isn't working every time
            }
            catch (Exception e)
            {
                Debug.LogError("trying to get subvoxel at " + subID + " from " + vc + " failed at shatterlevel " + i + " id = " + id + " num subvoxels = " + vc.subVoxels.Count + "\t" + e.Message);
                return(null);
            }
        }

        return(v);
    }
        private void CheckVoxel(Vector3 aPosition, VoxelContainer aContainer, MeshCollider aCollider, Texture2D aObjectTexture)
        {
            //Physics.SphereCastAll(aPosition, 0.05f, adirection, Mathf.Infinity);
            for (int i = 0; i < 6; i++)
            {
                if (!this.CheckIfInnerPoint(aPosition, aCollider, StaticValues.sixDirectionArray[i]))
                {
                    return;
                }
            }
            //Coord is inside

            Vector3 voxelPosition = this.RoundVector(aPosition);

            Color curColor    = Color.white;
            float curDistance = -1;

            for (int i = 0; i < 6; i++)
            {
                Vector3      curDirection = StaticValues.sixDirectionArray[i];
                RaycastHit[] hits         = Physics.RaycastAll(aPosition + (curDirection * 10000f), -curDirection, Mathf.Infinity);
                foreach (RaycastHit hit in hits)
                {
                    if (hit.collider == aCollider)
                    {
                        if ((curDistance == -1) || (curDistance > Vector3.Distance(voxelPosition, hit.point)))
                        {
                            curDistance = Vector3.Distance(voxelPosition, hit.point);
                            if (aObjectTexture != null)
                            {
                                curColor = this.GetColorByTolerance(aObjectTexture.GetPixel((int)(hit.textureCoord.x * aObjectTexture.width), (int)(hit.textureCoord.y * aObjectTexture.height)));
                            }
                        }
                    }
                }
            }
            if (!aContainer.voxels.ContainsKey(voxelPosition))
            {
                voxelPosition = voxelPosition - aCollider.transform.position;
                voxelPosition = this.RoundVector(voxelPosition);
                Voxel newVoxel = this.AddVoxelAtPosition(voxelPosition, aContainer, aCollider);
                if (aObjectTexture != null)
                {
                    newVoxel.color = curColor;
                }
            }
        }
        public void Init(VoxelLayer aLayer, ParamForOptimizerThread aTextureParam, Vector3 aVectorX, Vector3 aVectorY, Vector3 aOffset, int aOptmalisationMinMergableVoxels, VoxelContainer aContainer)
        {
            vertices  = new List <Vector3>();
            uvs       = new List <Vector2>();
            triangles = new List <int>();

            this.layer   = aLayer;
            this.texture = aTextureParam.voxelTexture;
            this.vectorX = aVectorX;
            this.vectorY = aVectorY;
            this.offset  = aOffset;
            this.optmalisationMinMergableVoxels = aOptmalisationMinMergableVoxels;
            this.ownerContainer = aContainer;
            this.textureWidth   = aTextureParam.textureWidth;
            this.textureHeight  = aTextureParam.textureHeight;
            //      this.ownerContainer.PrepareTextureAndUVDictionary(true);
        }
Beispiel #18
0
    internal void replaceSubVoxel(Voxel spawnedVox)
    {
        Voxel v = MapManager.manager.voxels[spawnedVox.layer][spawnedVox.columnID]; //v should be a voxel container for this to be a valid call to destroy subvoxel
        //Debug.Log("found top level container: " + v + " of type: " + v.GetType());
        int shatterLevel = spawnedVox.subVoxelID.Split(',').Length - 1;

        VoxelContainer vc = null;

        for (int i = 1; i <= shatterLevel; i++)
        {
            vc = v.gameObject.GetComponent <VoxelContainer>();
            //Debug.Log("opening container " + vc + " - " + vc.subVoxelID);
            v = (Voxel)vc.subVoxels[int.Parse(spawnedVox.subVoxelID.Split(',')[i])];
            //Debug.Log("opening contained subVoxel " + v + " - " + v.subVoxelID);
        }

        vc.subVoxels[int.Parse(spawnedVox.subVoxelID.Split(',')[shatterLevel])] = spawnedVox;
    }
Beispiel #19
0
    public Voxel getSubVoxelAt(int layer, int columnID, String subID)
    {
        // v should be a voxel container for this to be a valid call to destroy subvoxel
        Voxel v = voxels[layer][columnID];

        if (!v.isContainer)
        {
            Debug.LogError("base voxel of given layer, col: " + layer + "," + columnID + " is not a container. cannot find id: " + subID);
            return(null);
        }
        int shatterLevel = subID.Split(',').Length - 1;

        if (subID.ToCharArray()[0] == ',')
        {
            subID = subID.Substring(1);
        }

        string[] ids = subID.Split(',');

        for (int i = 0; i <= ids.Length; i++)
        {
            if (v == null)
            {
                Debug.LogError("found null voxel looking for subvoxel: " + layer + "," + columnID + "," + subID + " ; failed at level: " + i);
                return(null);
            }

            VoxelContainer vc = v.gameObject.GetComponent <VoxelContainer>();
            if (vc == null)
            {
                Debug.LogError("no voxel container comp attached to contained voxel: " + v.gameObject + " trying to get sub id: " + subID);
            }

            int id = -1;
            id = int.Parse(subID.Split(',')[i]);

            v = (Voxel)vc.subVoxels[id];
        }

        return(v);
    }
Beispiel #20
0
    public int?GetVoxel(int x, int y, int z)
    {
        int cx, cy, cz;

        Utils.CoordVoxelToChunk(x, y, z, out cx, out cy, out cz, ChunkSize);
        VoxelContainer vc = null;

        if (!VoxelContainer.Containers.TryGetValue(Utils.VoxelCoordToLong(cx, cy, cz), out vc))
        {
            return(null);
        }
        int val;
        int vx, vy, vz;

        Utils.CoordChunkToVoxel(cx, cy, cz, out vx, out vy, out vz);
        if (vc.Voxels.TryGetValue(Utils.VoxelCoordToLong(x - vx, y - vy, z - vz), out val))
        {
            return(val);
        }
        return(null);
    }
Beispiel #21
0
    private void addVoxelContainer(Voxel v)
    {
        VoxelContainer vc = v.GetComponent <VoxelContainer>();

        if (vc != null)
        {
            foreach (Voxel subVox in vc.subVoxels)
            {
                if (subVox.isContainer)
                {
                    addVoxelContainer(subVox);
                }
                else
                {
                    addVoxel(subVox);
                }
            }
        }
        else
        {
            Debug.LogError("no voxel container attached to voxel (" + v.gameObject + ") with isContainer = " + v.isContainer);
        }
    }
Beispiel #22
0
        private Texture2D GetTexture()
        {
            //handling input errors
            if (sourceTexture == null)
            {
                EditorUtility.DisplayDialog("Error", "Please set the source texture before convert.", "Ok");
                return(null);
            }

            //Reimport the texture if it is not readable
            Texture2D curTexture = this.sourceTexture;

            try
            {
                curTexture.GetPixel(0, 0);
            }
            catch
            {
                Debug.Log("Reimporting texture, because it is not readable.");
                curTexture = VoxelContainer.ReImportTexture(this.sourceTexture);
            }
            return(curTexture);
        }
        private void ExportObjectToVoxFile(string aFilename)
        {
            GameObject     tempGameObject = new GameObject();
            VoxelContainer voxelContainer = tempGameObject.AddComponent <VoxelContainer>();

            try
            {
                List <VoxelContainer> containers    = new List <VoxelContainer>();
                VoxelContainer        rootContainer = this.voxelObject.GetComponent <VoxelContainer>();
                if (this.exportChildObjects)
                {
                    containers.AddRange(this.voxelObject.transform.GetComponentsInChildren <VoxelContainer>());
                }
                else
                {
                    if (rootContainer != null)
                    {
                        containers.Add(rootContainer);
                    }
                }

                foreach (VoxelContainer curContainer in containers)
                {
                    foreach (Voxel curVoxel in curContainer.voxels.Values)
                    {
                        Voxel newVoxel = new Voxel();
                        newVoxel.color = curVoxel.color;
                        //Transform the positions into the same matrix
                        newVoxel.position = this.voxelObject.transform.InverseTransformPoint(curContainer.gameObject.transform.TransformPoint(curVoxel.position));
                        voxelContainer.AddVoxel(newVoxel, false);
                    }
                }


                if (voxelContainer.voxels.Count == 0)
                {
                    Debug.LogError("Vox Export: Did not found voxels or voxelContainer in the structure! Please make sure you selected an object with voxelcontainer");
                    return;
                }

                if (Path.GetExtension(aFilename).ToUpper() != ".vox".ToUpper())
                {
                    Debug.LogError("Extension must be .vox");
                    return;
                }

                BinaryWriter bw = new BinaryWriter(File.OpenWrite(aFilename));
                try
                {
                    char[] magicalString = "VOX ".ToCharArray();
                    bw.Write(magicalString);
                    int fileVersion = 150;
                    bw.Write(fileVersion);

                    //Main chunk
                    //Chunk header
                    char[] mainChunk = "MAIN".ToCharArray();
                    bw.Write(mainChunk);
                    int chunkSize = 0;                                                                   //3*4bytes
                    bw.Write(chunkSize);
                    int childChunks = (3 * 12) + 12 + (voxelContainer.voxels.Count * 4) + 4 + (256 * 4); //3 chunk header + size values + voxels values + voxelnumbers + color palette
                    bw.Write(childChunks);

                    //Size chunk
                    //Chunk header
                    char[] sizeChunk = "SIZE".ToCharArray();
                    bw.Write(sizeChunk);
                    chunkSize = 3 * 4;//3*4bytes
                    bw.Write(chunkSize);
                    childChunks = 0;
                    bw.Write(childChunks);

                    //Chunk data
                    Vector3 sizeVector = voxelContainer.GetMaxContainerVector() - voxelContainer.GetMinContainerVector();
                    int     size       = (int)sizeVector.x;
                    bw.Write(size); //x
                    size = (int)sizeVector.z;
                    bw.Write(size); //y
                    size = (int)sizeVector.y;
                    bw.Write(size); //z

                    //XYZI chunk
                    //Chunk header
                    char[] XYZIChunk = "XYZI".ToCharArray();
                    bw.Write(XYZIChunk);
                    chunkSize = 4 * voxelContainer.voxels.Count + 4;//the Voxel's preferences are stored on 4 bytes
                    bw.Write(chunkSize);
                    childChunks = 0;
                    bw.Write(childChunks);

                    List <Color> colorPalette = voxelContainer.GetColorPalette();
                    if (colorPalette.Count > 255)
                    {
                        Debug.LogError("Export Failed: MagicaVoxel does not support more then 255 colors.");
                        return;
                    }

                    //Prepare Transform Vector
                    //We need it because, it looks like MagicaVoxel drops everything under 0
                    Vector3 transFormVector = Vector3.zero;
                    Vector3 minVector       = voxelContainer.GetMinContainerVector();
                    if (minVector.x < 0)
                    {
                        transFormVector.x = minVector.x * -1f;
                    }
                    if (minVector.y < 0)
                    {
                        transFormVector.y = minVector.y * -1f;
                    }
                    if (minVector.z < 0)
                    {
                        transFormVector.z = minVector.z * -1f;
                    }

                    //Chunk Data
                    int voxelNumber = voxelContainer.voxels.Count;
                    bw.Write(voxelNumber);
                    foreach (Voxel curVoxel in voxelContainer.voxels.Values)
                    {
                        Vector3 voxelPos = curVoxel.position + transFormVector;
                        byte    coord    = (byte)voxelPos.x;
                        bw.Write(coord);
                        coord = (byte)voxelPos.z;
                        bw.Write(coord);
                        coord = (byte)voxelPos.y;
                        bw.Write(coord);
                        byte colorIndex = (byte)(colorPalette.IndexOf(curVoxel.color) + 1);
                        bw.Write(colorIndex);
                    }

                    //RGBA chunk
                    //Chunk header
                    char[] RGBAChunk = "RGBA".ToCharArray();
                    bw.Write(RGBAChunk);
                    chunkSize = 4 * 256;//Colors are stored in bytes
                    bw.Write(chunkSize);
                    childChunks = 0;
                    bw.Write(childChunks);

                    //Color data
                    for (int j = 0; j < colorPalette.Count; j++)
                    {
                        byte colorR = (byte)(colorPalette[j].r * 255);
                        bw.Write(colorR);
                        byte colorG = (byte)(colorPalette[j].g * 255);
                        bw.Write(colorG);
                        byte colorB = (byte)(colorPalette[j].b * 255);
                        bw.Write(colorB);
                        byte colorA = (byte)(colorPalette[j].a * 255);
                        bw.Write(colorA);
                    }
                    if (colorPalette.Count < 256)
                    {
                        //Fill update the color palette to 255
                        for (int j = colorPalette.Count; j < 256; j++)
                        {
                            for (int k = 0; k < 4; k++)
                            {
                                byte color = 255;
                                bw.Write(color);
                            }
                        }
                    }
                }
                finally
                {
                    bw.Flush();
                    bw.Close();
                }
            }
            finally
            {
                DestroyImmediate(tempGameObject);
            }
        }
        private void ImportAssetOptionsQEObject(string aFilename)
        {
            if (Path.GetExtension(aFilename).ToUpper() != ".qb".ToUpper())
            {
                Debug.LogError("Extension must be .qb");
                return;
            }

            //Consts
            uint CODEFLAG      = 2;
            uint NEXTSLICEFLAG = 6;

            //Parent Gameobject
            GameObject parentGameObject = new GameObject();

            parentGameObject.name = Path.GetFileNameWithoutExtension(aFilename);

            BinaryReader br = new BinaryReader(File.Open(aFilename, FileMode.Open));

            try
            {
                if (br == null)
                {
                    Debug.Log("VoxelMax: Could not open file. Filename: " + aFilename);
                    return;
                }
                uint fileVersion           = br.ReadUInt32();
                uint colorFormat           = br.ReadUInt32();
                uint zAxisOrientation      = br.ReadUInt32();
                uint compressed            = br.ReadUInt32();
                uint visibilityMaskEncoded = br.ReadUInt32();
                uint numMatrices           = br.ReadUInt32();
                Debug.Log("Qubicle File Import Info\r\n" +
                          "File Version: " + fileVersion + "\r\n" +
                          "Color Format: " + colorFormat + "\r\n" +
                          "zAxisOrientation: " + zAxisOrientation + "\r\n" +
                          "visibilityMaskEncoded: " + visibilityMaskEncoded + "\r\n" +
                          "Object Count: " + numMatrices);

                for (uint i = 0; i < numMatrices; i++)
                {
                    // read matrix name
                    byte   nameLength = br.ReadByte();
                    string matrixName = new string(br.ReadChars(nameLength));

                    GameObject newGameObject = new GameObject();
                    newGameObject.transform.parent = parentGameObject.transform;
                    newGameObject.name             = matrixName;
                    VoxelContainer newVoxelContainer = newGameObject.AddComponent <VoxelContainer>();

                    // read matrix size
                    uint sizeX = br.ReadUInt32();
                    uint sizeY = br.ReadUInt32();
                    uint sizeZ = br.ReadUInt32();

                    // read matrix position (in this example the position is irrelevant)
                    int posX = br.ReadInt32();
                    int posY = br.ReadInt32();
                    int posZ = br.ReadInt32();

                    newGameObject.transform.position = new Vector3(posX, posY, posZ);
                    if (compressed == 0) // if uncompressd
                    {
                        for (uint z = 0; z < sizeZ; z++)
                        {
                            for (uint y = 0; y < sizeY; y++)
                            {
                                for (uint x = 0; x < sizeX; x++)
                                {
                                    uint curColor = br.ReadUInt32();
                                    if (curColor != 0)
                                    {
                                        Voxel newVoxel = new Voxel();
                                        newVoxel.position = new Vector3(x, y, z);
                                        newVoxel.color    = this.UIntToColor(curColor);
                                        newVoxelContainer.AddVoxel(newVoxel, false);
                                    }
                                }
                            }
                        }
                    }
                    else // if compressed
                    {
                        uint z = 0;

                        while (z < sizeZ)
                        {
                            z++;
                            uint index = 0;

                            while (true)
                            {
                                uint data = br.ReadUInt32();

                                if (data == NEXTSLICEFLAG)
                                {
                                    break;
                                }
                                else if (data == CODEFLAG)
                                {
                                    uint count = br.ReadUInt32();
                                    data = br.ReadUInt32();

                                    for (uint j = 0; j < count; j++)
                                    {
                                        uint x = index % sizeX + 1; // mod = modulo e.g. 12 mod 8 = 4
                                        uint y = index / sizeX + 1; // div = integer division e.g. 12 div 8 = 1
                                        index++;

                                        if (data != 0)
                                        {
                                            Voxel newVoxel = new Voxel();
                                            newVoxel.position = new Vector3(x, y, z);
                                            newVoxel.color    = this.UIntToColor(data);
                                            newVoxelContainer.AddVoxel(newVoxel, false);
                                        }
                                    }
                                }
                                else
                                {
                                    uint x = index % sizeX + 1;
                                    uint y = index / sizeX + 1;
                                    index++;

                                    if (data != 0)
                                    {
                                        Voxel newVoxel = new Voxel();
                                        newVoxel.position = new Vector3(x, y, z);
                                        newVoxel.color    = this.UIntToColor(data);
                                        newVoxelContainer.AddVoxel(newVoxel, false);
                                    }
                                }
                            }
                        }
                    }

                    newVoxelContainer.UpdateStructure();
                    newVoxelContainer.BuildMesh(true, true, true, true);
                }
            }
            finally
            {
                br.Close();
            }
        }
        private GameObject ConvertObject(GameObject aObject)
        {
            if (aObject == null)
            {
                return(null);
            }

            GameObject newVoxelObject = new GameObject();

            newVoxelObject.name = aObject.name + "_Converted";

            if (this.isRecursive)
            {
                //I do this because the child list always change because
                //I have to removed the child while I convert it since
                //the mesh collider does not look to be workin as a child for me.
                //Reach out for me if you have better idea :)
                List <Transform> childList = new List <Transform>();
                for (int i = 0; i < aObject.transform.childCount; i++)
                {
                    childList.Add(aObject.transform.GetChild(i));
                }

                for (int i = 0; i < childList.Count; i++)
                {
                    GameObject newChild = this.ConvertObject(childList[i].gameObject);
                    if (newChild != null)
                    {
                        newChild.transform.parent        = newVoxelObject.transform;
                        newChild.transform.localPosition = childList[i].localPosition;
                    }
                }
            }

            MeshCollider meshcollider = aObject.GetComponent <MeshCollider>();

            if (meshcollider == null)
            {
                UnityEngine.Debug.LogError("VoxelMax: Source Object need meshcollider to be converted!");
                return(newVoxelObject);
            }

            EditorUtility.ClearProgressBar();
            EditorUtility.DisplayCancelableProgressBar("Building Voxel Matrix", "Building", 0f);

            //Clear colorpalette
            this.colorPalette = null;
            this.colorPalette = new List <Color>();


            VoxelContainer voxelContainer = newVoxelObject.AddComponent <VoxelContainer>();

            try
            {
                //Get Texture
                Texture2D objectTexture = null;
                Renderer  objRenderer   = aObject.GetComponent <Renderer>();
                if (objRenderer != null)
                {
                    if (objRenderer.sharedMaterial != null)
                    {
                        objectTexture = (Texture2D)objRenderer.sharedMaterial.mainTexture;
                        if (objectTexture != null)
                        {
                            try
                            {
                                objectTexture.GetPixel(0, 0);
                            }
                            catch
                            {
                                UnityEngine.Debug.Log("Reimporting texture, because it is not readable.");
                                objectTexture = VoxelContainer.ReImportTexture(objectTexture);
                            }
                        }
                    }
                }
                Transform originalParent = aObject.transform.parent;
                aObject.transform.parent = null;
                float maxStepCount = (meshcollider.bounds.max.x - meshcollider.bounds.min.x + 2) *
                                     (meshcollider.bounds.max.y - meshcollider.bounds.min.y + 2) *
                                     (meshcollider.bounds.max.z - meshcollider.bounds.min.z + 2);

                float eachStep = (meshcollider.bounds.max.y - meshcollider.bounds.min.y + 2) *
                                 (meshcollider.bounds.max.z - meshcollider.bounds.min.z + 2);


                for (float x = (int)(meshcollider.bounds.min.x - 1f); x <= meshcollider.bounds.max.x + 1f; x += 1f)
                {
                    for (float y = (int)(meshcollider.bounds.min.y - 1f); y <= meshcollider.bounds.max.y + 1f; y += 1f)
                    {
                        for (float z = (int)(meshcollider.bounds.min.z - 1f); z <= meshcollider.bounds.max.z + 1f; z += 1f)
                        {
                            Vector3 shootOrigin = new Vector3(x, y, z);
                            if (this.selectedAlgorithm == ConvertAlgorithm.RayBased)
                            {
                                for (int k = 0; k < 6; k++)
                                {
                                    this.ShootArray(shootOrigin, StaticValues.sixDirectionArray[k], voxelContainer, meshcollider, objectTexture);
                                }
                            }
                            else
                            {
                                this.CheckVoxel(shootOrigin, voxelContainer, meshcollider, objectTexture);
                            }
                        }
                    }
                    if (EditorUtility.DisplayCancelableProgressBar("Building Voxel Matrix", "Building", (eachStep * x) / maxStepCount))
                    {
                        EditorUtility.ClearProgressBar();
                        return(null);
                    }
                }
                aObject.transform.parent = originalParent;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            //      if (this.selectedAlgorithm == ConvertAlgorithm.RayBased)
            //         voxelContainer.FillUpObject();
            voxelContainer.BuildMesh(true, true, true, true);

            if (SceneView.lastActiveSceneView != null)
            {
                UnityEditor.Selection.activeGameObject = newVoxelObject;
                SceneView.lastActiveSceneView.pivot    = newVoxelObject.transform.position;
                SceneView.lastActiveSceneView.Repaint();
            }
            return(newVoxelObject);
        }
Beispiel #26
0
        // Update is called once per frame
        void Update()
        {
            if ((triggered) && (!this.exploded))
            {
                this.exploded = true;

                //Get the root object
                rootObjectForParticles = GameObject.Find("VoxelMaxExplosionRoot");
                if (rootObjectForParticles == null)
                {
                    rootObjectForParticles      = new GameObject();
                    rootObjectForParticles.name = "VoxelMaxExplosionRoot";
                }

                Collider[] colliderList = Physics.OverlapSphere(this.gameObject.transform.position, this.explosionRadius);
                foreach (Collider curCollider in colliderList)
                {
                    if (curCollider.gameObject.tag == "Indestructible")
                    {
                        continue;
                    }
                    VoxelContainer voxelContainer = curCollider.gameObject.GetComponent <VoxelContainer>();
                    if (voxelContainer != null)
                    {
                        Vector3      torqueVector   = new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)) * this.explosionForce;
                        Vector3      voxelPoint     = voxelContainer.gameObject.transform.InverseTransformPoint(this.gameObject.transform.position);
                        List <Voxel> voxelsToRemove = new List <Voxel>();

                        Vector3      transformedDistance = voxelContainer.gameObject.transform.InverseTransformVector(explosionRadius, 0f, 0f);
                        List <Voxel> voxelList;
                        lock (voxelContainer.voxels)
                        {
                            voxelList = new List <Voxel>(voxelContainer.voxels.Values);
                        }
                        foreach (Voxel curVoxel in voxelList)
                        {
                            float voxDistance = Vector3.Distance(curVoxel.position, voxelPoint);
                            if (voxDistance <= transformedDistance.magnitude)
                            {
                                voxelsToRemove.Add(curVoxel);
                            }
                        }


                        //Do not instantiate every voxel on large explosions to prevent frame drop
                        int particleStepper = 0;
                        if (maxParticleCount != 0)
                        {
                            particleStepper = Mathf.Max((int)(voxelsToRemove.Count / this.maxParticleCount), 1);
                        }

                        for (int i = 0; i < voxelsToRemove.Count; i++)
                        {
                            Voxel curVoxel = voxelsToRemove[i];
                            if ((particleStepper != 0) && ((i % particleStepper) == 0))
                            {
                                if (this.explosionParticle != null)
                                {
                                    GameObject newObject = Instantiate(this.explosionParticle);
                                    newObject.transform.parent     = rootObjectForParticles.transform;
                                    newObject.transform.localScale = voxelContainer.gameObject.transform.localScale;
                                    newObject.transform.position   = voxelContainer.gameObject.transform.TransformPoint(curVoxel.position);

                                    Renderer curRenderer = newObject.GetComponent <Renderer>();
                                    if (curRenderer != null)
                                    {
                                        if (curRenderer.material != null)
                                        {
                                            curRenderer.material.color = curVoxel.color;
                                        }
                                    }

                                    Rigidbody curRigidBody = newObject.GetComponent <Rigidbody>();
                                    if (curRigidBody != null)
                                    {
                                        curRigidBody.AddForce(voxelContainer.gameObject.transform.TransformDirection(curVoxel.position - voxelPoint).normalized *explosionForce);
                                        curRigidBody.AddRelativeTorque(torqueVector);
                                    }
                                }
                            }
                        }
                        voxelContainer.AddBuildTaskRemovedVoxels(voxelsToRemove);
                        VoxelPhysics vPhysics = this.GetComponent <VoxelPhysics>();
                        if ((vPhysics != null) && (vPhysics.enabled))
                        {
                            voxelContainer.rebuildCollider = false;
                        }


                        //Modification for Will
                        if (objectToInstantiate != null)
                        {
                            GameObject newGameObject = Instantiate <GameObject>(this.objectToInstantiate);
                            newGameObject.transform.position = this.gameObject.transform.position;
                            newGameObject.transform.parent   = rootObjectForParticles.transform;
                        }
                    }
                    else
                    {
                        Rigidbody curRigidBody = curCollider.gameObject.GetComponent <Rigidbody>();
                        if (curRigidBody != null)
                        {
                            Vector3 torqueVector = new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)) * this.explosionForce;
                            Vector3 voxelPoint   = curCollider.gameObject.transform.InverseTransformPoint(this.gameObject.transform.position);
                            curRigidBody.AddForce(curCollider.gameObject.transform.TransformDirection(voxelPoint - this.gameObject.transform.position).normalized *explosionForce);
                            curRigidBody.AddRelativeTorque(torqueVector);
                        }
                    }
                }
                Destroy(this.gameObject);
            }
        }
Beispiel #27
0
 public VoxelArea(Vector3 aPosition, VoxelContainer aContainer)
 {
     this.position  = aPosition;
     this.container = aContainer;
 }
        private void LoadVoxFile(string aFileName)
        {
            //I dissabled compiler warning, because we want to load some values from the file even if we would not use it later.
            //I think it is cleaner this way
            #pragma warning disable
            //Prepare Object
            GameObject newGameObject = new GameObject();
            newGameObject.name = "ImportedFromMagicaVoxel";
            VoxelContainer newVoxelContainer = newGameObject.AddComponent <VoxelContainer>();

            //Open File
            BinaryReader br = new BinaryReader(File.OpenRead(aFileName));

            string magic   = new string(br.ReadChars(4));
            int    version = br.ReadInt32();

            if (magic == "VOX ")
            {
                int sizex = 0, sizey = 0, sizez = 0;

                Color[]           colors = null;
                MagicaVoxelData[] voxelData = null;

                while (br.BaseStream.Position < br.BaseStream.Length)
                {
                    char[] chunkId     = br.ReadChars(4);
                    int    chunkSize   = br.ReadInt32();
                    int    childChunks = br.ReadInt32();
                    string chunkName   = new string(chunkId);

                    if (chunkName == "SIZE")
                    {
                        sizex = br.ReadInt32();
                        sizey = br.ReadInt32();
                        sizez = br.ReadInt32();

                        br.ReadBytes(chunkSize - 4 * 3);
                    }
                    else if (chunkName == "XYZI")
                    {
                        int numVoxels = br.ReadInt32();

                        voxelData = new MagicaVoxelData[numVoxels];
                        for (int i = 0; i < voxelData.Length; i++)
                        {
                            voxelData[i] = new MagicaVoxelData(br);
                        }
                    }
                    else if (chunkName == "RGBA")
                    {
                        colors = new Color[256];

                        for (int i = 0; i < 256; i++)
                        {
                            byte r = br.ReadByte();
                            byte g = br.ReadByte();
                            byte b = br.ReadByte();
                            byte a = br.ReadByte();

                            colors[i].r = r / 255f;
                            colors[i].g = g / 255f;
                            colors[i].b = b / 255f;
                            colors[i].a = a / 255f;
                        }
                    }
                    else
                    {
                        br.ReadBytes(chunkSize);
                    }
                }
                if ((voxelData == null) || (voxelData.Length == 0))
                {
                    return;
                }

                for (int i = 0; i < voxelData.Length; i++)
                {
                    Vector3 position = new Vector3(voxelData[i].x, voxelData[i].z, voxelData[i].y);
                    if (!newVoxelContainer.voxels.ContainsKey(position))
                    {
                        Voxel newVoxel = new Voxel();
                        newVoxel.position = position;
                        newVoxel.color    = (colors == null ? UShortToColor(voxColors[voxelData[i].color - 1]) : colors[voxelData[i].color - 1]);
                        newVoxelContainer.AddVoxel(newVoxel, false);
                    }
                }
                newVoxelContainer.UpdateStructure();
                newVoxelContainer.BuildMesh(true, true, true, true);
            }
            else
            {
                Debug.LogError("Error durring vox import. Probably this is not a .vox file.");
                return;
            }
            #pragma warning restore
        }
Beispiel #29
0
        public void DoObjectCreation()
        {
            this.currentState = PhysicsState.ObjectCreation;
            if (showDebugMessages)
            {
                Debug.Log("VoxelMax Physics: Object creation update");
            }


            if (this.physicsAggregatedList == null)
            {
                if (showDebugMessages)
                {
                    Debug.Log("VoxelMax Physics: No fragmented object to create");
                }
                this.currentState = PhysicsState.WaitingForTask;
                return;
            }

            if (this.physicsAggregatedList.Count > 1)
            {
                //Prepare GameObjectList because it can be only done in the main thread
                List <GameObject>     newGameObjectList = new List <GameObject>();
                List <VoxelContainer> newContainerList  = new List <VoxelContainer>();
                for (int i = 0; i < this.physicsAggregatedList.Count - 1; i++)
                {
                    GameObject newGameObject = new GameObject();
                    newGameObject.transform.parent = this.transform;

                    VoxelContainer newContainer = newGameObject.AddComponent <VoxelContainer>();
                    newContainer.enabled         = false;
                    newContainer.modelFilename   = this.container.modelFilename;
                    newContainer.modelName       = this.container.modelName;
                    newContainer.textureFilename = this.container.textureFilename;
                    //newContainer.AssignUVDictionary(this.container);
                    newContainerList.Add(newContainer);
                    this.fragmentContainers.Add(newContainer);

                    MeshRenderer meshRenderer = newGameObject.AddComponent <MeshRenderer>();
                    Rigidbody    rigidBody    = newGameObject.AddComponent <Rigidbody>();
                    newContainer.enabled = false;
                    meshRenderer.enabled = false;
                    rigidBody.useGravity = false;
                    newGameObject.transform.localScale = new Vector3(1f, 1f, 1f);
                    newGameObject.transform.rotation   = this.gameObject.transform.rotation;
                    newGameObject.transform.position   = this.gameObject.transform.position;

                    //Add physics to fragments
                    VoxelPhysics newVoxelPhysics = newGameObject.AddComponent <VoxelPhysics>();
                    newVoxelPhysics.tensionCalculation   = this.tensionCalculation;
                    newVoxelPhysics.layerWidthBreakPoint = this.layerWidthBreakPoint;
                    newVoxelPhysics.enabled = false;

                    newGameObject.GetComponent <Renderer>().sharedMaterial = this.gameObject.GetComponent <MeshRenderer>().sharedMaterial;

                    newGameObjectList.Add(newGameObject);
                }

                //  this.gameObject.GetComponent<MeshCollider>().enabled = false;
                if (this.gameObject.GetComponent <Rigidbody>() != null)
                {
                    this.gameObject.GetComponent <Rigidbody>().useGravity = false;
                }

                this.physicsBuildTask = new PhysicsBuildTask(newGameObjectList, this.physicsAggregatedList, newContainerList);

                this.DoMoveDataToObjects();
            }
            else
            {
                if (this.physicsAggregatedList.Count == 1)
                {
                    if (this.gameObject.GetComponent <Rigidbody>() == null)
                    {
                        //   Rigidbody curRigidBody = this.gameObject.AddComponent<Rigidbody>();
                        //   curRigidBody.mass = this.container.voxels.Count;
                    }

                    MeshCollider meshCollider = this.gameObject.GetComponent <MeshCollider>();
                    if (meshCollider != null)
                    {
                        Destroy(meshCollider);
                    }
                    this.physicsBuildTask = new PhysicsBuildTask(null, this.physicsAggregatedList, null);

                    this.DoMoveDataToObjects();
                }
            }
        }
Beispiel #30
0
        private void MoveAggregatedVoxelsIntoNewContainers(object aBuildTask)
        {
            PhysicsBuildTask buildTask = (PhysicsBuildTask)aBuildTask;

            int gameObjectIndex = 0;

            try
            {
                if (buildTask.physicsAggregatedList != null)
                {
                    while (buildTask.physicsAggregatedList.Count > 1)
                    {
                        int            smallestIndex = 0;
                        VoxelContainer newContainer  = buildTask.voxelContainerList[gameObjectIndex];
                        newContainer.AssignUVDictionary(this.container);
                        foreach (Voxel curVoxel in buildTask.physicsAggregatedList[smallestIndex])
                        {
                            newContainer.AddVoxel(curVoxel, true);
                            lock (this.container.voxels)
                            {
                                this.container.RemoveVoxel(curVoxel, true);
                            }
                        }


                        Texture2D curTexture       = null;
                        int       curTextureWidth  = 0;
                        int       curTextureHeight = 0;
                        foreach (VoxelArea curArea in this.container.voxelAreas.Values)
                        {
                            curTexture       = curArea.GetTexture();
                            curTextureWidth  = curArea.GetTextureWidth();
                            curTextureHeight = curArea.GetTextureHeight();
                            if (curTexture != null)
                            {
                                break;
                            }
                        }

                        foreach (VoxelArea curArea in newContainer.voxelAreas.Values)
                        {
                            curArea.SetTexture(curTexture, curTextureWidth, curTextureHeight);
                        }

                        foreach (VoxelArea curArea in newContainer.voxelAreas.Values)
                        {
                            curArea.SetTexture(curTexture, curTextureWidth, curTextureHeight);
                        }

                        newContainer.GenerateAreaBuffers();

                        newContainer.rebuildCollider = false;
                        List <VoxelContainer.ColliderDescriptor> colliders = newContainer.PrepareColliderDescriptors();
                        buildTask.colliders.Add(colliders);

                        gameObjectIndex++;
                        buildTask.physicsAggregatedList.RemoveAt(smallestIndex);
                    }
                    buildTask.mainBodyCollider = this.container.PrepareColliderDescriptors();
                    lock (this.container.voxels)
                    {
                        this.container.rebuildCollider = false;
                        this.container.GenerateAreaBuffers();
                        this.container.mustRebuildBeforeUpdate = false;
                        this.container.ingameBuildTask         = null;
                    }

                    this.currentState = PhysicsState.Finalisation;
                    buildTask.isReady = true;
                }
            }
            catch (Exception e)
            {
                Debug.LogError("VoxelPhysics error: " + e.Message);
            }
        }
        private void ExportObjectToQBFile(string aFilename)
        {
            List <VoxelContainer> containers    = new List <VoxelContainer>();
            VoxelContainer        rootContainer = this.voxelObject.GetComponent <VoxelContainer>();

            if (this.exportChildObjects)
            {
                containers.AddRange(this.voxelObject.transform.GetComponentsInChildren <VoxelContainer>());
            }
            else
            {
                if (rootContainer != null)
                {
                    containers.Add(rootContainer);
                }
            }

            if (containers.Count == 0)
            {
                Debug.LogError("QB Export: Did not found voxelContainer in the structure! Please make sure you selected an object with voxelcontainer");
                return;
            }

            if (Path.GetExtension(aFilename).ToUpper() != ".qb".ToUpper())
            {
                Debug.LogError("Extension must be .qb");
                return;
            }

            BinaryWriter bw = new BinaryWriter(File.OpenWrite(aFilename));

            try
            {
                //Header
                uint version = 257;
                bw.Write(version);
                uint colorFormat = 0;//RGBA
                bw.Write(colorFormat);
                uint zAxisOrientation = 0;
                bw.Write(zAxisOrientation);
                uint compression = 0;    //Not compressed
                bw.Write(compression);
                uint visibilityMask = 0; //Not encoded
                bw.Write(visibilityMask);
                uint matrixNumber = (uint)containers.Count;
                bw.Write(matrixNumber);


                for (int i = 0; i < matrixNumber; i++)
                {
                    VoxelContainer curContainer = containers[i];
                    //Data
                    string matrixName = curContainer.name;
                    byte   nameLength = (byte)matrixName.Length;
                    bw.Write(nameLength);
                    char[] charArrayOfName = matrixName.ToCharArray();
                    bw.Write(charArrayOfName);

                    Vector3 minVector = curContainer.GetMinContainerVector();
                    Vector3 maxVector = curContainer.GetMaxContainerVector();

                    uint sizeX = (uint)(maxVector.x - minVector.x + 1);
                    uint sizeY = (uint)(maxVector.y - minVector.y + 1);
                    uint sizeZ = (uint)(maxVector.z - minVector.z + 1);

                    bw.Write(sizeX);
                    bw.Write(sizeY);
                    bw.Write(sizeZ);

                    //
                    int posx = (int)(curContainer.transform.position.x + minVector.x);
                    int posy = (int)(curContainer.transform.position.y + minVector.y);
                    int posz = (int)(curContainer.transform.position.z + minVector.z);

                    bw.Write(posx);
                    bw.Write(posy);
                    bw.Write(posz);

                    for (int z = (int)minVector.z; z <= maxVector.z; z++)
                    {
                        for (int y = (int)minVector.y; y <= maxVector.y; y++)
                        {
                            for (int x = (int)minVector.x; x <= maxVector.x; x++)
                            {
                                Vector3 curPosition = new Vector3(x, y, z);
                                if (curContainer.voxels.ContainsKey(curPosition))
                                {
                                    uint voxelColor = this.ColorToUInt(curContainer.voxels[curPosition].color);
                                    bw.Write(voxelColor);
                                }
                                else
                                {
                                    uint noVoxel = 0;
                                    bw.Write(noVoxel);
                                }
                            }
                        }
                    }
                }
                Debug.Log("Export Finished");
            }finally
            {
                bw.Flush();
                bw.Close();
            }
        }
Beispiel #32
0
 public void SetContainer(VoxelContainer aVoxelContainer)
 {
     this.voxelContainer = aVoxelContainer;
     this.selectionList  = null;
 }