Combine() public static method

Combine the given mesh instances into a single mesh and return it.
public static Combine ( IEnumerable instances, bool generateStrips ) : Mesh
instances IEnumerable The mesh instances to combine.
generateStrips bool true to use triangle strips, false to use triangle lists.
return Mesh
    void CombineMeshes()
    {
        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            GameObject go = new GameObject("Combined mesh ");
            go.transform.parent        = parent_go.transform;
            go.transform.localScale    = Vector3.one;
            go.transform.localRotation = Quaternion.identity;
            go.transform.localPosition = Vector3.zero;
            go.AddComponent(typeof(MeshFilter));
            go.AddComponent("MeshRenderer");
            go.renderer.sharedMaterial = (Material)de.Key;
            if (go.renderer.sharedMaterial == null || go.renderer.sharedMaterial.name == null)
            {
                DestroyImmediate(go);
                continue;
            }
            go.name += " - " + go.renderer.sharedMaterial.name;

            MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));

            Vector3 centroid = GetAveragePosition(instances);
            go.transform.position = centroid;
            for (int i = 0; i < instances.Length; i++)
            {
                instances[i].transform = go.transform.worldToLocalMatrix * ((Transform)instanceToPosition[instances[i]]).localToWorldMatrix;
            }

            filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
        }
    }
Esempio n. 2
0
    void CombineAllInBounds(Bounds bounds, List <MeshRenderer> validRenderers)
    {
        List <MeshRenderer> renderersForThisCell = new List <MeshRenderer>();

        for (int i = validRenderers.Count - 1; i >= 0; i--)
        {
            MeshRenderer m = validRenderers[i];
            if (bounds.Intersects(m.bounds))
            {
                renderersForThisCell.Add(m);
                validRenderers.Remove(m);
            }
        }

        if (renderersForThisCell.Count > 0)
        {
            MeshCombineUtility.Combine(renderersForThisCell, MeshCombineUtility.RendererDisposeMethod.DestroyRendererAndFilter, "Level_Combined");
        }
    }
Esempio n. 3
0
    public void Combine()
    {
        List <MeshRenderer> validRenderers = new List <MeshRenderer>();

        foreach (GameObject combineParent in combineParents)
        {
            validRenderers.AddRange(combineParent.GetComponentsInChildren <MeshRenderer>());
        }

        if (useGrid)
        {
            for (int i = 0; i < GetGridCellCount(); i++)
            {
                if (GetGridCellBounds(i, out Bounds bounds))
                {
                    CombineAllInBounds(bounds, validRenderers);
                }
            }
        }
        else
        {
            MeshCombineUtility.Combine(validRenderers, MeshCombineUtility.RendererDisposeMethod.DestroyRendererAndFilter, "Level_Combined");
        }
    }
    private void Start()
    {
        Component[] componentsInChildren = base.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   worldToLocalMatrix   = base.get_transform().get_worldToLocalMatrix();
        Hashtable   hashtable            = new Hashtable();

        for (int i = 0; i < componentsInChildren.Length; i++)
        {
            MeshFilter meshFilter = (MeshFilter)componentsInChildren[i];
            Renderer   renderer   = componentsInChildren[i].get_renderer();
            MeshCombineUtility.MeshInstance meshInstance = default(MeshCombineUtility.MeshInstance);
            meshInstance.mesh = meshFilter.get_sharedMesh();
            if (renderer != null && renderer.get_enabled() && meshInstance.mesh != null)
            {
                meshInstance.transform = worldToLocalMatrix * meshFilter.get_transform().get_localToWorldMatrix();
                Material[] sharedMaterials = renderer.get_sharedMaterials();
                for (int j = 0; j < sharedMaterials.Length; j++)
                {
                    meshInstance.subMeshIndex = Math.Min(j, meshInstance.mesh.get_subMeshCount() - 1);
                    ArrayList arrayList = (ArrayList)hashtable.get_Item(sharedMaterials[j]);
                    if (arrayList != null)
                    {
                        arrayList.Add(meshInstance);
                    }
                    else
                    {
                        arrayList = new ArrayList();
                        arrayList.Add(meshInstance);
                        hashtable.Add(sharedMaterials[j], arrayList);
                    }
                }
                renderer.set_enabled(false);
            }
        }
        using (IDictionaryEnumerator enumerator = hashtable.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                DictionaryEntry dictionaryEntry            = (DictionaryEntry)enumerator.get_Current();
                ArrayList       arrayList2                 = (ArrayList)dictionaryEntry.get_Value();
                MeshCombineUtility.MeshInstance[] combines = (MeshCombineUtility.MeshInstance[])arrayList2.ToArray(typeof(MeshCombineUtility.MeshInstance));
                if (hashtable.get_Count() == 1)
                {
                    if (base.GetComponent(typeof(MeshFilter)) == null)
                    {
                        base.get_gameObject().AddComponent(typeof(MeshFilter));
                    }
                    if (!base.GetComponent("MeshRenderer"))
                    {
                        base.get_gameObject().AddComponent("MeshRenderer");
                    }
                    MeshFilter meshFilter2 = (MeshFilter)base.GetComponent(typeof(MeshFilter));
                    meshFilter2.set_mesh(MeshCombineUtility.Combine(combines, this.generateTriangleStrips));
                    base.get_renderer().set_material((Material)dictionaryEntry.get_Key());
                    base.get_renderer().set_enabled(true);
                }
                else
                {
                    GameObject gameObject = new GameObject("Combined mesh");
                    gameObject.get_transform().set_parent(base.get_transform());
                    gameObject.get_transform().set_localScale(Vector3.get_one());
                    gameObject.get_transform().set_localRotation(Quaternion.get_identity());
                    gameObject.get_transform().set_localPosition(Vector3.get_zero());
                    gameObject.AddComponent(typeof(MeshFilter));
                    gameObject.AddComponent("MeshRenderer");
                    gameObject.get_renderer().set_material((Material)dictionaryEntry.get_Key());
                    MeshFilter meshFilter3 = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
                    meshFilter3.set_mesh(MeshCombineUtility.Combine(combines, this.generateTriangleStrips));
                }
            }
        }
    }
    public IEnumerator _Batch(bool AddMeshColliders = false, bool RemoveLeftOvers = false, bool isItPatternExport = false, bool isPrepareForLightmapping = false)
    {
        for (int i = 0; i < BatchedObjects.Count; i++)
        {
            Destroy(BatchedObjects[i]);
        }

        BatchedObjects.Clear();

        Component[]      filters        = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4        myTransform    = transform.worldToLocalMatrix;
        List <Hashtable> materialToMesh = new List <Hashtable>();
        int vertexCalc    = 0;
        int hasIterations = 0;

        materialToMesh.Add(new Hashtable());

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;

            if (!instance.mesh)
            {
                continue;
            }

            vertexCalc += instance.mesh.vertexCount;

            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[hasIterations][materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh[hasIterations].Add(materials[m], objects);
                    }

                    if (vertexCalc > optLevel)
                    {
                        vertexCalc = 0;
                        hasIterations++;
                        materialToMesh.Add(new Hashtable());
                    }
                }

                if (!RemoveLeftOvers)
                {
                    curRenderer.enabled = false;
                }
            }
        }

        int counter = 0;

        for (int i = 0; i < hasIterations + 1; i++)
        {
            foreach (DictionaryEntry de  in materialToMesh[i])
            {
                                #if UNITY_EDITOR
                if (EditorApplication.isPlaying)
                {
                                #endif
                yield return(0);

                                #if UNITY_EDITOR
            }
                                #endif

                ArrayList elements = (ArrayList)de.Value;
                MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

                GameObject go = new GameObject("uteTagID_1555");
                BatchedObjects.Add(go);
                go.transform.parent        = transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");
                go.isStatic          = true;
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);

                if (isPrepareForLightmapping)
                {
                                        #if UNITY_EDITOR
                                                #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5
                    Unwrapping.GeneratePerTriangleUV(filter.mesh);
                                                #endif
                    Unwrapping.GenerateSecondaryUVSet(filter.mesh);
                                        #endif
                }

                if (AddMeshColliders)
                {
                                        #if UNITY_EDITOR
                    if (EditorApplication.isPlaying)
                    {
                                        #endif
                    yield return(0);

                                        #if UNITY_EDITOR
                }
                                        #endif

                    go.AddComponent <MeshCollider>();
                }
            }
        }

        if (RemoveLeftOvers)
        {
            List <GameObject> children = new List <GameObject>();
            int counterpp = 0;
            foreach (Transform child in transform)
            {
                children.Add(child.gameObject);
            }

                        #if UNITY_EDITOR
            if (EditorApplication.isPlaying)
            {
                        #endif
            for (int s = 0; s < children.Count; s++)
            {
                if (children[s].name != "uteTagID_1555")
                {
                                                #if UNITY_EDITOR
                    if (EditorApplication.isPlaying)
                    {
                        if (s % 1000 == 0)
                        {
                            yield return(0);
                        }
                                                #endif
                    Destroy(children[s]);
                                                #if UNITY_EDITOR
                }
                                                #endif
                }
                else
                {
                    children[s].name = "Batch_" + (counterpp++).ToString();
                }
            }
                        #if UNITY_EDITOR
        }
        else
        {
            for (int s = 0; s < children.Count; s++)
            {
                if (children[s].name != ("uteTagID_1555"))
                {
                    DestroyImmediate(children[s], true);
                }
                else
                {
                    children[s].name = "Batch_" + (counterpp++).ToString();
                }
            }
        }
                        #endif
        }

        yield return(0);
    }
    void Start()
    {
        filters = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4 myTransform = transform.worldToLocalMatrix;

        instance = new MeshCombineUtility.MeshInstance[filters.Length];
        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].GetComponent <Renderer>();
            instance[i]          = new MeshCombineUtility.MeshInstance();
            instance[i].mesh     = filter.sharedMesh;
            instance[i].childIdx = i;
            if (curRenderer != null && curRenderer.enabled && instance[i].mesh != null)
            {
                instance[i].transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance[i].subMeshIndex = System.Math.Min(m, instance[i].mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance[i]);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance[i]);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                curRenderer.enabled = false;
            }
        }

        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (GetComponent(typeof(MeshFilter)) == null)
                {
                    gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!GetComponent("MeshRenderer"))
                {
                    gameObject.AddComponent <MeshRenderer>();
                }

                MeshFilter filter = (MeshFilter)GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.CombineFirst(instances, generateTriangleStrips, ref element);
                GetComponent <Renderer>().material = (Material)de.Key;
                GetComponent <Renderer>().enabled  = true;
                mf = filter;
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                GameObject combinedMesh = new GameObject("Combined mesh");
                combinedMesh.transform.parent        = transform;
                combinedMesh.transform.localScale    = Vector3.one;
                combinedMesh.transform.localRotation = Quaternion.identity;
                combinedMesh.transform.localPosition = Vector3.zero;
                combinedMesh.AddComponent(typeof(MeshFilter));
                combinedMesh.AddComponent <MeshRenderer>();
                combinedMesh.GetComponent <Renderer>().material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)combinedMesh.GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
            }
        }
    }
