public static bool bake(MB3_MeshBakerCommon mom)
        {
            bool createdDummyTextureBakeResults = false;
            bool success = false;

            try{
                if (mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoSceneObject ||
                    mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoPrefab)
                {
                    success = MB3_MeshBakerEditorFunctions.BakeIntoCombined(mom, out createdDummyTextureBakeResults);
                }
                else
                {
                    //bake meshes in place
                    if (mom is MB3_MeshBaker)
                    {
                        if (MB3_MeshCombiner.EVAL_VERSION)
                        {
                            Debug.LogError("Bake Meshes In Place is disabled in the evaluation version.");
                        }
                        else
                        {
                            MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;
                            if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.prefabOnly, new MB3_EditorMethods(), vl))
                            {
                                return(false);
                            }

                            List <GameObject> objsToMesh = mom.GetObjectsToCombine();
                            Mesh m = MB3_BakeInPlace.BakeMeshesInPlace((MB3_MeshCombinerSingle)((MB3_MeshBaker)mom).meshCombiner, objsToMesh, mom.bakeAssetsInPlaceFolderPath, updateProgressBar);
                            if (m != null)
                            {
                                success = true;
                            }
                        }
                    }
                    else
                    {
                        Debug.LogError("Multi-mesh Baker components cannot be used for Bake In Place. Use an ordinary Mesh Baker object instead.");
                    }
                }
                if (mom.clearBuffersAfterBake)
                {
                    mom.meshCombiner.ClearBuffers();
                }
                mom.meshCombiner.CheckIntegrity();
            } catch (Exception e) {
                Debug.LogError(e);
            } finally {
                if (createdDummyTextureBakeResults)
                {
                    GameObject.DestroyImmediate(mom.textureBakeResults);
                    mom.textureBakeResults = null;
                }
                EditorUtility.ClearProgressBar();
            }
            return(success);
        }