Esempio n. 7
0
    public static void Combine(SimpleMeshCombine target)
    {
        MeshFilter[] meshFilters = FindEnabledMeshes(target.transform);

        if (meshFilters.Length > 0)
        {
            GameObject combinedFrags = new GameObject();
            combinedFrags.AddComponent <MeshFilter>();
            combinedFrags.AddComponent <MeshRenderer>();
            MeshInstance[] instances   = new MeshInstance[meshFilters.Length];
            GameObject[]   combinedGOs = new GameObject[meshFilters.Length];
            MeshFilter     matFilter   = null;

            for (int i = 0; i < meshFilters.Length; i++)
            {
                MeshFilter mf = meshFilters[i];
                if (i == meshFilters.Length - 1)
                {
                    matFilter = mf;
                }
                combinedGOs[i] = mf.gameObject;
                MeshInstance mi = new MeshInstance();
                mi.mesh = mf.sharedMesh;
                // D.Log(mi.mesh.vertices.Length);
                // mi.subMeshIndex = mf.sharedMesh.subMeshCount;
                mi.subMeshIndex = 0;
                mi.transform    = mf.transform.localToWorldMatrix;
                instances[i]    = mi;
            }

            target.combinedGameObjects = combinedGOs;
            Mesh m = MeshCombineUtility.Combine(instances, false);

            // D.Log(target.transform.name+
            //       " Combined " + meshFilters.Length + " Meshes");
            // D.Warn("Mesh: " + m.vertices.Length);

            // CombineInstance[] combine = new CombineInstance[meshFilters.Length];
            // GameObject[] mfGOs = new GameObject[meshFilters.Length];
            // for (int i=0; i<meshFilters.Length; i++) {
            //     MeshFilter mf = meshFilters[i];
            //     MeshRenderer mr = combinedFrags.GetComponent<MeshRenderer>();
            //     mr.sharedMaterial = mf.transform.GetComponent<MeshRenderer>().sharedMaterial;
            //     mfGOs[i] = meshFilters[i].gameObject;
            //     CombineInstance ci = combine[i];
            //     ci.mesh = mf.transform.GetComponent<MeshFilter>().sharedMesh;
            //     ci.transform = mf.transform.localToWorldMatrix;
            //     combine[i] = ci;
            // }

            combinedFrags.GetComponent <MeshFilter>().mesh             = m;
            combinedFrags.GetComponent <MeshRenderer>().sharedMaterial = matFilter.GetComponent <Renderer>().sharedMaterial;
            // combinedFrags.GetComponent<MeshFilter>().mesh = new Mesh();
            // combinedFrags.GetComponent<MeshFilter>().sharedMesh.CombineMeshes(combine);

            // // Disabled for now
            // // if (target._generateLightmapUV){
            // //     Unwrapping.GenerateSecondaryUVSet(combinedFrags.GetComponent(MeshFilter).sharedMesh);
            // //     combinedFrags.isStatic = true;
            // // }

            combinedFrags.name             = "_Combined Mesh [" + target.transform.name + "]";
            target.combined                = combinedFrags.gameObject;
            combinedFrags.transform.parent = target.transform;
            EnableRenderers(meshFilters, false);
        }
    }
Esempio n. 8
0
    /// <summary>
    /// Combines selected gameobjects that have meshfilters to the lowest possible meshcount.
    /// </summary>
    private void Combine()
    {
        GameObject GO_Parent = Selection.gameObjects[0];

        GameObject[] oldGameObjects = Selection.gameObjects;
        Vector3      oldPosition    = new Vector3(GO_Parent.transform.position.x, GO_Parent.transform.position.y, GO_Parent.transform.position.z);

        //		oldPositions.Clear();
        //		oldRotations.Clear();
        //		oldPositions = StoreOriginalPositions(oldGameObjects);
        //		oldRotations = StoreOriginalQuaternions(oldGameObjects);

        Component[] filters        = GetMeshFilters();
        Matrix4x4   myTransform    = GO_Parent.transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].GetComponent <Renderer>();
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }
            }
        }

        int nameCount = 1; //used for multimesh naming.

        //for each material found
        foreach (DictionaryEntry de in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            GameObject go = new GameObject("Combined Mesh");
            if (keepLayer)
            {
                go.layer = GO_Parent.layer;
            }
            // transforms should be zeroed out, then reset when we place the new object em.
            go.transform.localScale    = Vector3.one;
            go.transform.localRotation = GO_Parent.transform.localRotation;
            go.transform.localPosition = Vector3.zero;
            go.transform.position      = Vector3.zero;
            go.AddComponent(typeof(MeshFilter));
            go.AddComponent <MeshRenderer>();
            go.GetComponent <Renderer>().material = (Material)de.Key;
            MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
            filter.sharedMesh = MeshCombineUtility.Combine(instances, false);
            filter.GetComponent <Renderer>().receiveShadows = receiveShadows;
            filter.GetComponent <Renderer>().castShadows    = castShadows;
            go.isStatic = isStatic;
            if (isLightmapped)
            {
                Unwrapping.GenerateSecondaryUVSet(filter.sharedMesh);
            }
            if (addMeshCollider)
            {
                go.AddComponent <MeshCollider>();
            }
            //add the new object to our list.
            newObjects.Add(go);
        }


        if (destroyAfterOptimized)
        {
            for (int x = 0; x < oldGameObjects.Length; x++)
            {
                DestroyImmediate(oldGameObjects[x]);
            }
        }

        //if we found unique materials, make sure we name the GO's properly.
        if (newObjects.Count > 1)
        {
            for (int x = 0; x < newObjects.Count; x++)
            {
                if (x > 0)
                {
                    newObjects[x].name = newName + nameCount;
                }
                else
                {
                    newObjects[0].name = newName;
                }
                nameCount++;
                newObjects[x].transform.position = oldPosition;
            }
        }
        else
        {
            newObjects[0].name = newName;
            newObjects[0].transform.position = oldPosition;
        }

        if (createParentGO)
        {
            GameObject p = new GameObject(newName);
            p.transform.position = oldPosition;
            foreach (GameObject g in newObjects)
            {
                g.transform.parent = p.transform;
            }
        }
    }
Esempio n. 9
0
    public static void Combine(GameObject g)
    {
        Component[] filters        = g.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = g.transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        foreach (Component t in filters)
        {
            MeshFilter filter      = (MeshFilter)t;
            Renderer   curRenderer = t.renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList {
                            instance
                        };
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                curRenderer.enabled = false;
            }
        }

        foreach (DictionaryEntry de in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (g.GetComponent(typeof(MeshFilter)) == null)
                {
                    g.gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!g.GetComponent("MeshRenderer"))
                {
                    g.gameObject.AddComponent("MeshRenderer");
                }

                MeshFilter filter = (MeshFilter)g.GetComponent(typeof(MeshFilter));
                filter.mesh         = MeshCombineUtility.Combine(instances, true);
                g.renderer.material = (Material)de.Key;
                g.renderer.enabled  = true;
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                GameObject go = new GameObject("Combined mesh");
                go.transform.parent        = g.transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.Combine(instances, true);
            }
        }
    }