Exemplo n.º 2
0
    public IEnumerator CreateAtlasesCoroutine(ProgressUpdateDelegate progressInfo, CreateAtlasesCoroutineResult coroutineResult, bool saveAtlasesAsAssets = false, MB2_EditorMethodsInterface editorMethods = null, float maxTimePerFrame = .01f)
    {
        MBVersionConcrete mbv = new MBVersionConcrete();

        if (!MB3_TextureCombiner._RunCorutineWithoutPauseIsRunning && (mbv.GetMajorVersion() < 5 || (mbv.GetMajorVersion() == 5 && mbv.GetMinorVersion() < 3)))
        {
            Debug.LogError("Running the texture combiner as a coroutine only works in Unity 5.3 and higher");
            coroutineResult.success = false;
            yield break;
        }
        this.OnCombinedTexturesCoroutineAtlasesAndRects = null;

        if (maxTimePerFrame <= 0f)
        {
            Debug.LogError("maxTimePerFrame must be a value greater than zero");
            coroutineResult.isFinished = true;
            yield break;
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!DoCombinedValidate(this, MB_ObjsToCombineTypes.dontCare, null, vl))
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        if (_doMultiMaterial && !_ValidateResultMaterials())
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        else if (!_doMultiMaterial)
        {
            if (_resultMaterial == null)
            {
                Debug.LogError("Combined Material is null please create and assign a result material.");
                coroutineResult.isFinished = true;
                yield break;
            }
            Shader targShader = _resultMaterial.shader;
            for (int i = 0; i < objsToMesh.Count; i++)
            {
                Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
                for (int j = 0; j < ms.Length; j++)
                {
                    Material m = ms[j];
                    if (m != null && m.shader != targShader)
                    {
                        Debug.LogWarning("Game object " + objsToMesh[i] + " does not use shader " + targShader + " it may not have the required textures. If not small solid color textures will be generated.");
                    }
                }
            }
        }

        MB3_TextureCombiner combiner = CreateAndConfigureTextureCombiner();

        combiner.saveAtlasesAsAssets = saveAtlasesAsAssets;

        //initialize structure to store results
        int numResults = 1;

        if (_doMultiMaterial)
        {
            numResults = resultMaterials.Length;
        }
        OnCombinedTexturesCoroutineAtlasesAndRects = new MB_AtlasesAndRects[numResults];
        for (int i = 0; i < OnCombinedTexturesCoroutineAtlasesAndRects.Length; i++)
        {
            OnCombinedTexturesCoroutineAtlasesAndRects[i] = new MB_AtlasesAndRects();
        }

        //Do the material combining.
        for (int i = 0; i < OnCombinedTexturesCoroutineAtlasesAndRects.Length; i++)
        {
            Material        resMatToPass = null;
            List <Material> sourceMats   = null;
            if (_doMultiMaterial)
            {
                sourceMats   = resultMaterials[i].sourceMaterials;
                resMatToPass = resultMaterials[i].combinedMaterial;
                combiner.fixOutOfBoundsUVs = resultMaterials[i].considerMeshUVs;
            }
            else
            {
                resMatToPass = _resultMaterial;
            }

            MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult coroutineResult2 = new MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult();
            yield return(combiner.CombineTexturesIntoAtlasesCoroutine(progressInfo, OnCombinedTexturesCoroutineAtlasesAndRects[i], resMatToPass, objsToMesh, sourceMats, editorMethods, coroutineResult2, maxTimePerFrame));

            coroutineResult.success = coroutineResult2.success;
            if (!coroutineResult.success)
            {
                coroutineResult.isFinished = true;
                yield break;
            }
        }

        unpackMat2RectMap(textureBakeResults);
        //Save the results
        textureBakeResults.doMultiMaterial = _doMultiMaterial;
        //textureBakeResults.resultMaterial = _resultMaterial;
        if (_doMultiMaterial)
        {
            textureBakeResults.resultMaterials = resultMaterials;
        }
        else
        {
            MB_MultiMaterial[] resMats = new MB_MultiMaterial[1];
            resMats[0] = new MB_MultiMaterial();
            resMats[0].combinedMaterial = _resultMaterial;
            resMats[0].considerMeshUVs  = _fixOutOfBoundsUVs;
            resMats[0].sourceMaterials  = new List <Material>();
            for (int i = 0; i < textureBakeResults.materialsAndUVRects.Length; i++)
            {
                resMats[0].sourceMaterials.Add(textureBakeResults.materialsAndUVRects[i].material);
            }
            textureBakeResults.resultMaterials = resMats;
        }
        //textureBakeResults.fixOutOfBoundsUVs = combiner.fixOutOfBoundsUVs;


        //set the texture bake resultAtlasesAndRects on the Mesh Baker component if it exists
        MB3_MeshBakerCommon[] mb = GetComponentsInChildren <MB3_MeshBakerCommon>();
        for (int i = 0; i < mb.Length; i++)
        {
            mb[i].textureBakeResults = textureBakeResults;
        }

        if (LOG_LEVEL >= MB2_LogLevel.info)
        {
            Debug.Log("Created Atlases");
        }

        coroutineResult.isFinished = true;
        if (coroutineResult.success && onBuiltAtlasesSuccess != null)
        {
            onBuiltAtlasesSuccess();
        }
        if (!coroutineResult.success && onBuiltAtlasesFail != null)
        {
            onBuiltAtlasesFail();
        }
    }
    /// <summary>
    ///  Bakes a combined mesh.
    /// </summary>
    /// <param name="so">If this is being called from Inspector code then pass in the SerializedObject for the component.
    /// This is necessary for "bake into prefab" which can corrupt the SerializedObject.</param>
    public static bool BakeIntoCombined(MB3_MeshBakerCommon mom, out bool createdDummyTextureBakeResults, ref SerializedObject so)
    {
        MB2_OutputOptions prefabOrSceneObject = mom.meshCombiner.outputOption;

        createdDummyTextureBakeResults = false;

        // Initial Validate
        {
            if (mom.meshCombiner.resultSceneObject != null &&
                (MBVersionEditor.PrefabUtility_GetPrefabType(mom.meshCombiner.resultSceneObject) == MB_PrefabType.modelPrefabAsset ||
                 MBVersionEditor.PrefabUtility_GetPrefabType(mom.meshCombiner.resultSceneObject) == MB_PrefabType.prefabAsset))
            {
                Debug.LogWarning("Result Game Object was a project asset not a scene object instance. Clearing this field.");
                mom.meshCombiner.resultSceneObject = null;
            }

            if (prefabOrSceneObject != MB2_OutputOptions.bakeIntoPrefab && prefabOrSceneObject != MB2_OutputOptions.bakeIntoSceneObject)
            {
                Debug.LogError("Paramater prefabOrSceneObject must be bakeIntoPrefab or bakeIntoSceneObject");
                return(false);
            }

            if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab)
            {
                if (MB3_MeshCombiner.EVAL_VERSION)
                {
                    Debug.LogError("Cannot BakeIntoPrefab with evaluation version.");
                    return(false);
                }

                if (mom.resultPrefab == null)
                {
                    Debug.LogError("Need to set the Combined Mesh Prefab field. Create a prefab asset, drag an empty game object into it, and drag it to the 'Combined Mesh Prefab' field.");
                    return(false);
                }

                string prefabPth = AssetDatabase.GetAssetPath(mom.resultPrefab);
                if (prefabPth == null || prefabPth.Length == 0)
                {
                    Debug.LogError("Could not save result to prefab. Result Prefab value is not a project asset. Is it an instance in the scene?");
                    return(false);
                }
            }
        }

        {
            // Find or create texture bake results
            MB3_TextureBaker tb = mom.GetComponentInParent <MB3_TextureBaker>();
            if (mom.textureBakeResults == null && tb != null)
            {
                mom.textureBakeResults = tb.textureBakeResults;
            }

            if (mom.textureBakeResults == null)
            {
                if (_OkToCreateDummyTextureBakeResult(mom))
                {
                    createdDummyTextureBakeResults = true;
                    List <GameObject> gos = mom.GetObjectsToCombine();
                    if (mom.GetNumObjectsInCombined() > 0)
                    {
                        if (mom.clearBuffersAfterBake)
                        {
                            mom.ClearMesh();
                        }
                        else
                        {
                            Debug.LogError("'Texture Bake Result' must be set to add more objects to a combined mesh that already contains objects. Try enabling 'clear buffers after bake'");
                            return(false);
                        }
                    }
                    mom.textureBakeResults = MB2_TextureBakeResults.CreateForMaterialsOnRenderer(gos.ToArray(), mom.meshCombiner.GetMaterialsOnTargetRenderer());
                    if (mom.meshCombiner.LOG_LEVEL >= MB2_LogLevel.debug)
                    {
                        Debug.Log("'Texture Bake Result' was not set. Creating a temporary one. Each material will be mapped to a separate submesh.");
                    }
                }
            }
        }

        // Second level of validation now that TextureBakeResults exists.
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.sceneObjOnly, new MB3_EditorMethods(), vl))
        {
            return(false);
        }

        // Add Delete Game Objects
        bool success;

        if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoSceneObject)
        {
            success = _BakeIntoCombinedSceneObject(mom, createdDummyTextureBakeResults, ref so);
        }
        else if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab)
        {
            success = _BakeIntoCombinedPrefab(mom, createdDummyTextureBakeResults, ref so);
        }
        else
        {
            Debug.LogError("Should be impossible.");
            success = false;
        }

        if (mom.clearBuffersAfterBake)
        {
            mom.meshCombiner.ClearBuffers();
        }
        if (createdDummyTextureBakeResults)
        {
            MB_Utility.Destroy(mom.textureBakeResults);
        }
        return(success);
    }
    public static bool BakeIntoCombined(MB3_MeshBakerCommon mom)
    {
        MB2_OutputOptions prefabOrSceneObject = mom.meshCombiner.outputOption;

        if (MB3_MeshCombiner.EVAL_VERSION && prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab)
        {
            Debug.LogError("Cannot BakeIntoPrefab with evaluation version.");
            return(false);
        }
        if (prefabOrSceneObject != MB2_OutputOptions.bakeIntoPrefab && prefabOrSceneObject != MB2_OutputOptions.bakeIntoSceneObject)
        {
            Debug.LogError("Paramater prefabOrSceneObject must be bakeIntoPrefab or bakeIntoSceneObject");
            return(false);
        }

        MB3_TextureBaker tb = mom.GetComponent <MB3_TextureBaker>();

        if (mom.textureBakeResults == null && tb != null)
        {
            mom.textureBakeResults = tb.textureBakeResults;
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.sceneObjOnly, new MB3_EditorMethods(), vl))
        {
            return(false);
        }
        if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab &&
            mom.resultPrefab == null)
        {
            Debug.LogError("Need to set the Combined Mesh Prefab field. Create a prefab asset, drag an empty game object into it, and drag it to the 'Combined Mesh Prefab' field.");
            return(false);
        }
        if (mom.meshCombiner.resultSceneObject != null &&
            (PrefabUtility.GetPrefabType(mom.meshCombiner.resultSceneObject) == PrefabType.ModelPrefab ||
             PrefabUtility.GetPrefabType(mom.meshCombiner.resultSceneObject) == PrefabType.Prefab))
        {
            Debug.LogWarning("Result Game Object was a project asset not a scene object instance. Clearing this field.");
            mom.meshCombiner.resultSceneObject = null;
        }

        mom.ClearMesh();
        if (mom.AddDeleteGameObjects(mom.GetObjectsToCombine().ToArray(), null, false))
        {
            mom.Apply(Unwrapping.GenerateSecondaryUVSet);
            Debug.Log(String.Format("Successfully baked {0} meshes", mom.GetObjectsToCombine().Count));
            if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoSceneObject)
            {
                PrefabType pt = PrefabUtility.GetPrefabType(mom.meshCombiner.resultSceneObject);
                if (pt == PrefabType.Prefab || pt == PrefabType.ModelPrefab)
                {
                    Debug.LogError("Combined Mesh Object is a prefab asset. If output option bakeIntoSceneObject then this must be an instance in the scene.");
                    return(false);
                }
            }
            else if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab)
            {
                string prefabPth = AssetDatabase.GetAssetPath(mom.resultPrefab);
                if (prefabPth == null || prefabPth.Length == 0)
                {
                    Debug.LogError("Could not save result to prefab. Result Prefab value is not an Asset.");
                    return(false);
                }
                string baseName    = Path.GetFileNameWithoutExtension(prefabPth);
                string folderPath  = prefabPth.Substring(0, prefabPth.Length - baseName.Length - 7);
                string newFilename = folderPath + baseName + "-mesh";
                SaveMeshsToAssetDatabase(mom, folderPath, newFilename);

                if (mom.meshCombiner.renderType == MB_RenderType.skinnedMeshRenderer)
                {
                    Debug.LogWarning("Render type is skinned mesh renderer. " +
                                     "Can't create prefab until all bones have been added to the combined mesh object " + mom.resultPrefab +
                                     " Add the bones then drag the combined mesh object to the prefab.");
                }
                else
                {
                    RebuildPrefab(mom);
                }
            }
            else
            {
                Debug.LogError("Unknown parameter");
                return(false);
            }
        }
        return(true);
    }