Esempio n. 10
0
    void ReCombineSkinnedMeshes()
    {
        VERTEX_NUMBER = 0;
        BONE_NUMBER   = 0;
        Component[] allsmr = GetComponentsInChildren(typeof(SkinnedMeshRenderer));

        for (int i = 0; i < allsmr.Length; ++i)
        {
            if (allsmr[i].name == name || ((SkinnedMeshRenderer)allsmr[i]).sharedMesh == null)
            {
                continue;
            }

            VERTEX_NUMBER += ((SkinnedMeshRenderer)allsmr[i]).sharedMesh.vertices.Length;
            BONE_NUMBER   += ((SkinnedMeshRenderer)allsmr[i]).bones.Length;
        }
        Matrix4x4 myTransform    = transform.worldToLocalMatrix;
        Hashtable materialToMesh = new Hashtable();

        Hashtable boneHash = new Hashtable();

        Transform[] totalBones = new Transform[BONE_NUMBER];

        Matrix4x4[] totalBindPoses = new Matrix4x4[BONE_NUMBER];

        BoneWeight[] totalBoneWeight = new BoneWeight[VERTEX_NUMBER];


        int offset   = 0;
        int b_offset = 0;

        Transform[] usedBones = new Transform[totalBones.Length];


        for (int i = 0; i < allsmr.Length; i++)
        {
            if (allsmr[i].name == name || ((SkinnedMeshRenderer)allsmr[i]).sharedMesh == null)
            {
                continue;
            }

            SkinnedMeshRenderer smrenderer = (SkinnedMeshRenderer)allsmr[i];

            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();

            instance.mesh = smrenderer.sharedMesh;

            if (smrenderer != null && smrenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * smrenderer.transform.localToWorldMatrix;


                Material[] materials = smrenderer.sharedMaterials;

                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                for (int x = 0; x < smrenderer.bones.Length; x++)
                {
                    bool flag = false;
                    for (int j = 0; j < totalBones.Length; j++)
                    {
                        if (usedBones[j] != null)
                        {
                            if ((smrenderer.bones[x] == usedBones[j]))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }

                    if (!flag)
                    {
                        for (int f = 0; f < totalBones.Length; f++)
                        {
                            if (usedBones[f] == null)
                            {
                                usedBones[f] = smrenderer.bones[x];
                                break;
                            }
                        }
                        totalBones[offset] = smrenderer.bones[x];
                        boneHash.Add(smrenderer.bones[x].name, offset);

                        totalBindPoses[offset] = smrenderer.bones[x].worldToLocalMatrix * transform.localToWorldMatrix;

                        offset++;
                    }
                }

                for (int x = 0; x < smrenderer.sharedMesh.boneWeights.Length; x++)
                {
                    totalBoneWeight[b_offset] = recalculateIndexes(smrenderer.sharedMesh.boneWeights[x], boneHash, smrenderer.bones);
                    b_offset++;
                }

                ((SkinnedMeshRenderer)allsmr[i]).enabled = false;
            }
        }
        foreach (DictionaryEntry de in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            //int i = 0;

            //foreach (var item in instances)
            //{
            //    Mogo.Util.LoggerHelper.Debug(item.mesh.name + " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            //    Mesh mesh = Resources.Load(item.mesh.name) as Mesh;
            //    instances[i++].mesh = mesh;
            //}

            if (materialToMesh.Count == 1)
            {
                if (GetComponent(typeof(SkinnedMeshRenderer)) == null)
                {
                    gameObject.AddComponent <SkinnedMeshRenderer>();
                }

                SkinnedMeshRenderer objRenderer = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
                objRenderer.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                objRenderer.material   = (Material)de.Key;

                objRenderer.castShadows    = castShadows;
                objRenderer.receiveShadows = receiveShadows;

                objRenderer.sharedMesh.bindposes = totalBindPoses;

                objRenderer.sharedMesh.boneWeights = totalBoneWeight;


                objRenderer.bones = totalBones;

                objRenderer.sharedMesh.RecalculateNormals();
                objRenderer.sharedMesh.RecalculateBounds();

                objRenderer.enabled = true;
            }
            else
            {
                Mogo.Util.LoggerHelper.Debug("More Than One Material !!!!!! " + materialToMesh.Count);
                //GameObject go = new GameObject("CombinedSkinnedMesh");
                //go.transform.parent = transform;
                //go.transform.localScale = Vector3.one;
                //go.transform.localRotation = Quaternion.identity;
                //go.transform.localPosition = Vector3.zero;
                //go.AddComponent(typeof(SkinnedMeshRenderer));
                //((SkinnedMeshRenderer)go.GetComponent(typeof(SkinnedMeshRenderer))).material = (Material)de.Key;

                //SkinnedMeshRenderer objRenderer = (SkinnedMeshRenderer)go.GetComponent(typeof(SkinnedMeshRenderer));
                //objRenderer.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);

                //objRenderer.sharedMesh.bindposes = totalBindPoses;

                //objRenderer.sharedMesh.boneWeights = totalBoneWeight;

                //objRenderer.bones = totalBones;

                //objRenderer.sharedMesh.RecalculateNormals();
                //objRenderer.sharedMesh.RecalculateBounds();

                //objRenderer.enabled = true;
            }
        }
    }
    GameObject combineMesh(bool exportAssets, bool genCollider = true, bool doSetParent = true, bool doSetLayer = true, bool doSetTag = true)
    {
//		GameObject returnObject = new GameObject(m_parentObject.name);
//		returnObject.transform.position = m_parentObject.transform.position;
//		returnObject.transform.rotation = m_parentObject.transform.rotation;


        MeshFilter[] filters     = m_parentObject.GetComponentsInChildren <MeshFilter>();
        Matrix4x4    myTransform = m_parentObject.transform.worldToLocalMatrix;

        this.checkAndCreateFolder();

        Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > allMeshesAndMaterials = new Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > >();

        for (int i = 0; i < filters.Length; i++)
        {
            Renderer curRenderer = filters[i].GetComponent <Renderer>();
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();

            instance.mesh = filters[i].sharedMesh;

            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filters[i].transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    if (!allMeshesAndMaterials.ContainsKey(materials[m].shader.ToString()))
                    {
                        allMeshesAndMaterials.Add(materials[m].shader.ToString(), new Dictionary <Material, List <MeshCombineUtility.MeshInstance> >());
                    }

                    if (!allMeshesAndMaterials[materials[m].shader.ToString()].ContainsKey(materials[m]))
                    {
                        allMeshesAndMaterials[materials[m].shader.ToString()].Add(materials[m], new List <MeshCombineUtility.MeshInstance>());
                    }

                    allMeshesAndMaterials[materials[m].shader.ToString()][materials[m]].Add(instance);
                }
            }
        }

        foreach (KeyValuePair <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > firstPass in allMeshesAndMaterials)
        {
            Material[] allMaterialTextures = new Material[firstPass.Value.Keys.Count];
            int        index = 0;

            foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
            {
                allMaterialTextures[index] = kv.Key;
                index++;
            }

            TextureCombineUtility.TexturePosition[] textureUVPositions;
            Material combined = TextureCombineUtility.combine(allMaterialTextures, out textureUVPositions, m_textureAtlasInfo);
            List <MeshCombineUtility.MeshInstance> meshes = new List <MeshCombineUtility.MeshInstance>();

            foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
            {
                List <MeshCombineUtility.MeshInstance> meshIntermediates = new List <MeshCombineUtility.MeshInstance>();
                Mesh[] firstCombineStep = MeshCombineUtility.Combine(kv.Value.ToArray());

                for (int i = 0; i < firstCombineStep.Length; i++)
                {
                    MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
                    instance.mesh         = firstCombineStep[i];
                    instance.subMeshIndex = 0;
                    instance.transform    = Matrix4x4.identity;
                    meshIntermediates.Add(instance);
                }
                if (textureUVPositions != null)
                {
                    TextureCombineUtility.TexturePosition refTexture = textureUVPositions[0];

                    for (int j = 0; j < textureUVPositions.Length; j++)
                    {
                        if (kv.Key.mainTexture.name == textureUVPositions[j].textures[0].name)
                        {
                            refTexture = textureUVPositions[j];
                            break;
                        }
                    }


                    for (int j = 0; j < meshIntermediates.Count; j++)
                    {
                        Vector2[] uvCopy = meshIntermediates[j].mesh.uv;
                        for (int k = 0; k < uvCopy.Length; k++)
                        {
                            uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                            uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                        }

                        meshIntermediates[j].mesh.uv = uvCopy;

                        uvCopy = meshIntermediates[j].mesh.uv2;
                        for (int k = 0; k < uvCopy.Length; k++)
                        {
                            uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                            uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                        }

                        meshIntermediates[j].mesh.uv2 = uvCopy;

                        uvCopy = meshIntermediates[j].mesh.uv2;
                        for (int k = 0; k < uvCopy.Length; k++)
                        {
                            uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                            uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                        }

                        meshIntermediates[j].mesh.uv2 = uvCopy;

                        meshes.Add(meshIntermediates[j]);
                    }
                }
            }

            Material mat = combined;

            if (exportAssets)            //combined exportMaterial and combined Textures
            {
                checkAndCreateFolder();

                Debug.Log((mat.mainTexture as Texture2D).format);
                if ((mat.mainTexture as Texture2D).format != TextureFormat.ARGB32 &&
                    (mat.mainTexture as Texture2D).format != TextureFormat.RGB24 &&
                    (mat.mainTexture as Texture2D).format != TextureFormat.RGBA32)
                {
                    Debug.LogError("Textures assigned to objects must be either RGBA32 or RGB 24 to be exported");
                    return(null);
                }

                byte[] textureByte   = (mat.mainTexture as Texture2D).EncodeToPNG();
                string texturefolder = m_pathToAssets.Substring(m_pathToAssets.LastIndexOf("Assets/")) + "Textures/";
                checkAndCreateFolder(texturefolder);
                System.IO.File.WriteAllBytes(texturefolder + m_parentObject.name + ".png", textureByte);
                Material outMat         = new Material(mat);
                string   materialfolder = m_pathToAssets.Substring(m_pathToAssets.LastIndexOf("Assets/")) + "Materials/";
                checkAndCreateFolder(materialfolder);
                string assetPathFile = materialfolder + m_parentObject.name + ".mat";
                AssetDatabase.CreateAsset(outMat, assetPathFile);
                outMat.CopyPropertiesFromMaterial(mat);
                outMat.mainTexture = AssetDatabase.LoadAssetAtPath(texturefolder + m_parentObject.name + ".png", typeof(Texture)) as Texture;
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                mat = outMat;
            }

            Mesh[] combinedMeshes = MeshCombineUtility.Combine(meshes.ToArray());

            GameObject parent = new GameObject(m_parentObject.name + "_Combined " + firstPass.Key + " Mesh Parent");
            parent.transform.position = m_parentObject.transform.position;
            parent.transform.rotation = m_parentObject.transform.rotation;
            parent.transform.parent   = m_parentObject.transform;

            if (doSetLayer)
            {
                parent.layer = m_parentObject.layer;
            }

            if (doSetTag)
            {
                parent.tag = m_parentObject.tag;
            }

            if (doSetParent)
            {
                parent.transform.parent = m_parentObject.transform.parent;
            }

            parent.isStatic = m_parentObject.isStatic;

            for (int i = 0; i < combinedMeshes.Length; i++)
            {
                GameObject go = new GameObject(m_parentObject.name + "_Combined_Meshs");
                go.transform.parent = parent.transform;
                go.tag   = m_parentObject.tag;
                go.layer = m_parentObject.layer;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                MeshFilter filter = go.AddComponent <MeshFilter>();
                go.AddComponent <MeshRenderer>();
                go.GetComponent <Renderer>().sharedMaterial = mat;

                filter.mesh = combinedMeshes[i];

                if (exportAssets == true)
                {
                    exportMeshFilter(filter, m_parentObject.name + i);
//					exportMesh(combinedMeshes[i], m_parentObject.name + i,mat);
                }
                if (genCollider)
                {
                    if (go.GetComponent <MeshCollider>() == null)
                    {
                        go.gameObject.AddComponent <MeshCollider>();
                    }
                }

                if (doSetLayer)
                {
                    go.layer = m_parentObject.layer;
                }

                if (doSetTag)
                {
                    go.tag = m_parentObject.tag;
                }

                go.isStatic = m_parentObject.isStatic;
            }
        }

        //if(developmentBake == true)
        //{
        foreach (Renderer r in m_parentObject.GetComponentsInChildren <Renderer>())
        {
            r.enabled = false;
        }
        //}

        return(m_parentObject);
    }
    static void Merge(GameObject target)
    {
        Component[] filters        = target.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = target.transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        Dictionary <Material, MapTextureChangeData> mcd = new Dictionary <Material, MapTextureChangeData>();

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;

            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;

                MapTextureChangeObject o = curRenderer.gameObject.GetComponent <MapTextureChangeObject>();

                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];

                    if (objects != null)
                    {
                        objects.Add(instance);

                        if (o != null && mcd.ContainsKey(materials[m]) == false)
                        {
                            MapTextureChangeData d = new MapTextureChangeData();
                            d.effectMat   = o.effect;
                            d.originalMat = o.original;
                            d.type        = o.type;

                            mcd.Add(materials[m], d);
                        }
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);

                        if (o != null && mcd.ContainsKey(materials[m]) == false)
                        {
                            MapTextureChangeData d = new MapTextureChangeData();
                            d.effectMat   = o.effect;
                            d.originalMat = o.original;
                            d.type        = o.type;

                            mcd.Add(materials[m], d);
                        }
                    }
                }


                if (Application.isPlaying && destroyAfterOptimized && combineOnStart)
                {
                    GameObject.Destroy(curRenderer.gameObject);
                }
                else if (destroyAfterOptimized)
                {
                    GameObject.DestroyImmediate(curRenderer.gameObject);
                }
                else
                {
                    curRenderer.enabled = false;
                }
            }
        }

        int randomIndex = 0;

        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (target.GetComponent(typeof(MeshFilter)) == null)
                {
                    target.gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!target.GetComponent("MeshRenderer"))
                {
                    target.gameObject.AddComponent("MeshRenderer");
                }


                Material   mat    = (Material)de.Key;
                MeshFilter filter = (MeshFilter)target.GetComponent(typeof(MeshFilter));

                filter.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips, checkSubUVByMaterialName && checkHasSecondUV(mat.shader.name.ToLower()));

                target.renderer.material = mat;
                target.renderer.enabled  = true;
                if (addMeshCollider)
                {
                    target.gameObject.AddComponent <MeshCollider>();
                }
                target.renderer.castShadows    = false;
                target.renderer.receiveShadows = false;

                if (mcd.ContainsKey(mat))
                {
                    MapTextureChangeObject mco = target.AddComponent <MapTextureChangeObject>();
                    mco.effect   = mcd[mat].effectMat;
                    mco.original = mcd[mat].originalMat;
                    mco.type     = mcd[mat].type;
                }
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                string n = "";

                n = de.Key.ToString();
                n = n.Substring(0, n.LastIndexOf("(") - 1);

                GameObject go = new GameObject("Combined mesh " + n);
                if (keepLayer)
                {
                    go.layer = target.gameObject.layer;
                }
                go.transform.parent        = target.transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");

                Material mat = (Material)de.Key;

                if (mcd.ContainsKey(mat))
                {
                    MapTextureChangeObject mco = go.AddComponent <MapTextureChangeObject>();
                    mco.effect   = mcd[mat].effectMat;
                    mco.original = mcd[mat].originalMat;
                    mco.type     = mcd[mat].type;
                }

                go.renderer.material = mat;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));

                if (Application.isPlaying)
                {
                    filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips, (checkSubUVByMaterialName && checkHasSecondUV(mat.shader.name.ToLower()) == false)?false:true);
                }
                else
                {
                    filter.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips, checkSubUVByMaterialName && checkHasSecondUV(mat.shader.name.ToLower()));
                }
                go.renderer.castShadows    = false;
                go.renderer.receiveShadows = false;
                if (addMeshCollider)
                {
                    go.AddComponent <MeshCollider>();
                }

                                #if UNITY_EDITOR
                if (Application.isPlaying == false)
                {
                    GameObject tg = target.gameObject;

                    string name     = tg.name;
                    string rootName = "";

                    while (tg.transform.parent != null)
                    {
                        name     = tg.transform.parent.name + "_" + name + n;
                        tg       = tg.transform.parent.gameObject;
                        rootName = tg.name;
                    }

                    if (Directory.Exists("Assets/00_CombineMeshes/" + rootName) == false)
                    {
                        Directory.CreateDirectory("Assets/00_CombineMeshes/" + rootName);
                    }

                    if (name.StartsWith(rootName))
                    {
                        name = name.Substring(rootName.Length);
                        if (name.StartsWith("_Normal_"))
                        {
                            try
                            {
                                name = name.Substring(8);
                            }
                            catch
                            {
                            }
                        }
                    }

                    UnityEditor.AssetDatabase.CreateAsset(filter.sharedMesh, "Assets/00_CombineMeshes/" + rootName + "/" + ((fileStartName.Length > 0)?(fileStartName + "_"):"") + name + (++randomIndex) + ".asset");
                }
                                #endif
            }
        }
    }
Esempio n. 13
0
    public void Calculate(DecalPresets presets, GameObject affectedObject)
    {
        if (!affectedObject)
        {
            Debug.LogWarning("No object will be affected. Decal will not be calculated.");
            return;
        }

        angleCosine = Mathf.Cos(presets.maxAngle * Mathf.Deg2Rad);

        m_InstancesList = new List <MeshInstance>();
        CalculateObjectDecal(affectedObject);

        if (m_InstancesList.Count > 0)
        {
            MeshInstance[] instances = new MeshInstance[m_InstancesList.Count];
            for (int i = 0; i < instances.Length; i++)
            {
                instances[i] = m_InstancesList[i];
            }

            MeshRenderer meshRenderer = gameObject.GetComponent <MeshRenderer>();
            if (!meshRenderer)
            {
                meshRenderer = gameObject.AddComponent <MeshRenderer>();
            }

            meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            meshRenderer.material          = presets.material;

            MeshFilter meshFilter = gameObject.GetComponent <MeshFilter>();

            if (!meshFilter)
            {
                meshFilter = gameObject.AddComponent <MeshFilter>();
            }
            else
            {
                DestroyImmediate(meshFilter.sharedMesh);
            }

            Mesh finalMesh = MeshCombineUtility.Combine(instances, true);

            if (presets.pushDistance > 0.0f)
            {
                List <List <int> > relations = new List <List <int> >();
                Vector3[]          vert      = finalMesh.vertices;
                Vector3[]          normals   = finalMesh.normals;

                bool[] usedIndex = new bool[vert.Length];
                for (int i = 0; i < usedIndex.Length; i++)
                {
                    usedIndex[i] = false;
                }

                for (int i = 0; i < vert.Length; i++)
                {
                    if (usedIndex[i])
                    {
                        continue;
                    }

                    List <int> c = new List <int>
                    {
                        i
                    };

                    usedIndex[i] = true;

                    for (int j = i + 1; j < vert.Length; j++)
                    {
                        if (usedIndex[j])
                        {
                            continue;
                        }

                        if (Vector3.Distance(vert[i], vert[j]) > 0.001f)
                        {
                            continue;
                        }

                        c.Add(j);

                        usedIndex[j] = true;
                    }

                    relations.Add(c);
                }

                for (int i = 0, k = relations.Count; i < k; i++)
                {
                    Vector3 nNormal = Vector3.zero;
                    foreach (int j in relations[i])
                    {
                        nNormal += normals[j];
                    }

                    nNormal = (nNormal / relations[i].Count).normalized;

                    foreach (int j in relations[i])
                    {
                        vert[j] += nNormal * (presets.pushDistance);
                    }
                }

                finalMesh.vertices = vert;
            }

            finalMesh.name  = "DecalMesh";
            meshFilter.mesh = finalMesh;

            for (int i = 0; i < m_InstancesList.Count; i++)
            {
                DestroyImmediate(m_InstancesList[i].mesh);
            }
        }

        m_InstancesList.Clear();
        m_InstancesList = null;
    }
    /// This option has a far longer preprocessing time at startup but leads to better runtime performance.
    void Start()
    {
#if UNITY_EDITOR
        Debug.LogError("ERRORRR!!!!!");
        Debug.LogError("ERRORRR!!!!!"); Debug.LogError("ERRORRR!!!!!");
        Debug.LogError("ERRORRR!!!!!");
        Debug.LogError("ERRORRR!!!!!");
        Debug.LogError("ERRORRR!!!!!");
        Debug.LogError("ERRORRR!!!!!");
#endif
        return;


        Component[] filters        = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        Component[] filters1 = GetComponentsInChildren(typeof(Animator));
        int         flen2    = filters1.Length;
        for (int i = 0; i < flen2; ++i)
        {
            Destroy((Animator)filters1[i]);
            //((Animator)filters1[i]).enabled = false;
        }

        int flen = filters.Length;
        for (int i = 0; i < flen; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].renderer;
            curRenderer.castShadows    = false;
            curRenderer.receiveShadows = false;

            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);


                    if (materials[m] == null)
                    {
                        Debug.LogError("FBX BACKGROUND ERROR!!!!");
                        continue;
                    }

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];

                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                //curRenderer.enabled = false;

                GameObject.DestroyImmediate(curRenderer.gameObject);
            }
        }

        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (GetComponent(typeof(MeshFilter)) == null)
                {
                    gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!GetComponent("MeshRenderer"))
                {
                    gameObject.AddComponent("MeshRenderer");
                }

                MeshFilter filter = (MeshFilter)GetComponent(typeof(MeshFilter));
                filter.mesh             = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                renderer.material       = (Material)de.Key;
                renderer.enabled        = true;
                renderer.castShadows    = false;
                renderer.receiveShadows = false;
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                string n = "";

                n = de.Key.ToString();
                n = n.Substring(0, n.LastIndexOf("(") - 1);

                GameObject go = new GameObject("Combined mesh " + n);
                go.transform.parent        = transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));

                go.renderer.castShadows    = false;
                go.renderer.receiveShadows = false;
                if (go.animation != null && go.animation.GetClipCount() == 0)
                {
                    go.animation.enabled = false;
                }

                filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
            }
        }
    }