Exemplo n.º 5
0
        void bake(MB3_MeshBakerCommon mom)
        {
            bool createdDummyTextureBakeResults = false;

            try{
                if (mom.textureBakeResults == null)
                {
                    if (_OkToCreateDummyTextureBakeResult(mom))
                    {
                        createdDummyTextureBakeResults = true;
                        List <GameObject> gos = mom.GetObjectsToCombine();
                        mom.textureBakeResults = MB2_TextureBakeResults.CreateForMaterialsOnRenderer(MB_Utility.GetRenderer(gos[0]));
                    }
                }
                if (mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoSceneObject)
                {
                    MB3_MeshBakerEditorFunctions.BakeIntoCombined(mom);
                }
                else if (mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoPrefab)
                {
                    MB3_MeshBakerEditorFunctions.BakeIntoCombined(mom);
                }
                else
                {
                    if (mom is MB3_MeshBaker)
                    {
                        if (MB3_MeshCombiner.EVAL_VERSION)
                        {
                            Debug.LogError("Bake Meshes In Place is disabled in the evaluation version.");
                        }
                        else
                        {
                            MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;
                            if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.prefabOnly, new MB3_EditorMethods(), vl))
                            {
                                return;
                            }

                            List <GameObject> objsToMesh = mom.GetObjectsToCombine();
                            //objsToMesh = mom.GetComponent<MB3_TextureBaker>().GetObjectsToCombine();
                            MB3_BakeInPlace.BakeMeshesInPlace((MB3_MeshCombinerSingle)((MB3_MeshBaker)mom).meshCombiner, objsToMesh, mom.bakeAssetsInPlaceFolderPath, updateProgressBar);
                        }
                    }
                    else
                    {
                        Debug.LogError("Multi-mesh Baker components cannot be used for Bake In Place. Use an ordinary Mesh Baker object instead.");
                    }
                }
                if (mom.clearBuffersAfterBake)
                {
                    mom.meshCombiner.ClearBuffers();
                }
            } catch (Exception e) {
                Debug.LogError(e);
            } finally {
                if (createdDummyTextureBakeResults)
                {
                    GameObject.DestroyImmediate(mom.textureBakeResults);
                    mom.textureBakeResults = null;
                }
                EditorUtility.ClearProgressBar();
            }
        }
Exemplo n.º 6
0
    private IEnumerator _CreateAtlasesCoroutine(ProgressUpdateDelegate progressInfo, MB3_TextureCombiner.CreateAtlasesCoroutineResult coroutineResult, bool saveAtlasesAsAssets = false, MB2_EditorMethodsInterface editorMethods = null, float maxTimePerFrame = .01f)
    {
        MBVersionConcrete mbv = new MBVersionConcrete();

        if (!MB3_TextureCombiner._RunCorutineWithoutPauseIsRunning && (mbv.GetMajorVersion() < 5 || (mbv.GetMajorVersion() == 5 && mbv.GetMinorVersion() < 3)))
        {
            Debug.LogError("Running the texture combiner as a coroutine only works in Unity 5.3 and higher");
            coroutineResult.success = false;
            yield break;
        }
        this.OnCombinedTexturesCoroutineAtlasesAndRects = null;

        if (maxTimePerFrame <= 0f)
        {
            Debug.LogError("maxTimePerFrame must be a value greater than zero");
            coroutineResult.isFinished = true;
            yield break;
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!DoCombinedValidate(this, MB_ObjsToCombineTypes.dontCare, null, vl))
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        if (_doMultiMaterial && !_ValidateResultMaterials())
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        else if (resultType == MB2_TextureBakeResults.ResultType.textureArray)
        {
            //TODO validate texture arrays.
        }
        else if (!_doMultiMaterial)
        {
            if (_resultMaterial == null)
            {
                Debug.LogError("Combined Material is null please create and assign a result material.");
                coroutineResult.isFinished = true;
                yield break;
            }
            Shader targShader = _resultMaterial.shader;
            for (int i = 0; i < objsToMesh.Count; i++)
            {
                Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
                for (int j = 0; j < ms.Length; j++)
                {
                    Material m = ms[j];
                    if (m != null && m.shader != targShader)
                    {
                        Debug.LogWarning("Game object " + objsToMesh[i] + " does not use shader " + targShader + " it may not have the required textures. If not small solid color textures will be generated.");
                    }
                }
            }
        }

        MB3_TextureCombiner combiner = CreateAndConfigureTextureCombiner();

        combiner.saveAtlasesAsAssets = saveAtlasesAsAssets;

        OnCombinedTexturesCoroutineAtlasesAndRects = null;
        if (resultType == MB2_TextureBakeResults.ResultType.textureArray)
        {
            yield return(_CreateAtlasesCoroutineTextureArray(combiner, progressInfo, coroutineResult, saveAtlasesAsAssets, editorMethods, maxTimePerFrame));

            if (!coroutineResult.success)
            {
                yield break;
            }
        }
        else
        {
            yield return(_CreateAtlasesCoroutineAtlases(combiner, progressInfo, coroutineResult, saveAtlasesAsAssets, editorMethods, maxTimePerFrame));

            if (!coroutineResult.success)
            {
                yield break;
            }
        }

        //set the texture bake resultAtlasesAndRects on the Mesh Baker component if it exists
        MB3_MeshBakerCommon[] mb = GetComponentsInChildren <MB3_MeshBakerCommon>();
        for (int i = 0; i < mb.Length; i++)
        {
            mb[i].textureBakeResults = textureBakeResults;
        }

        coroutineResult.isFinished = true;
    }
    public static bool BakeIntoCombined(MB3_MeshBakerCommon mom, out bool createdDummyTextureBakeResults)
    {
		MB2_OutputOptions prefabOrSceneObject = mom.meshCombiner.outputOption;
        createdDummyTextureBakeResults = false;
        if (MB3_MeshCombiner.EVAL_VERSION && prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab){
			Debug.LogError("Cannot BakeIntoPrefab with evaluation version.");
			return false;
		}
		if (prefabOrSceneObject != MB2_OutputOptions.bakeIntoPrefab && prefabOrSceneObject != MB2_OutputOptions.bakeIntoSceneObject){
			Debug.LogError("Paramater prefabOrSceneObject must be bakeIntoPrefab or bakeIntoSceneObject");
			return false;
		}

		MB3_TextureBaker tb = mom.GetComponentInParent<MB3_TextureBaker>();
		if (mom.textureBakeResults == null && tb != null){
			mom.textureBakeResults = tb.textureBakeResults;	
		}
        if (mom.textureBakeResults == null)
        {
            if (_OkToCreateDummyTextureBakeResult(mom))
            {
                createdDummyTextureBakeResults = true;
                List<GameObject> gos = mom.GetObjectsToCombine();
                if (mom.GetNumObjectsInCombined() > 0)
                {
                    Debug.LogError("'Texture Bake Result' must be set to add more objects to a combined mesh that already contains objects. Try enabling 'clear buffers after bake'");
                    return false;
                }
                mom.textureBakeResults = MB2_TextureBakeResults.CreateForMaterialsOnRenderer(gos.ToArray(), mom.meshCombiner.GetMaterialsOnTargetRenderer());
                if (mom.meshCombiner.LOG_LEVEL >= MB2_LogLevel.debug) { Debug.Log("'Texture Bake Result' was not set. Creating a temporary one. Each material will be mapped to a separate submesh."); }
            }
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust; 
		if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.sceneObjOnly, new MB3_EditorMethods(),vl)) return false;	
		if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab && 
			mom.resultPrefab == null){
			Debug.LogError("Need to set the Combined Mesh Prefab field. Create a prefab asset, drag an empty game object into it, and drag it to the 'Combined Mesh Prefab' field.");
			return false;
		}
		if (mom.meshCombiner.resultSceneObject != null &&
						(PrefabUtility.GetPrefabType (mom.meshCombiner.resultSceneObject) == PrefabType.ModelPrefab ||
						PrefabUtility.GetPrefabType (mom.meshCombiner.resultSceneObject) == PrefabType.Prefab)) {
			Debug.LogWarning("Result Game Object was a project asset not a scene object instance. Clearing this field.");
			mom.meshCombiner.resultSceneObject = null;
		}

		mom.ClearMesh();
		if (mom.AddDeleteGameObjects(mom.GetObjectsToCombine().ToArray(),null,false)){
			mom.Apply( UnwrapUV2 );
            if (createdDummyTextureBakeResults)
            {
                Debug.Log(String.Format("Successfully baked {0} meshes each material is mapped to its own submesh.", mom.GetObjectsToCombine().Count));
            } else
            {
                Debug.Log(String.Format("Successfully baked {0} meshes", mom.GetObjectsToCombine().Count));
            }

            
			if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoSceneObject){
				PrefabType pt = PrefabUtility.GetPrefabType(mom.meshCombiner.resultSceneObject);
				if (pt == PrefabType.Prefab || pt == PrefabType.ModelPrefab){
					Debug.LogError("Combined Mesh Object is a prefab asset. If output option bakeIntoSceneObject then this must be an instance in the scene.");
					return false;
				}
			} else if (prefabOrSceneObject == MB2_OutputOptions.bakeIntoPrefab){
				string prefabPth = AssetDatabase.GetAssetPath(mom.resultPrefab);
				if (prefabPth == null || prefabPth.Length == 0){
					Debug.LogError("Could not save result to prefab. Result Prefab value is not an Asset.");
					return false;
				}
				string baseName = Path.GetFileNameWithoutExtension(prefabPth);
				string folderPath = prefabPth.Substring(0,prefabPth.Length - baseName.Length - 7);		
				string newFilename = folderPath + baseName + "-mesh";
				SaveMeshsToAssetDatabase(mom, folderPath,newFilename);
				
				if (mom.meshCombiner.renderType == MB_RenderType.skinnedMeshRenderer){
					Debug.LogWarning("Render type is skinned mesh renderer. " +
							"Can't create prefab until all bones have been added to the combined mesh object " + mom.resultPrefab + 
							" Add the bones then drag the combined mesh object to the prefab.");	
					
				} else {
					RebuildPrefab(mom);
				}
			} else {
				Debug.LogError("Unknown parameter");
				return false;
			}
		}
		return true;
	}