Esempio n. 15
0
    public void DoCombine()
    {
        Component[] componentsInChildren = base.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   matrix4x4            = base.transform.worldToLocalMatrix;
        Hashtable   hashtables           = new Hashtable();

        for (int i = 0; i < (int)componentsInChildren.Length; i++)
        {
            MeshFilter meshFilter = (MeshFilter)componentsInChildren[i];
            Renderer   renderer   = componentsInChildren[i].renderer;
            MeshCombineUtility.MeshInstance meshInstance = new MeshCombineUtility.MeshInstance()
            {
                mesh = meshFilter.sharedMesh
            };
            if (renderer != null && renderer.enabled && meshInstance.mesh != null)
            {
                meshInstance.transform = matrix4x4 * meshFilter.transform.localToWorldMatrix;
                Material[] materialArray = renderer.sharedMaterials;
                for (int j = 0; j < (int)materialArray.Length; j++)
                {
                    meshInstance.subMeshIndex = Math.Min(j, meshInstance.mesh.subMeshCount - 1);
                    ArrayList item = (ArrayList)hashtables[materialArray[j]];
                    if (item == null)
                    {
                        item = new ArrayList();
                        item.Add(meshInstance);
                        hashtables.Add(materialArray[j], item);
                    }
                    else
                    {
                        item.Add(meshInstance);
                    }
                }
                renderer.enabled = false;
            }
        }
        IDictionaryEnumerator enumerator = hashtables.GetEnumerator();

        try
        {
            while (enumerator.MoveNext())
            {
                DictionaryEntry current = (DictionaryEntry)enumerator.Current;
                MeshCombineUtility.MeshInstance[] array = (MeshCombineUtility.MeshInstance[])((ArrayList)current.Value).ToArray(typeof(MeshCombineUtility.MeshInstance));
                if (hashtables.Count != 1)
                {
                    GameObject gameObject = new GameObject("Combined mesh");
                    gameObject.transform.parent        = base.transform;
                    gameObject.transform.localScale    = Vector3.one;
                    gameObject.transform.localRotation = Quaternion.identity;
                    gameObject.transform.localPosition = Vector3.zero;
                    gameObject.AddComponent(typeof(MeshFilter));
                    gameObject.AddComponent("MeshRenderer");
                    gameObject.renderer.material = (Material)current.Key;
                    MeshFilter component = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
                    component.mesh = MeshCombineUtility.Combine(array, this.generateTriangleStrips);
                }
                else
                {
                    if (base.GetComponent(typeof(MeshFilter)) == null)
                    {
                        base.gameObject.AddComponent(typeof(MeshFilter));
                    }
                    if (!base.GetComponent("MeshRenderer"))
                    {
                        base.gameObject.AddComponent("MeshRenderer");
                    }
                    MeshFilter component1 = (MeshFilter)base.GetComponent(typeof(MeshFilter));
                    component1.mesh        = MeshCombineUtility.Combine(array, this.generateTriangleStrips);
                    base.renderer.material = (Material)current.Key;
                    base.renderer.enabled  = true;
                }
            }
        }
        finally
        {
            IDisposable disposable = enumerator as IDisposable;
            if (disposable == null)
            {
            }
            disposable.Dispose();
        }
    }
Esempio n. 16
0
    //Method responsible for constructing the Decal Mesh, based on the affected objects.
    public void CalculateDecal()
    {
        ClearDecals();

        maxAngle    = Mathf.Clamp(maxAngle, 0.0f, 180.0f);
        angleCosine = Mathf.Cos(maxAngle * Mathf.Deg2Rad);

        uvAngle = Mathf.Clamp(uvAngle, 0.0f, 360.0f);
        uCos    = Mathf.Cos(uvAngle * Mathf.Deg2Rad);
        vSin    = Mathf.Sin(uvAngle * Mathf.Deg2Rad);

        if (affectedObjects == null)
        {
            //Debug.LogWarning("No object will be affected. Decal will not be calculated.");
            return;
        }
        else if (affectedObjects.Length <= 0)
        {
            //Debug.LogWarning("No object will be affected. Decal will not be calculated.");
            return;
        }

        //Current transform matrix
        Matrix4x4 myTransform = transform.worldToLocalMatrix;

        instancesList = new List <MeshCombineUtility.MeshInstance>();

        for (int i = 0; i < affectedObjects.Length; i++)
        {
            if (affectedObjects[i] == null)
            {
                continue;
            }

            CalculateObjectDecal(affectedObjects[i], myTransform);
        }

        if (instancesList.Count > 0)
        {
            MeshCombineUtility.MeshInstance[] instances = new MeshCombineUtility.MeshInstance[instancesList.Count];
            for (int i = 0; i < instances.Length; i++)
            {
                instances[i] = instancesList[i];
            }

            MeshRenderer r = gameObject.GetComponent <MeshRenderer>();
            if (r == null)
            {
                r = gameObject.AddComponent <MeshRenderer>();
            }

            r.material = decalMaterial;

            MeshFilter fi = gameObject.GetComponent <MeshFilter>();

            if (fi == null)
            {
                fi = gameObject.AddComponent <MeshFilter>();
            }
            else
            {
                DestroyImmediate(fi.sharedMesh);
            }

            Mesh finalMesh = MeshCombineUtility.Combine(instances, true);

            if (pushDistance > 0.0f)
            {
                List <List <int> > relations = new List <List <int> >();
                Vector3[]          vert      = finalMesh.vertices;
                Vector3[]          normals   = finalMesh.normals;

                bool[] usedIndex = new bool[vert.Length];
                for (int i = 0; i < usedIndex.Length; i++)
                {
                    usedIndex[i] = false;
                }

                for (int i = 0; i < vert.Length; i++)
                {
                    if (usedIndex[i])
                    {
                        continue;
                    }

                    List <int> c = new List <int>();
                    c.Add(i);

                    usedIndex[i] = true;

                    for (int j = i + 1; j < vert.Length; j++)
                    {
                        if (usedIndex[j])
                        {
                            continue;
                        }

                        if (Vector3.Distance(vert[i], vert[j]) < 0.001f)
                        {
                            c.Add(j);

                            usedIndex[j] = true;
                        }
                    }

                    relations.Add(c);
                }

                foreach (List <int> l in relations)
                {
                    Vector3 nNormal = Vector3.zero;
                    foreach (int i in l)
                    {
                        nNormal += normals[i];
                    }

                    nNormal = (nNormal / l.Count).normalized;

                    foreach (int i in l)
                    {
                        vert[i] += nNormal * (pushDistance);
                    }
                }

                finalMesh.vertices = vert;
            }

            finalMesh.name = "DecalMesh";

            fi.mesh = finalMesh;

            for (int i = 0; i < instancesList.Count; i++)
            {
                DestroyImmediate(instancesList[i].mesh);
            }
        }

        instancesList.Clear();
        instancesList = null;
    }