Exemplo n.º 8
0
    public IEnumerator CreateAtlasesCoroutine(ProgressUpdateDelegate progressInfo, CreateAtlasesCoroutineResult coroutineResult, bool saveAtlasesAsAssets = false, MB2_EditorMethodsInterface editorMethods = null, float maxTimePerFrame = .01f)
    {
        MBVersionConcrete mbv = new MBVersionConcrete();

        if (!MB3_TextureCombiner._RunCorutineWithoutPauseIsRunning && (mbv.GetMajorVersion() < 5 || (mbv.GetMajorVersion() == 5 && mbv.GetMinorVersion() < 3)))
        {
            Debug.LogError("Running the texture combiner as a coroutine only works in Unity 5.3 and higher");
            yield return(null);
        }
        this.OnCombinedTexturesCoroutineAtlasesAndRects = null;
        //if (!Application.isPlaying)
        //{
        //    Debug.LogError("CombineTexturesIntoAtlasesCoroutine should only be called when the game is running. Use CombineTexturesIntoAtlases in the editor.");
        //    _CreateAtlasesCoroutineIsFinished = true;
        //    yield break;
        //}
        if (maxTimePerFrame <= 0f)
        {
            Debug.LogError("maxTimePerFrame must be a value greater than zero");
            coroutineResult.isFinished = true;
            yield break;
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!DoCombinedValidate(this, MB_ObjsToCombineTypes.dontCare, null, vl))
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        if (_doMultiMaterial && !_ValidateResultMaterials())
        {
            coroutineResult.isFinished = true;
            yield break;
        }
        else if (!_doMultiMaterial)
        {
            if (_resultMaterial == null)
            {
                Debug.LogError("Combined Material is null please create and assign a result material.");
                coroutineResult.isFinished = true;
                yield break;
            }
            Shader targShader = _resultMaterial.shader;
            for (int i = 0; i < objsToMesh.Count; i++)
            {
                Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
                for (int j = 0; j < ms.Length; j++)
                {
                    Material m = ms[j];
                    if (m != null && m.shader != targShader)
                    {
                        Debug.LogWarning("Game object " + objsToMesh[i] + " does not use shader " + targShader + " it may not have the required textures. If not small solid color textures will be generated.");
                    }
                }
            }
        }

        for (int i = 0; i < objsToMesh.Count; i++)
        {
            Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
            for (int j = 0; j < ms.Length; j++)
            {
                Material m = ms[j];
                if (m == null)
                {
                    Debug.LogError("Game object " + objsToMesh[i] + " has a null material. Can't build atlases");
                    coroutineResult.isFinished = true;
                    yield break;
                }
            }
        }

        MB3_TextureCombiner combiner = new MB3_TextureCombiner();

        combiner.LOG_LEVEL             = LOG_LEVEL;
        combiner.atlasPadding          = _atlasPadding;
        combiner.maxAtlasSize          = _maxAtlasSize;
        combiner.customShaderPropNames = _customShaderProperties;
        combiner.fixOutOfBoundsUVs     = _fixOutOfBoundsUVs;
        combiner.maxTilingBakeSize     = _maxTilingBakeSize;
        combiner.packingAlgorithm      = _packingAlgorithm;
        combiner.meshBakerTexturePackerForcePowerOfTwo = _meshBakerTexturePackerForcePowerOfTwo;
        combiner.resizePowerOfTwoTextures     = _resizePowerOfTwoTextures;
        combiner.saveAtlasesAsAssets          = saveAtlasesAsAssets;
        combiner.considerNonTextureProperties = _considerNonTextureProperties;

        //initialize structure to store results
        int numResults = 1;

        if (_doMultiMaterial)
        {
            numResults = resultMaterials.Length;
        }
        OnCombinedTexturesCoroutineAtlasesAndRects = new MB_AtlasesAndRects[numResults];
        for (int i = 0; i < OnCombinedTexturesCoroutineAtlasesAndRects.Length; i++)
        {
            OnCombinedTexturesCoroutineAtlasesAndRects[i] = new MB_AtlasesAndRects();
        }

        //Do the material combining.
        for (int i = 0; i < OnCombinedTexturesCoroutineAtlasesAndRects.Length; i++)
        {
            Material        resMatToPass = null;
            List <Material> sourceMats   = null;
            if (_doMultiMaterial)
            {
                sourceMats   = resultMaterials[i].sourceMaterials;
                resMatToPass = resultMaterials[i].combinedMaterial;
            }
            else
            {
                resMatToPass = _resultMaterial;
            }
            Debug.Log(string.Format("Creating atlases for result material {0} using shader {1}", resMatToPass, resMatToPass.shader));
            MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult coroutineResult2 = new MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult();
            yield return(combiner.CombineTexturesIntoAtlasesCoroutine(progressInfo, OnCombinedTexturesCoroutineAtlasesAndRects[i], resMatToPass, objsToMesh, sourceMats, editorMethods, coroutineResult2, maxTimePerFrame));

            coroutineResult.success = coroutineResult2.success;
            if (!coroutineResult.success)
            {
                coroutineResult.isFinished = true;
                yield break;
            }
        }

        //Save the results
        textureBakeResults.combinedMaterialInfo = OnCombinedTexturesCoroutineAtlasesAndRects;
        textureBakeResults.doMultiMaterial      = _doMultiMaterial;
        textureBakeResults.resultMaterial       = _resultMaterial;
        textureBakeResults.resultMaterials      = resultMaterials;
        textureBakeResults.fixOutOfBoundsUVs    = combiner.fixOutOfBoundsUVs;
        unpackMat2RectMap(textureBakeResults);

        //set the texture bake resultAtlasesAndRects on the Mesh Baker component if it exists
        MB3_MeshBakerCommon[] mb = GetComponentsInChildren <MB3_MeshBakerCommon>();
        for (int i = 0; i < mb.Length; i++)
        {
            mb[i].textureBakeResults = textureBakeResults;
        }

        if (LOG_LEVEL >= MB2_LogLevel.info)
        {
            Debug.Log("Created Atlases");
        }

        coroutineResult.isFinished = true;
        if (coroutineResult.success && onBuiltAtlasesSuccess != null)
        {
            onBuiltAtlasesSuccess();
        }
        if (!coroutineResult.success && onBuiltAtlasesFail != null)
        {
            onBuiltAtlasesFail();
        }
    }
Exemplo n.º 9
0
    public static bool DoCombinedValidate(MB3_MeshBakerRoot mom, MB_ObjsToCombineTypes objToCombineType, MB2_EditorMethodsInterface editorMethods, MB2_ValidationLevel validationLevel)
    {
        if (mom.textureBakeResults == null)
        {
            Debug.LogError("Need to set Texture Bake Result on " + mom);
            return(false);
        }
        if (mom is MB3_MeshBakerCommon)
        {
            MB3_MeshBakerCommon momMB = (MB3_MeshBakerCommon)mom;
            MB3_TextureBaker    tb    = momMB.GetTextureBaker();
            if (tb != null && tb.textureBakeResults != mom.textureBakeResults)
            {
                Debug.LogWarning("Texture Bake Result on this component is not the same as the Texture Bake Result on the MB3_TextureBaker.");
            }
        }

        Dictionary <int, MB_Utility.MeshAnalysisResult> meshAnalysisResultCache = null;

        if (validationLevel == MB2_ValidationLevel.robust)
        {
            meshAnalysisResultCache = new Dictionary <int, MB_Utility.MeshAnalysisResult>();
        }
        List <GameObject> objsToMesh = mom.GetObjectsToCombine();

        for (int i = 0; i < objsToMesh.Count; i++)
        {
            GameObject go = objsToMesh[i];
            if (go == null)
            {
                Debug.LogError("The list of objects to combine contains a null at position." + i + " Select and use [shift] delete to remove");
                return(false);
            }
            for (int j = i + 1; j < objsToMesh.Count; j++)
            {
                if (objsToMesh[i] == objsToMesh[j])
                {
                    Debug.LogError("The list of objects to combine contains duplicates at " + i + " and " + j);
                    return(false);
                }
            }
            if (MB_Utility.GetGOMaterials(go).Length == 0)
            {
                Debug.LogError("Object " + go + " in the list of objects to be combined does not have a material");
                return(false);
            }
            Mesh m = MB_Utility.GetMesh(go);
            if (m == null)
            {
                Debug.LogError("Object " + go + " in the list of objects to be combined does not have a mesh");
                return(false);
            }
            if (m != null)              //This check can be very expensive and it only warns so only do this if we are in the editor.
            {
                if (!Application.isEditor &&
                    Application.isPlaying &&
                    mom.textureBakeResults.doMultiMaterial &&
                    validationLevel >= MB2_ValidationLevel.robust)
                {
                    MB_Utility.MeshAnalysisResult mar;
                    if (!meshAnalysisResultCache.TryGetValue(m.GetInstanceID(), out mar))
                    {
                        MB_Utility.doSubmeshesShareVertsOrTris(m, ref mar);
                        meshAnalysisResultCache.Add(m.GetInstanceID(), mar);
                    }
                    if (mar.hasOverlappingSubmeshVerts)
                    {
                        Debug.LogWarning("Object " + objsToMesh[i] + " in the list of objects to combine has overlapping submeshes (submeshes share vertices). If the UVs associated with the shared vertices are important then this bake may not work. If you are using multiple materials then this object can only be combined with objects that use the exact same set of textures (each atlas contains one texture). There may be other undesirable side affects as well. Mesh Master, available in the asset store can fix overlapping submeshes.");
                    }
                }
            }
        }


        List <GameObject> objs = objsToMesh;

        if (mom is MB3_MeshBaker)
        {
            objs = mom.GetObjectsToCombine();
            //if (((MB3_MeshBaker)mom).useObjsToMeshFromTexBaker && tb != null) objs = tb.GetObjectsToCombine();
            if (objs == null || objs.Count == 0)
            {
                Debug.LogError("No meshes to combine. Please assign some meshes to combine.");
                return(false);
            }
            if (mom is MB3_MeshBaker && ((MB3_MeshBaker)mom).meshCombiner.settings.renderType == MB_RenderType.skinnedMeshRenderer)
            {
                if (!editorMethods.ValidateSkinnedMeshes(objs))
                {
                    return(false);
                }
            }
        }

        if (editorMethods != null)
        {
            editorMethods.CheckPrefabTypes(objToCombineType, objsToMesh);
        }
        return(true);
    }