Esempio n. 17
0
    public void Combine()
    {
        var       filters        = GetComponentsInChildren <MeshFilter>();
        Matrix4x4 myTransform    = transform.worldToLocalMatrix;
        var       materialToMesh = new Dictionary <Material, List <MeshCombineUtility.MeshInstance> >();

        foreach (var sourceFilter in filters)
        {
            Renderer curRenderer = sourceFilter.renderer;
            if (curRenderer == null || !curRenderer.enabled)
            {
                continue;
            }

            var instance = new MeshCombineUtility.MeshInstance
            {
                mesh      = sourceFilter.sharedMesh,
                transform = myTransform * sourceFilter.transform.localToWorldMatrix
            };
            if (instance.mesh == null)
            {
                continue;
            }

            Material[] materials = curRenderer.sharedMaterials;
            for (int m = 0; m < materials.Length; m++)
            {
                instance.subMeshIndex = Math.Min(m, instance.mesh.subMeshCount - 1);

                List <MeshCombineUtility.MeshInstance> objects;
                if (!materialToMesh.TryGetValue(materials[m], out objects))
                {
                    objects = new List <MeshCombineUtility.MeshInstance>();
                    materialToMesh.Add(materials[m], objects);
                }
                objects.Add(instance);
            }

            if (Application.isPlaying && destroyAfterOptimized && combineOnStart)
            {
                Destroy(curRenderer.gameObject);
            }
            else if (destroyAfterOptimized)
            {
                DestroyImmediate(curRenderer.gameObject);
            }
            else
            {
                curRenderer.enabled = false;
            }
        }

        int targetMeshIndex = 0;

        foreach (var de in materialToMesh)
        {
            foreach (var instance in de.Value)
            {
                instance.targetSubMeshIndex = targetMeshIndex;
            }
            ++targetMeshIndex;
        }

        if (!GetComponent <MeshFilter>())
        {
            gameObject.AddComponent <MeshFilter>();
        }
        var filter = GetComponent <MeshFilter>();

        if (!GetComponent <MeshRenderer>())
        {
            gameObject.AddComponent <MeshRenderer>();
        }

        var mesh = MeshCombineUtility.Combine(materialToMesh.SelectMany(kvp => kvp.Value), generateTriangleStrips);

        mesh.name = combinedMeshName;
        if (Application.isPlaying)
        {
            filter.mesh = mesh;
        }
        else
        {
            filter.sharedMesh = mesh;
        }
        renderer.materials = materialToMesh.Keys.ToArray();
        renderer.enabled   = true;
        if (addMeshCollider)
        {
            gameObject.AddComponent <MeshCollider>();
        }
        renderer.castShadows    = castShadow;
        renderer.receiveShadows = receiveShadow;
    }
Esempio n. 18
0
    private void Start()
    {
        Component[] componentsInChildren = base.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   worldToLocalMatrix   = base.transform.worldToLocalMatrix;
        Hashtable   hashtable            = new Hashtable();

        for (int i = 0; i < componentsInChildren.Length; i++)
        {
            MeshFilter meshFilter = (MeshFilter)componentsInChildren[i];
            Renderer   renderer   = componentsInChildren[i].renderer;
            MeshCombineUtility.MeshInstance meshInstance = default(MeshCombineUtility.MeshInstance);
            meshInstance.mesh = meshFilter.sharedMesh;
            if (renderer != null && renderer.enabled && meshInstance.mesh != null)
            {
                meshInstance.transform = worldToLocalMatrix * meshFilter.transform.localToWorldMatrix;
                Material[] sharedMaterials = renderer.sharedMaterials;
                for (int j = 0; j < sharedMaterials.Length; j++)
                {
                    meshInstance.subMeshIndex = Math.Min(j, meshInstance.mesh.subMeshCount - 1);
                    ArrayList arrayList = (ArrayList)hashtable[sharedMaterials[j]];
                    if (arrayList != null)
                    {
                        arrayList.Add(meshInstance);
                    }
                    else
                    {
                        arrayList = new ArrayList();
                        arrayList.Add(meshInstance);
                        hashtable.Add(sharedMaterials[j], arrayList);
                    }
                }
                renderer.enabled = false;
            }
        }
        foreach (DictionaryEntry dictionaryEntry in hashtable)
        {
            ArrayList arrayList2 = (ArrayList)dictionaryEntry.Value;
            MeshCombineUtility.MeshInstance[] combines = (MeshCombineUtility.MeshInstance[])arrayList2.ToArray(typeof(MeshCombineUtility.MeshInstance));
            if (hashtable.Count == 1)
            {
                if (base.GetComponent(typeof(MeshFilter)) == null)
                {
                    base.gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!base.GetComponent("MeshRenderer"))
                {
                    base.gameObject.AddComponent("MeshRenderer");
                }
                MeshFilter meshFilter2 = (MeshFilter)base.GetComponent(typeof(MeshFilter));
                meshFilter2.mesh       = MeshCombineUtility.Combine(combines, this.generateTriangleStrips);
                base.renderer.material = (Material)dictionaryEntry.Key;
                base.renderer.enabled  = true;
            }
            else
            {
                GameObject gameObject = new GameObject("Combined mesh");
                gameObject.transform.parent        = base.transform;
                gameObject.transform.localScale    = Vector3.one;
                gameObject.transform.localRotation = Quaternion.identity;
                gameObject.transform.localPosition = Vector3.zero;
                gameObject.AddComponent(typeof(MeshFilter));
                gameObject.AddComponent("MeshRenderer");
                gameObject.renderer.material = (Material)dictionaryEntry.Key;
                MeshFilter meshFilter3 = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
                meshFilter3.mesh = MeshCombineUtility.Combine(combines, this.generateTriangleStrips);
            }
        }
    }
Esempio n. 19
0
    public void DoCombine()
    {
        Component[] componentsInChildren = base.GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   worldToLocalMatrix   = base.transform.worldToLocalMatrix;
        Hashtable   hashtable            = new Hashtable();

        for (int i = 0; i < componentsInChildren.Length; i++)
        {
            MeshFilter filter   = (MeshFilter)componentsInChildren[i];
            Renderer   renderer = componentsInChildren[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance {
                mesh = filter.sharedMesh
            };
            if (((renderer != null) && renderer.enabled) && (instance.mesh != null))
            {
                instance.transform = worldToLocalMatrix * filter.transform.localToWorldMatrix;
                Material[] sharedMaterials = renderer.sharedMaterials;
                for (int j = 0; j < sharedMaterials.Length; j++)
                {
                    instance.subMeshIndex = Math.Min(j, instance.mesh.subMeshCount - 1);
                    ArrayList list = (ArrayList)hashtable[sharedMaterials[j]];
                    if (list != null)
                    {
                        list.Add(instance);
                    }
                    else
                    {
                        list = new ArrayList();
                        list.Add(instance);
                        hashtable.Add(sharedMaterials[j], list);
                    }
                }
                renderer.enabled = false;
            }
        }
        IDictionaryEnumerator enumerator = hashtable.GetEnumerator();

        try
        {
            while (enumerator.MoveNext())
            {
                DictionaryEntry current = (DictionaryEntry)enumerator.Current;
                ArrayList       list2   = (ArrayList)current.Value;
                MeshCombineUtility.MeshInstance[] combines = (MeshCombineUtility.MeshInstance[])list2.ToArray(typeof(MeshCombineUtility.MeshInstance));
                if (hashtable.Count == 1)
                {
                    if (base.GetComponent(typeof(MeshFilter)) == null)
                    {
                        base.gameObject.AddComponent(typeof(MeshFilter));
                    }
                    if (base.GetComponent("MeshRenderer") == null)
                    {
                        base.gameObject.AddComponent("MeshRenderer");
                    }
                    MeshFilter component = (MeshFilter)base.GetComponent(typeof(MeshFilter));
                    component.mesh         = MeshCombineUtility.Combine(combines, this.generateTriangleStrips);
                    base.renderer.material = (Material)current.Key;
                    base.renderer.enabled  = true;
                }
                else
                {
                    GameObject obj2 = new GameObject("Combined mesh")
                    {
                        transform = { parent = base.transform, localScale = Vector3.one, localRotation = Quaternion.identity, localPosition = Vector3.zero }
                    };
                    obj2.AddComponent(typeof(MeshFilter));
                    obj2.AddComponent("MeshRenderer");
                    obj2.renderer.material = (Material)current.Key;
                    MeshFilter filter3 = (MeshFilter)obj2.GetComponent(typeof(MeshFilter));
                    filter3.mesh = MeshCombineUtility.Combine(combines, this.generateTriangleStrips);
                }
            }
        }
        finally
        {
            IDisposable disposable = enumerator as IDisposable;
            if (disposable == null)
            {
            }
            disposable.Dispose();
        }
    }
Esempio n. 20
0
    public void Combine()
    {
#if UNITY_EDITOR
        if (!Application.isPlaying)
        {
            Undo.RegisterSceneUndo("Combine meshes");
        }
#endif
        Component[] filters        = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }
                if (Application.isPlaying && destroyAfterOptimized && combineOnStart)
                {
                    Destroy(curRenderer.gameObject);
                }
                else if (destroyAfterOptimized)
                {
                    DestroyImmediate(curRenderer.gameObject);
                }
                else
                {
                    curRenderer.enabled = false;
                }
            }
        }

        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (GetComponent(typeof(MeshFilter)) == null)
                {
                    gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!GetComponent("MeshRenderer"))
                {
                    gameObject.AddComponent("MeshRenderer");
                }

                MeshFilter filter = (MeshFilter)GetComponent(typeof(MeshFilter));
                if (Application.isPlaying)
                {
                    filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                }
                else
                {
                    filter.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                }
                renderer.material = (Material)de.Key;
                renderer.enabled  = true;
                if (addMeshCollider)
                {
                    gameObject.AddComponent <MeshCollider>();
                }
                renderer.castShadows    = castShadow;
                renderer.receiveShadows = receiveShadow;
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                GameObject go = new GameObject("Combined mesh");
                if (keepLayer)
                {
                    go.layer = gameObject.layer;
                }
                go.transform.parent        = transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
                if (Application.isPlaying)
                {
                    filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                }
                else
                {
                    filter.sharedMesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                }
                go.renderer.castShadows    = castShadow;
                go.renderer.receiveShadows = receiveShadow;
                if (addMeshCollider)
                {
                    go.AddComponent <MeshCollider>();
                }
            }
        }
    }