Exemplo n.º 10
0
    MB_AtlasesAndRects[] _CreateAtlases(ProgressUpdateDelegate progressInfo, bool saveAtlasesAsAssets = false, MB2_EditorMethodsInterface editorMethods = null)
    {
        //validation
        if (saveAtlasesAsAssets && editorMethods == null)
        {
            Debug.LogError("Error in CreateAtlases If saveAtlasesAsAssets = true then editorMethods cannot be null.");
            return(null);
        }
        if (saveAtlasesAsAssets && !Application.isEditor)
        {
            Debug.LogError("Error in CreateAtlases If saveAtlasesAsAssets = true it must be called from the Unity Editor.");
            return(null);
        }
        MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;

        if (!DoCombinedValidate(this, MB_ObjsToCombineTypes.dontCare, editorMethods, vl))
        {
            return(null);
        }
        if (_doMultiMaterial && !_ValidateResultMaterials())
        {
            return(null);
        }
        else if (!_doMultiMaterial)
        {
            if (_resultMaterial == null)
            {
                Debug.LogError("Combined Material is null please create and assign a result material.");
                return(null);
            }
            Shader targShader = _resultMaterial.shader;
            for (int i = 0; i < objsToMesh.Count; i++)
            {
                Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
                for (int j = 0; j < ms.Length; j++)
                {
                    Material m = ms[j];
                    if (m != null && m.shader != targShader)
                    {
                        Debug.LogWarning("Game object " + objsToMesh[i] + " does not use shader " + targShader + " it may not have the required textures. If not 2x2 clear textures will be generated.");
                    }
                }
            }
        }

        for (int i = 0; i < objsToMesh.Count; i++)
        {
            Material[] ms = MB_Utility.GetGOMaterials(objsToMesh[i]);
            for (int j = 0; j < ms.Length; j++)
            {
                Material m = ms[j];
                if (m == null)
                {
                    Debug.LogError("Game object " + objsToMesh[i] + " has a null material. Can't build atlases");
                    return(null);
                }
            }
        }

        MB3_TextureCombiner combiner = new MB3_TextureCombiner();

        combiner.LOG_LEVEL             = LOG_LEVEL;
        combiner.atlasPadding          = _atlasPadding;
        combiner.maxAtlasSize          = _maxAtlasSize;
        combiner.customShaderPropNames = _customShaderProperties;
        combiner.fixOutOfBoundsUVs     = _fixOutOfBoundsUVs;
        combiner.maxTilingBakeSize     = _maxTilingBakeSize;
        combiner.packingAlgorithm      = _packingAlgorithm;
        combiner.meshBakerTexturePackerForcePowerOfTwo = _meshBakerTexturePackerForcePowerOfTwo;
        combiner.resizePowerOfTwoTextures = _resizePowerOfTwoTextures;
        combiner.saveAtlasesAsAssets      = saveAtlasesAsAssets;

        // if editor analyse meshes and suggest treatment
        if (!Application.isPlaying)
        {
            Material[] rms;
            if (_doMultiMaterial)
            {
                rms = new Material[resultMaterials.Length];
                for (int i = 0; i < rms.Length; i++)
                {
                    rms[i] = resultMaterials[i].combinedMaterial;
                }
            }
            else
            {
                rms    = new Material[1];
                rms[0] = _resultMaterial;
            }
            combiner.SuggestTreatment(objsToMesh, rms, combiner.customShaderPropNames);
        }

        //initialize structure to store results
        int numResults = 1;

        if (_doMultiMaterial)
        {
            numResults = resultMaterials.Length;
        }
        MB_AtlasesAndRects[] resultAtlasesAndRects = new MB_AtlasesAndRects[numResults];
        for (int i = 0; i < resultAtlasesAndRects.Length; i++)
        {
            resultAtlasesAndRects[i] = new MB_AtlasesAndRects();
        }

        //Do the material combining.
        for (int i = 0; i < resultAtlasesAndRects.Length; i++)
        {
            Material        resMatToPass = null;
            List <Material> sourceMats   = null;
            if (_doMultiMaterial)
            {
                sourceMats   = resultMaterials[i].sourceMaterials;
                resMatToPass = resultMaterials[i].combinedMaterial;
            }
            else
            {
                resMatToPass = _resultMaterial;
            }
            Debug.Log("Creating atlases for result material " + resMatToPass);
            if (!combiner.CombineTexturesIntoAtlases(progressInfo, resultAtlasesAndRects[i], resMatToPass, objsToMesh, sourceMats, editorMethods))
            {
                return(null);
            }
        }

        //Save the results
        textureBakeResults.combinedMaterialInfo = resultAtlasesAndRects;
        textureBakeResults.doMultiMaterial      = _doMultiMaterial;
        textureBakeResults.resultMaterial       = _resultMaterial;
        textureBakeResults.resultMaterials      = resultMaterials;
        textureBakeResults.fixOutOfBoundsUVs    = combiner.fixOutOfBoundsUVs;
        unpackMat2RectMap(textureBakeResults);

        //set the texture bake resultAtlasesAndRects on the Mesh Baker component if it exists
        MB3_MeshBakerCommon[] mb = GetComponentsInChildren <MB3_MeshBakerCommon>();
        for (int i = 0; i < mb.Length; i++)
        {
            mb[i].textureBakeResults = textureBakeResults;
        }

        if (LOG_LEVEL >= MB2_LogLevel.info)
        {
            Debug.Log("Created Atlases");
        }
        return(resultAtlasesAndRects);
    }
Exemplo n.º 11
0
    private MB_AtlasesAndRects[] _CreateAtlases(ProgressUpdateDelegate progressInfo, bool saveAtlasesAsAssets = false, MB2_EditorMethodsInterface editorMethods = null)
    {
        if (saveAtlasesAsAssets && editorMethods == null)
        {
            Debug.LogError("Error in CreateAtlases If saveAtlasesAsAssets = true then editorMethods cannot be null.");
            return(null);
        }
        if (saveAtlasesAsAssets && !Application.isEditor)
        {
            Debug.LogError("Error in CreateAtlases If saveAtlasesAsAssets = true it must be called from the Unity Editor.");
            return(null);
        }
        MB2_ValidationLevel validationLevel = (!Application.isPlaying) ? MB2_ValidationLevel.robust : MB2_ValidationLevel.quick;

        if (!MB3_MeshBakerRoot.DoCombinedValidate(this, MB_ObjsToCombineTypes.dontCare, editorMethods, validationLevel))
        {
            return(null);
        }
        if (this._doMultiMaterial && !this._ValidateResultMaterials())
        {
            return(null);
        }
        if (!this._doMultiMaterial)
        {
            if (this._resultMaterial == null)
            {
                Debug.LogError("Combined Material is null please create and assign a result material.");
                return(null);
            }
            Shader shader = this._resultMaterial.shader;
            for (int i = 0; i < this.objsToMesh.Count; i++)
            {
                foreach (Material material in MB_Utility.GetGOMaterials(this.objsToMesh[i]))
                {
                    if (material != null && material.shader != shader)
                    {
                        Debug.LogWarning(string.Concat(new object[]
                        {
                            "Game object ",
                            this.objsToMesh[i],
                            " does not use shader ",
                            shader,
                            " it may not have the required textures. If not 2x2 clear textures will be generated."
                        }));
                    }
                }
            }
        }
        for (int k = 0; k < this.objsToMesh.Count; k++)
        {
            foreach (Material x in MB_Utility.GetGOMaterials(this.objsToMesh[k]))
            {
                if (x == null)
                {
                    Debug.LogError("Game object " + this.objsToMesh[k] + " has a null material. Can't build atlases");
                    return(null);
                }
            }
        }
        MB3_TextureCombiner mb3_TextureCombiner = new MB3_TextureCombiner();

        mb3_TextureCombiner.LOG_LEVEL             = this.LOG_LEVEL;
        mb3_TextureCombiner.atlasPadding          = this._atlasPadding;
        mb3_TextureCombiner.maxAtlasSize          = this._maxAtlasSize;
        mb3_TextureCombiner.customShaderPropNames = this._customShaderProperties;
        mb3_TextureCombiner.fixOutOfBoundsUVs     = this._fixOutOfBoundsUVs;
        mb3_TextureCombiner.maxTilingBakeSize     = this._maxTilingBakeSize;
        mb3_TextureCombiner.packingAlgorithm      = this._packingAlgorithm;
        mb3_TextureCombiner.meshBakerTexturePackerForcePowerOfTwo = this._meshBakerTexturePackerForcePowerOfTwo;
        mb3_TextureCombiner.resizePowerOfTwoTextures = this._resizePowerOfTwoTextures;
        mb3_TextureCombiner.saveAtlasesAsAssets      = saveAtlasesAsAssets;
        if (!Application.isPlaying)
        {
            Material[] array;
            if (this._doMultiMaterial)
            {
                array = new Material[this.resultMaterials.Length];
                for (int m = 0; m < array.Length; m++)
                {
                    array[m] = this.resultMaterials[m].combinedMaterial;
                }
            }
            else
            {
                array = new Material[]
                {
                    this._resultMaterial
                };
            }
            mb3_TextureCombiner.SuggestTreatment(this.objsToMesh, array, mb3_TextureCombiner.customShaderPropNames);
        }
        int num = 1;

        if (this._doMultiMaterial)
        {
            num = this.resultMaterials.Length;
        }
        MB_AtlasesAndRects[] array2 = new MB_AtlasesAndRects[num];
        for (int n = 0; n < array2.Length; n++)
        {
            array2[n] = new MB_AtlasesAndRects();
        }
        for (int num2 = 0; num2 < array2.Length; num2++)
        {
            List <Material> allowedMaterialsFilter = null;
            Material        material2;
            if (this._doMultiMaterial)
            {
                allowedMaterialsFilter = this.resultMaterials[num2].sourceMaterials;
                material2 = this.resultMaterials[num2].combinedMaterial;
            }
            else
            {
                material2 = this._resultMaterial;
            }
            Debug.Log("Creating atlases for result material " + material2);
            if (!mb3_TextureCombiner.CombineTexturesIntoAtlases(progressInfo, array2[num2], material2, this.objsToMesh, allowedMaterialsFilter, editorMethods))
            {
                return(null);
            }
        }
        this.textureBakeResults.combinedMaterialInfo = array2;
        this.textureBakeResults.doMultiMaterial      = this._doMultiMaterial;
        this.textureBakeResults.resultMaterial       = this._resultMaterial;
        this.textureBakeResults.resultMaterials      = this.resultMaterials;
        this.textureBakeResults.fixOutOfBoundsUVs    = mb3_TextureCombiner.fixOutOfBoundsUVs;
        this.unpackMat2RectMap(this.textureBakeResults);
        MB3_MeshBakerCommon[] componentsInChildren = base.GetComponentsInChildren <MB3_MeshBakerCommon>();
        for (int num3 = 0; num3 < componentsInChildren.Length; num3++)
        {
            componentsInChildren[num3].textureBakeResults = this.textureBakeResults;
        }
        if (this.LOG_LEVEL >= MB2_LogLevel.info)
        {
            Debug.Log("Created Atlases");
        }
        return(array2);
    }