Esempio n. 21
0
    void Start()
    {
        Component[] filters        = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter      = (MeshFilter)filters[i];
            Renderer   curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                curRenderer.enabled = false;
            }
        }

        foreach (DictionaryEntry de in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            if (materialToMesh.Count == 1)
            {
                if (GetComponent(typeof(MeshFilter)) == null)
                {
                    gameObject.AddComponent <MeshFilter>();
                }
                if (!GetComponent(typeof(MeshRenderer)))
                {
                    gameObject.AddComponent <MeshRenderer>();
                }

                MeshFilter filter = (MeshFilter)GetComponent(typeof(MeshFilter));
                filter.mesh       = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                renderer.material = (Material)de.Key;
                renderer.enabled  = true;
            }
            else
            {
                GameObject go = new GameObject("Combined mesh");
                go.transform.parent        = transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent <MeshFilter>();
                go.AddComponent <MeshRenderer>();
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
            }
        }
    }
Esempio n. 22
0
    /// This option has a far longer preprocessing time at startup but leads to better runtime performance.
    public void Combine()
    {
        if (!Application.isEditor)
        {
            DisableCombine();
        }

        currentMeshes = new List <GameObject>();
        allRenderers  = new List <Renderer>();

        Component[] filters        = GetComponentsInChildren(typeof(MeshFilter));
        Matrix4x4   myTransform    = transform.worldToLocalMatrix;
        Hashtable   materialToMesh = new Hashtable();

        MeshFilter f = GetComponent <MeshFilter>();

        for (int i = 0; i < filters.Length; i++)
        {
            MeshFilter filter = (MeshFilter)filters[i];

            if (f != null)
            {
                if (f == filter)
                {
                    continue;
                }
            }

            if (removeColliders)
            {
                if (filter.collider != null)
                {
                    if (Application.isEditor)
                    {
                        DestroyImmediate(filter.collider);
                    }
                    else
                    {
                        Destroy(filter.collider);
                    }
                }
            }

            Renderer curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    ArrayList objects = (ArrayList)materialToMesh[materials[m]];
                    if (objects != null)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new ArrayList();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

                allRenderers.Add(curRenderer);
                curRenderer.enabled = false;
            }
        }

        foreach (DictionaryEntry de  in materialToMesh)
        {
            ArrayList elements = (ArrayList)de.Value;
            MeshCombineUtility.MeshInstance[] instances = (MeshCombineUtility.MeshInstance[])elements.ToArray(typeof(MeshCombineUtility.MeshInstance));

            // We have a maximum of one material, so just attach the mesh to our own game object
            if (materialToMesh.Count == 1)
            {
                // Make sure we have a mesh filter & renderer
                if (GetComponent(typeof(MeshFilter)) == null)
                {
                    gameObject.AddComponent(typeof(MeshFilter));
                }
                if (!GetComponent("MeshRenderer"))
                {
                    gameObject.AddComponent("MeshRenderer");
                }

                MeshFilter filter = (MeshFilter)GetComponent(typeof(MeshFilter));
                filter.mesh       = MeshCombineUtility.Combine(instances, generateTriangleStrips);
                renderer.material = (Material)de.Key;
                renderer.enabled  = true;
            }
            // We have multiple materials to take care of, build one mesh / gameobject for each material
            // and parent it to this object
            else
            {
                GameObject go = new GameObject("Combined mesh");
                currentMeshes.Add(go);
                go.transform.parent        = transform;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                go.AddComponent(typeof(MeshFilter));
                go.AddComponent("MeshRenderer");
                go.renderer.material = (Material)de.Key;
                MeshFilter filter = (MeshFilter)go.GetComponent(typeof(MeshFilter));
                filter.mesh = MeshCombineUtility.Combine(instances, generateTriangleStrips);
            }
        }
    }
Esempio n. 23
0
    GameObject combineMesh(bool exportAssets)
    {
        GameObject returnObject = new GameObject(m_parentObject.name);

        returnObject.transform.position = m_parentObject.transform.position;
        returnObject.transform.rotation = m_parentObject.transform.rotation;


        MeshFilter[] filters     = m_parentObject.GetComponentsInChildren <MeshFilter>();
        Matrix4x4    myTransform = m_parentObject.transform.worldToLocalMatrix;

        Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > allMeshesAndMaterials = new Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > >();

        for (int i = 0; i < filters.Length; i++)
        {
            Renderer curRenderer = filters[i].renderer;
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();

            instance.mesh = filters[i].sharedMesh;

            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filters[i].transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    if (!allMeshesAndMaterials.ContainsKey(materials[m].shader.ToString()))
                    {
                        allMeshesAndMaterials.Add(materials[m].shader.ToString(), new Dictionary <Material, List <MeshCombineUtility.MeshInstance> >());
                    }

                    if (!allMeshesAndMaterials[materials[m].shader.ToString()].ContainsKey(materials[m]))
                    {
                        allMeshesAndMaterials[materials[m].shader.ToString()].Add(materials[m], new List <MeshCombineUtility.MeshInstance>());
                    }

                    allMeshesAndMaterials[materials[m].shader.ToString()][materials[m]].Add(instance);
                }
            }
        }

        foreach (KeyValuePair <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > firstPass in allMeshesAndMaterials)
        {
            Material[] allMaterialTextures = new Material[firstPass.Value.Keys.Count];
            int        index = 0;

            foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
            {
                allMaterialTextures[index] = kv.Key;
                index++;
            }

            TextureCombineUtility.TexturePosition[] textureUVPositions;
            Material combined = TextureCombineUtility.combine(allMaterialTextures, out textureUVPositions, m_textureAtlasInfo);
            List <MeshCombineUtility.MeshInstance> meshes = new List <MeshCombineUtility.MeshInstance>();

            foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
            {
                List <MeshCombineUtility.MeshInstance> meshIntermediates = new List <MeshCombineUtility.MeshInstance>();
                Mesh[] firstCombineStep = MeshCombineUtility.Combine(kv.Value.ToArray());

                for (int i = 0; i < firstCombineStep.Length; i++)
                {
                    MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();
                    instance.mesh         = firstCombineStep[i];
                    instance.subMeshIndex = 0;
                    instance.transform    = Matrix4x4.identity;
                    meshIntermediates.Add(instance);
                }

                TextureCombineUtility.TexturePosition refTexture = textureUVPositions[0];

                for (int j = 0; j < textureUVPositions.Length; j++)
                {
                    if (kv.Key.mainTexture.name == textureUVPositions[j].textures[0].name)
                    {
                        refTexture = textureUVPositions[j];
                        break;
                    }
                }

                for (int j = 0; j < meshIntermediates.Count; j++)
                {
                    Vector2[] uvCopy = meshIntermediates[j].mesh.uv;
                    for (int k = 0; k < uvCopy.Length; k++)
                    {
                        uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                        uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                    }

                    meshIntermediates[j].mesh.uv = uvCopy;

                    uvCopy = meshIntermediates[j].mesh.uv1;
                    for (int k = 0; k < uvCopy.Length; k++)
                    {
                        uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                        uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                    }

                    meshIntermediates[j].mesh.uv1 = uvCopy;

                    uvCopy = meshIntermediates[j].mesh.uv2;
                    for (int k = 0; k < uvCopy.Length; k++)
                    {
                        uvCopy[k].x = refTexture.position.x + uvCopy[k].x * refTexture.position.width;
                        uvCopy[k].y = refTexture.position.y + uvCopy[k].y * refTexture.position.height;
                    }

                    meshIntermediates[j].mesh.uv2 = uvCopy;

                    meshes.Add(meshIntermediates[j]);
                }
            }

            Material mat = combined;

            Mesh[] combinedMeshes = MeshCombineUtility.Combine(meshes.ToArray());

            GameObject parent = new GameObject("Combined " + m_parentObject.name + " " + firstPass.Key + " Mesh Parent");
            parent.transform.position = m_parentObject.transform.position;
            parent.transform.rotation = m_parentObject.transform.rotation;
            parent.transform.parent   = returnObject.transform;

            for (int i = 0; i < combinedMeshes.Length; i++)
            {
                GameObject go = new GameObject("Combined " + m_parentObject.name + " Mesh");
                go.transform.parent = parent.transform;
                go.tag   = m_parentObject.tag;
                go.layer = m_parentObject.layer;
                go.transform.localScale    = Vector3.one;
                go.transform.localRotation = Quaternion.identity;
                go.transform.localPosition = Vector3.zero;
                MeshFilter filter = go.AddComponent <MeshFilter>();
                go.AddComponent <MeshRenderer>();
                go.renderer.sharedMaterial = mat;

                filter.mesh = combinedMeshes[i];

                if (exportAssets == true)
                {
                    checkAndCreateFolder();

                    //(go.GetComponent<MeshRenderer>().material.mainTexture as Texture2D).format = TextureFormat.RGBA32;
                    Debug.Log((go.GetComponent <MeshRenderer>().sharedMaterial.mainTexture as Texture2D).format);
                    if ((go.GetComponent <MeshRenderer>().sharedMaterial.mainTexture as Texture2D).format != TextureFormat.ARGB32 &&
                        (go.GetComponent <MeshRenderer>().sharedMaterial.mainTexture as Texture2D).format != TextureFormat.RGB24 &&
                        (go.GetComponent <MeshRenderer>().sharedMaterial.mainTexture as Texture2D).format != TextureFormat.RGBA32)
                    {
                        Debug.LogError("Textures assigned to objects must be either RGBA32 or RGB 24 to be exported");
                        return(null);
                    }

                    byte[] texture = (go.GetComponent <MeshRenderer>().material.mainTexture as Texture2D).EncodeToPNG();
                    System.IO.File.WriteAllBytes(m_pathToAssets + mat.shader.ToString().Remove(mat.shader.ToString().IndexOf("(")) + i + ".png", texture);
                    exportMesh(combinedMeshes[i], mat.shader.ToString().Remove(mat.shader.ToString().IndexOf("(")) + i);
                }
            }
        }

        //if(developmentBake == true)
        //{
        foreach (Renderer r in m_parentObject.GetComponentsInChildren <Renderer>())
        {
            r.enabled = false;
        }
        //}

        return(returnObject);
    }
Esempio n. 24
0
    public TextureAtlasInfo textureAtlasProperties;    // = new TextureCombineUtility.TextureAtlasInfo();

    /// This option has a far longer preprocessing time at startup but leads to better runtime performance.
    void Start()
    {
        MeshFilter[] filters     = GetComponentsInChildren <MeshFilter>();
        Matrix4x4    myTransform = transform.worldToLocalMatrix;

        Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > allMeshesAndMaterials = new Dictionary <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > >();

        for (int i = 0; i < filters.Length; i++)
        {
            Renderer curRenderer = filters[i].GetComponent <Renderer>();
            MeshCombineUtility.MeshInstance instance = new MeshCombineUtility.MeshInstance();

            instance.mesh = filters[i].mesh;

            if (curRenderer != null && curRenderer.enabled && instance.mesh != null)
            {
                instance.transform = myTransform * filters[i].transform.localToWorldMatrix;

                Material[] materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; m++)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    if (!allMeshesAndMaterials.ContainsKey(materials[m].shader.ToString()))
                    {
                        allMeshesAndMaterials.Add(materials[m].shader.ToString(), new Dictionary <Material, List <MeshCombineUtility.MeshInstance> >());
                    }

                    if (!allMeshesAndMaterials[materials[m].shader.ToString()].ContainsKey(materials[m]))
                    {
                        allMeshesAndMaterials[materials[m].shader.ToString()].Add(materials[m], new List <MeshCombineUtility.MeshInstance>());
                    }

                    allMeshesAndMaterials[materials[m].shader.ToString()][materials[m]].Add(instance);
                }
            }
        }

        foreach (KeyValuePair <string, Dictionary <Material, List <MeshCombineUtility.MeshInstance> > > firstPass in allMeshesAndMaterials)
        {
            Material[] allMaterialTextures = new Material[firstPass.Value.Keys.Count];
            int        index = 0;

            foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
            {
                allMaterialTextures[index] = kv.Key;
                index++;
            }

            TextureCombineUtility.TexturePosition[] textureUVPositions;
            Material combined = TextureCombineUtility.combine(allMaterialTextures, out textureUVPositions, textureAtlasProperties);

            if (textureUVPositions != null)
            {
                List <MeshCombineUtility.MeshInstance> meshIntermediates = new List <MeshCombineUtility.MeshInstance>();
                foreach (KeyValuePair <Material, List <MeshCombineUtility.MeshInstance> > kv in firstPass.Value)
                {
                    TextureCombineUtility.TexturePosition refTexture = textureUVPositions[0];

                    for (int i = 0; i < textureUVPositions.Length; i++)
                    {
                        if (kv.Key.mainTexture.name == textureUVPositions[i].textures[0].name)
                        {
                            refTexture = textureUVPositions[i];
                            break;
                        }
                    }

                    for (int i = 0; i < kv.Value.Count; i++)
                    {
                        Vector2[] uvCopy = kv.Value[i].mesh.uv;

                        for (int j = 0; j < uvCopy.Length; j++)
                        {
                            uvCopy[j].x = refTexture.position.x + uvCopy[j].x * refTexture.position.width;
                            uvCopy[j].y = refTexture.position.y + uvCopy[j].y * refTexture.position.height;
                        }

                        kv.Value[i].mesh.uv = uvCopy;


                        uvCopy = kv.Value[i].mesh.uv2;
                        for (int j = 0; j < uvCopy.Length; j++)
                        {
                            uvCopy[j].x = refTexture.position.x + uvCopy[j].x * refTexture.position.width;
                            uvCopy[j].y = refTexture.position.y + uvCopy[j].y * refTexture.position.height;
                        }

                        kv.Value[i].mesh.uv2 = uvCopy;



                        uvCopy = kv.Value[i].mesh.uv2;
                        for (int j = 0; j < uvCopy.Length; j++)
                        {
                            uvCopy[j].x = refTexture.position.x + uvCopy[j].x * refTexture.position.width;
                            uvCopy[j].y = refTexture.position.y + uvCopy[j].y * refTexture.position.height;
                        }

                        kv.Value[i].mesh.uv2 = uvCopy;


                        meshIntermediates.Add(kv.Value[i]);
                    }
                }

                Material mat = combined;

                Mesh[] combinedMeshes = MeshCombineUtility.Combine(meshIntermediates.ToArray());

                GameObject parent = new GameObject("Combined " + gameObject.name + " " + firstPass.Key + " Mesh Parent");
                parent.transform.position = transform.position;
                parent.transform.rotation = transform.rotation;

                for (int i = 0; i < combinedMeshes.Length; i++)
                {
                    GameObject go = new GameObject("Combined " + gameObject.name + " Mesh");
                    go.transform.parent = parent.transform;
                    go.tag   = gameObject.tag;
                    go.layer = gameObject.layer;
                    go.transform.localScale    = Vector3.one;
                    go.transform.localRotation = Quaternion.identity;
                    go.transform.localPosition = Vector3.zero;
                    MeshFilter filter = go.AddComponent <MeshFilter>();
                    go.AddComponent <MeshRenderer>();
                    go.GetComponent <Renderer>().sharedMaterial = mat;

                    filter.mesh = combinedMeshes[i];
                }
            }
        }
        Destroy(gameObject);
    }
Esempio n. 25
0
    public void CombineChildren()
    {
        var target         = Selection.activeGameObject;
        var filters        = target.GetComponentsInChildren <MeshFilter>();
        var myTransform    = target.transform.worldToLocalMatrix;
        var materialToMesh = new Dictionary <Material, List <MeshCombineUtility.MeshInstance> >();

        for (int i = 0; i < filters.Length; ++i)
        {
            var filter = filters[i];
            if (filter.gameObject.name.Contains("Collider"))
            {
                continue;
            }
            var curRenderer = filters[i].renderer;
            var instance    = new MeshCombineUtility.MeshInstance();
            instance.mesh = filter.sharedMesh;
            if (curRenderer != null && instance.mesh != null)
            {
                instance.transform = myTransform * filter.transform.localToWorldMatrix;

                var materials = curRenderer.sharedMaterials;
                for (int m = 0; m < materials.Length; ++m)
                {
                    instance.subMeshIndex = System.Math.Min(m, instance.mesh.subMeshCount - 1);

                    List <MeshCombineUtility.MeshInstance> objects = null;
                    var gotList = materialToMesh.TryGetValue(materials[m], out objects);
                    if (gotList)
                    {
                        objects.Add(instance);
                    }
                    else
                    {
                        objects = new List <MeshCombineUtility.MeshInstance>();
                        objects.Add(instance);
                        materialToMesh.Add(materials[m], objects);
                    }
                }

//				curRenderer.enabled = true;
            }
        }

        var meshCount        = 0;
        var combinedChildren = new List <GameObject>();

        foreach (var keyValuePair in materialToMesh)
        {
            var elements  = keyValuePair.Value;
            var instances = elements.ToArray();

            Mesh mesh       = null;
            var  gameObject = new GameObject("Combined mesh");
            gameObject.transform.parent        = target.transform;
            gameObject.transform.localScale    = Vector3.one;
            gameObject.transform.localRotation = Quaternion.identity;
            gameObject.transform.localPosition = Vector3.zero;
            gameObject.AddComponent <MeshFilter>();
            gameObject.AddComponent <MeshRenderer>();
            gameObject.renderer.material = keyValuePair.Key;
            var filter = gameObject.GetComponent <MeshFilter>();
            mesh        = MeshCombineUtility.Combine(instances, generateTriangleStrips);
            filter.mesh = mesh;

            combinedChildren.Add(gameObject);

            ++meshCount;
            AddMeshToAssets(target, mesh, meshCount);
        }

        var clone = GameObject.Instantiate(target) as GameObject;

        clone.name = target.name;
        combinedChildren.Each(c => DestroyImmediate(c));
        clone.GetComponentsInChildren <MeshRenderer>().Where(r => r != null &&
                                                             r.gameObject.name != "Combined mesh" &&
                                                             !r.gameObject.name.Contains("Collider") &&
                                                             !r.gameObject.name.Contains("Collision") &&
                                                             !r.gameObject.name.Contains("Indoors"))
        .Each(renderer => DestroyImmediate(renderer.gameObject));

        var destroyedCompletely = false;

        do
        {
            destroyedCompletely = !DestroyEmptyGameObjectsIn(clone);
        } while (!destroyedCompletely);

        var assetName = string.Format("Assets/Prefabs/Combined Prefabs/{0}.prefab", clone.name);
        // can't catch the folder error, so just create the folder first manually
        var prefab = EditorUtility.CreateEmptyPrefab(assetName);

        EditorUtility.ReplacePrefab(clone, prefab);
        AssetDatabase.Refresh();

        DestroyImmediate(clone);         // the clone must be manually destroyed because it can never be empty
    }