Exemplo n.º 12
0
	public static bool DoCombinedValidate(MB3_MeshBakerRoot mom, MB_ObjsToCombineTypes objToCombineType, MB2_EditorMethodsInterface editorMethods, MB2_ValidationLevel validationLevel){
		if (mom.textureBakeResults == null){
			Debug.LogError("Need to set Material Bake Result on " + mom);
			return false;
		}
		if (mom is MB3_MeshBakerCommon){
			MB3_MeshBakerCommon momMB = (MB3_MeshBakerCommon) mom;
			MB3_TextureBaker tb = momMB.GetTextureBaker();
			if (tb != null && tb.textureBakeResults != mom.textureBakeResults){
				Debug.LogWarning("Material Bake Result on this component is not the same as the Material Bake Result on the MB3_TextureBaker.");
			}
		}

		Dictionary<int,MB_Utility.MeshAnalysisResult> meshAnalysisResultCache = null;
		if (validationLevel == MB2_ValidationLevel.robust){
			meshAnalysisResultCache = new Dictionary<int, MB_Utility.MeshAnalysisResult>();
		}
		List<GameObject> objsToMesh = mom.GetObjectsToCombine();
		for (int i = 0; i < objsToMesh.Count; i++){
			GameObject go = objsToMesh[i];
			if (go == null){
				Debug.LogError("The list of objects to combine contains a null at position." + i + " Select and use [shift] delete to remove");
				return false;					
			}
			for (int j = i + 1; j < objsToMesh.Count; j++){
				if (objsToMesh[i] == objsToMesh[j]){
					Debug.LogError("The list of objects to combine contains duplicates at " + i + " and " + j);
					return false;	
				}
			}
			if (MB_Utility.GetGOMaterials(go) == null){
				Debug.LogError("Object " + go + " in the list of objects to be combined does not have a material");
				return false;
			}
			Mesh m = MB_Utility.GetMesh(go);
			if (m == null){
				Debug.LogError("Object " + go + " in the list of objects to be combined does not have a mesh");
				return false;
			}
			if (m != null){ //This check can be very expensive and it only warns so only do this if we are in the editor.
				if (!Application.isEditor && 
				    Application.isPlaying &&
					mom.textureBakeResults.doMultiMaterial && 
					validationLevel >= MB2_ValidationLevel.robust){
					MB_Utility.MeshAnalysisResult mar;
					if (!meshAnalysisResultCache.TryGetValue(m.GetInstanceID(),out mar)){
						MB_Utility.doSubmeshesShareVertsOrTris(m,ref mar);
						meshAnalysisResultCache.Add (m.GetInstanceID(),mar);
					}
					if (mar.hasOverlappingSubmeshVerts){
						Debug.LogWarning("Object " + objsToMesh[i] + " in the list of objects to combine has overlapping submeshes (submeshes share vertices). If the UVs associated with the shared vertices are important then this bake may not work. If you are using multiple materials then this object can only be combined with objects that use the exact same set of textures (each atlas contains one texture). There may be other undesirable side affects as well. Mesh Master, available in the asset store can fix overlapping submeshes.");	
					}
				}
			}
		}

		
		List<GameObject> objs = objsToMesh;
		
		if (mom is MB3_MeshBaker)
		{
			objs = mom.GetObjectsToCombine();
			//if (((MB3_MeshBaker)mom).useObjsToMeshFromTexBaker && tb != null) objs = tb.GetObjectsToCombine(); 
			if (objs == null || objs.Count == 0)
			{
				Debug.LogError("No meshes to combine. Please assign some meshes to combine.");
				return false;
			}
			if (mom is MB3_MeshBaker && ((MB3_MeshBaker)mom).meshCombiner.renderType == MB_RenderType.skinnedMeshRenderer){
				if (!editorMethods.ValidateSkinnedMeshes(objs))
				{
					return false;
				}
			}
		}
		
		if (editorMethods != null){
			editorMethods.CheckPrefabTypes(objToCombineType, objsToMesh);
		}
		return true;
	}
Exemplo n.º 13
0
    public static bool DoCombinedValidate(MB3_MeshBakerRoot mom, MB_ObjsToCombineTypes objToCombineType, MB2_EditorMethodsInterface editorMethods, MB2_ValidationLevel validationLevel)
    {
        if (mom.textureBakeResults == null)
        {
            Debug.LogError("Need to set Material Bake Result on " + mom);
            return(false);
        }
        if (mom is MB3_MeshBakerCommon)
        {
            MB3_MeshBakerCommon mb3_MeshBakerCommon = (MB3_MeshBakerCommon)mom;
            MB3_TextureBaker    textureBaker        = mb3_MeshBakerCommon.GetTextureBaker();
            if (textureBaker != null && textureBaker.textureBakeResults != mom.textureBakeResults)
            {
                Debug.LogWarning("Material Bake Result on this component is not the same as the Material Bake Result on the MB3_TextureBaker.");
            }
        }
        Dictionary <int, MB_Utility.MeshAnalysisResult> dictionary = null;

        if (validationLevel == MB2_ValidationLevel.robust)
        {
            dictionary = new Dictionary <int, MB_Utility.MeshAnalysisResult>();
        }
        List <GameObject> objectsToCombine = mom.GetObjectsToCombine();

        for (int i = 0; i < objectsToCombine.Count; i++)
        {
            GameObject gameObject = objectsToCombine[i];
            if (gameObject == null)
            {
                Debug.LogError("The list of objects to combine contains a null at position." + i + " Select and use [shift] delete to remove");
                return(false);
            }
            for (int j = i + 1; j < objectsToCombine.Count; j++)
            {
                if (objectsToCombine[i] == objectsToCombine[j])
                {
                    Debug.LogError(string.Concat(new object[]
                    {
                        "The list of objects to combine contains duplicates at ",
                        i,
                        " and ",
                        j
                    }));
                    return(false);
                }
            }
            if (MB_Utility.GetGOMaterials(gameObject) == null)
            {
                Debug.LogError("Object " + gameObject + " in the list of objects to be combined does not have a material");
                return(false);
            }
            Mesh mesh = MB_Utility.GetMesh(gameObject);
            if (mesh == null)
            {
                Debug.LogError("Object " + gameObject + " in the list of objects to be combined does not have a mesh");
                return(false);
            }
            if (mesh != null && !Application.isEditor && Application.isPlaying && mom.textureBakeResults.doMultiMaterial && validationLevel >= MB2_ValidationLevel.robust)
            {
                MB_Utility.MeshAnalysisResult value;
                if (!dictionary.TryGetValue(mesh.GetInstanceID(), out value))
                {
                    MB_Utility.doSubmeshesShareVertsOrTris(mesh, ref value);
                    dictionary.Add(mesh.GetInstanceID(), value);
                }
                if (value.hasOverlappingSubmeshVerts)
                {
                    Debug.LogWarning("Object " + objectsToCombine[i] + " in the list of objects to combine has overlapping submeshes (submeshes share vertices). If the UVs associated with the shared vertices are important then this bake may not work. If you are using multiple materials then this object can only be combined with objects that use the exact same set of textures (each atlas contains one texture). There may be other undesirable side affects as well. Mesh Master, available in the asset store can fix overlapping submeshes.");
                }
            }
        }
        if (mom is MB3_MeshBaker)
        {
            List <GameObject> objectsToCombine2 = mom.GetObjectsToCombine();
            if (objectsToCombine2 == null || objectsToCombine2.Count == 0)
            {
                Debug.LogError("No meshes to combine. Please assign some meshes to combine.");
                return(false);
            }
            if (mom is MB3_MeshBaker && ((MB3_MeshBaker)mom).meshCombiner.renderType == MB_RenderType.skinnedMeshRenderer && !editorMethods.ValidateSkinnedMeshes(objectsToCombine2))
            {
                return(false);
            }
        }
        if (editorMethods != null)
        {
            editorMethods.CheckPrefabTypes(objToCombineType, objectsToCombine);
        }
        return(true);
    }
Exemplo n.º 14
0
    public static bool DoCombinedValidate(MB3_MeshBakerRoot mom, MB_ObjsToCombineTypes objToCombineType, MB2_EditorMethodsInterface editorMethods, MB2_ValidationLevel validationLevel)
    {
        if (mom.textureBakeResults == null)
        {
            Debug.LogError("Need to set Texture Bake Result on " + mom);
            return(false);
        }
        if (mom is MB3_MeshBakerCommon)
        {
            MB3_MeshBakerCommon momMB = (MB3_MeshBakerCommon)mom;
            MB3_TextureBaker    tb    = momMB.GetTextureBaker();
            if (tb != null && tb.textureBakeResults != mom.textureBakeResults)
            {
                Debug.LogWarning("Texture Bake Result on this component is not the same as the Texture Bake Result on the MB3_TextureBaker.");
            }
        }

        Dictionary <int, MB_Utility.MeshAnalysisResult> meshAnalysisResultCache = null;

        if (validationLevel == MB2_ValidationLevel.robust)
        {
            meshAnalysisResultCache = new Dictionary <int, MB_Utility.MeshAnalysisResult>();
        }
        List <GameObject>             objsToMesh  = mom.GetObjectsToCombine();
        Dictionary <string, Material> matName2Mat = new Dictionary <string, Material>();

        for (int i = 0; i < objsToMesh.Count; i++)
        {
            GameObject go = objsToMesh[i];
            if (go == null)
            {
                Debug.LogError("The list of objects to combine contains a null at position." + i + " Select and use [shift] delete to remove");
                return(false);
            }
            for (int j = i + 1; j < objsToMesh.Count; j++)
            {
                if (objsToMesh[i] == objsToMesh[j])
                {
                    Debug.LogError("The list of objects to combine contains duplicates at " + i + " and " + j);
                    return(false);
                }
            }

            Material[] mats = MB_Utility.GetGOMaterials(go);
            if (mats.Length == 0)
            {
                Debug.LogError("Object " + go + " in the list of objects to be combined does not have a material");
                return(false);
            }
            Mesh m = MB_Utility.GetMesh(go);
            if (m == null)
            {
                Debug.LogError("Object " + go + " in the list of objects to be combined does not have a mesh");
                return(false);
            }
            if (m != null)              //This check can be very expensive and it only warns so only do this if we are in the editor.
            {
                if (!Application.isEditor &&
                    Application.isPlaying &&
                    mom.textureBakeResults.doMultiMaterial &&
                    validationLevel >= MB2_ValidationLevel.robust)
                {
                    MB_Utility.MeshAnalysisResult mar;
                    if (!meshAnalysisResultCache.TryGetValue(m.GetInstanceID(), out mar))
                    {
                        MB_Utility.doSubmeshesShareVertsOrTris(m, ref mar);
                        meshAnalysisResultCache.Add(m.GetInstanceID(), mar);
                    }
                    if (mar.hasOverlappingSubmeshVerts)
                    {
                        Debug.LogWarning("Object " + objsToMesh[i] + " in the list of objects to combine has overlapping submeshes (submeshes share vertices). If the UVs associated with the shared vertices are important then this bake may not work. If you are using multiple materials then this object can only be combined with objects that use the exact same set of textures (each atlas contains one texture). There may be other undesirable side affects as well. Mesh Master, available in the asset store can fix overlapping submeshes.");
                    }
                }
            }

            if (MBVersion.IsUsingAddressables())
            {
                HashSet <string> materialsWithDuplicateNames = new HashSet <string>();
                for (int matIdx = 0; matIdx < mats.Length; matIdx++)
                {
                    if (mats[matIdx] != null)
                    {
                        if (matName2Mat.ContainsKey(mats[matIdx].name))
                        {
                            if (mats[matIdx] != matName2Mat[mats[matIdx].name])
                            {
                                // This is an error. If using addressables we consider materials that have the same name to be the same material when baking at runtime.
                                // Two different material must NOT have the same name.
                                materialsWithDuplicateNames.Add(mats[matIdx].name);
                            }
                        }
                        else
                        {
                            matName2Mat.Add(mats[matIdx].name, mats[matIdx]);
                        }
                    }
                }

                if (materialsWithDuplicateNames.Count > 0)
                {
                    String[] stringArray = new String[materialsWithDuplicateNames.Count];
                    materialsWithDuplicateNames.CopyTo(stringArray);
                    string matsWithSameName = string.Join(",", stringArray);
                    Debug.LogError("The source objects use different materials that have the same name (" + matsWithSameName + "). " +
                                   "If using addressables, materials with the same name are considered to be the same material when baking meshes at runtime. " +
                                   "If you want to use this Material Bake Result at runtime then all source materials must have distinct names. Baking in edit-mode will still work.");
                }
            }
        }


        List <GameObject> objs = objsToMesh;

        if (mom is MB3_MeshBaker)
        {
            objs = mom.GetObjectsToCombine();
            //if (((MB3_MeshBaker)mom).useObjsToMeshFromTexBaker && tb != null) objs = tb.GetObjectsToCombine();
            if (objs == null || objs.Count == 0)
            {
                Debug.LogError("No meshes to combine. Please assign some meshes to combine.");
                return(false);
            }
            if (mom is MB3_MeshBaker && ((MB3_MeshBaker)mom).meshCombiner.settings.renderType == MB_RenderType.skinnedMeshRenderer)
            {
                if (!editorMethods.ValidateSkinnedMeshes(objs))
                {
                    return(false);
                }
            }
        }

        if (editorMethods != null)
        {
            editorMethods.CheckPrefabTypes(objToCombineType, objsToMesh);
        }
        return(true);
    }