コード例 #1
0
        public static void GenerateMesh(IvyGraph ivyGraph, IvyProfile ivyProfile, bool doUV2s = false, bool forceGeneration = false)
        {
            // avoid GC allocations by reusing static lists
            verticesAll.Clear();
            texCoordsAll.Clear();
            trianglesAll.Clear();
            leafVerticesAll.Clear();
            leafUVsAll.Clear();
            leafTrianglesAll.Clear();
            leafColorsAll.Clear();

            // the main mesh generation actually happens here; if it can't generate a mesh, then stop
            if (!GenerateMeshData(ivyGraph, ivyProfile, forceGeneration))
            {
                return;
            }
            ivyGraph.dirtyUV2s = !doUV2s;

            InitOrRefreshRoot(ivyGraph, ivyProfile);
            var myAsset = IvyCore.GetDataAsset(ivyGraph.rootGO);

            // Branch mesh debug
            // Debug.Log( "branchVertices: " + verticesAll.Count );
            // Debug.Log( "branchTris: " + string.Join(", ", trianglesAll.Select( tri => tri.ToString() ).ToArray()) );
            // foreach ( var vert in verticesAll ) {
            //     Debug.DrawRay( vert + ivyGraph.seedPos, Vector3.up, Color.cyan, 1f, false );
            // }

            if (ivyProfile.ivyBranchSize < 0.0001f)
            {
                if (ivyGraph.branchMF != null)
                {
                    IvyCore.DestroyObject(ivyGraph.branchMF.gameObject);
                }
                IvyCore.TryDestroyMesh(ivyGraph.branchMeshID, myAsset, true);
            }
            else
            {
                CheckMeshDataAsset(ref ivyGraph.branchMeshID, myAsset, ivyProfile.meshCompress);
                branchMesh = myAsset.meshList[ivyGraph.branchMeshID];

                if (ivyGraph.branchMF == null || ivyGraph.branchR == null)
                {
                    CreateIvyMeshObject(ivyGraph, ivyProfile, branchMesh, false);
                }
                RefreshMeshObject(ivyGraph.branchMF, ivyProfile);

                branchMesh.Clear();
                ivyGraph.branchMF.name             = ivyGraph.rootGO.name + "_Branches";
                ivyGraph.branchR.shadowCastingMode = ivyProfile.castShadows;
                ivyGraph.branchR.receiveShadows    = ivyProfile.receiveShadows;
                branchMesh.name = ivyGraph.branchMF.name;
                branchMesh.SetVertices(verticesAll);
                branchMesh.SetUVs(0, texCoordsAll);
                if (ivyProfile.useLightmapping && doUV2s)
                {
                    PackBranchUV2s(ivyGraph);
                }
                branchMesh.SetTriangles(trianglesAll, 0);
                branchMesh.RecalculateBounds();
                branchMesh.RecalculateNormals();
                branchMesh.RecalculateTangents();
                #if UNITY_2017_1_OR_NEWER && UNITY_EDITOR
                MeshUtility.Optimize(branchMesh);
                #endif
                ivyGraph.branchMF.sharedMesh = branchMesh;
#if UNITY_EDITOR
                ivyGraph.branchR.sharedMaterial = ivyProfile.branchMaterial != null ? ivyProfile.branchMaterial : AssetDatabase.GetBuiltinExtraResource <Material>("Default-Diffuse.mat");
#else
                ivyGraph.branchR.sharedMaterial = ivyProfile.branchMaterial;
#endif
            }

            // Leaves mesh debug
            // Debug.Log( "leafVertices: " + ivyGraph.leafVertices.Count );
            // Debug.Log( "leafTris: " + string.Join(", ", ivyGraph.leafTriangles.Select( tri => tri.ToString() ).ToArray()) );

            // don't do leaf mesh if it's unnecessary
            if (ivyProfile.leafProbability < 0.001f)
            {
                if (ivyGraph.leafMF != null)
                {
                    IvyCore.DestroyObject(ivyGraph.leafMF.gameObject);
                }
                IvyCore.TryDestroyMesh(ivyGraph.leafMeshID, myAsset, true);
            }
            else
            {
                CheckMeshDataAsset(ref ivyGraph.leafMeshID, myAsset, ivyProfile.meshCompress);
                leafMesh = myAsset.meshList[ivyGraph.leafMeshID];

                if (ivyGraph.leafMF == null || ivyGraph.leafR == null)
                {
                    CreateIvyMeshObject(ivyGraph, ivyProfile, leafMesh, true);
                }
                RefreshMeshObject(ivyGraph.leafMF, ivyProfile);

                leafMesh.Clear();
                ivyGraph.leafMF.name             = ivyGraph.rootGO.name + "_Leaves";
                ivyGraph.leafR.shadowCastingMode = ivyProfile.castShadows;
                ivyGraph.leafR.receiveShadows    = ivyProfile.receiveShadows;
                leafMesh.name = ivyGraph.leafMF.name;
                leafMesh.SetVertices(leafVerticesAll);
                leafMesh.SetUVs(0, leafUVsAll);
                if (ivyProfile.useLightmapping && doUV2s)
                {
                    PackLeafUV2s(ivyGraph);
                }
                leafMesh.SetTriangles(leafTrianglesAll, 0);
                if (ivyProfile.useVertexColors)
                {
                    leafMesh.SetColors(leafColorsAll);
                }
                leafMesh.RecalculateBounds();
                leafMesh.RecalculateNormals();
                leafMesh.RecalculateTangents();
#if UNITY_2017_1_OR_NEWER && UNITY_EDITOR
                MeshUtility.Optimize(leafMesh);
#endif
                ivyGraph.leafMF.sharedMesh = leafMesh;
#if UNITY_EDITOR
                ivyGraph.leafR.sharedMaterial = ivyProfile.leafMaterial != null ? ivyProfile.leafMaterial : AssetDatabase.GetBuiltinExtraResource <Material>("Default-Diffuse.mat");
#else
                ivyGraph.leafR.sharedMaterial = ivyProfile.leafMaterial;
#endif
            }
            // EditorUtility.SetDirty( myAsset );
            // AssetDatabase.SaveAssets();
            // AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath(myAsset) );
        }
        //called whenever the inspector gui gets rendered
        public override void OnInspectorGUI()
        {
            EditorGUILayout.Space();
            if (ivyBehavior == null)
            {
                ivyBehavior = (IvyBehavior)target;
            }
            wasPartOfPrefab = IvyCore.IsPartOfPrefab(ivyBehavior.gameObject);

            bool isInARealScene = !string.IsNullOrEmpty(ivyBehavior.gameObject.scene.path) && ivyBehavior.gameObject.activeInHierarchy;

            if (isInARealScene)
            {
                lastDataAsset = IvyCore.GetDataAsset(ivyBehavior.gameObject);
            }

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            EditorGUI.BeginChangeCheck();
            ivyBehavior.profileAsset = EditorGUILayout.ObjectField(ivyBehavior.profileAsset, typeof(IvyProfileAsset), false) as IvyProfileAsset;
            if (EditorGUI.EndChangeCheck() || (ivyProfileEditor == null && ivyBehavior.profileAsset != null))
            {
                ivyProfileEditor = Editor.CreateEditor(ivyBehavior.profileAsset);
                ((IvyProfileEditor)ivyProfileEditor).viewedFromMonobehavior = true;
            }

            // destroy old editor / cleanup
            if (ivyBehavior.profileAsset == null && ivyProfileEditor != null)
            {
                DestroyImmediate(ivyProfileEditor);
            }

            if (ivyBehavior.profileAsset == null || ivyProfileEditor == null)
            {
                EditorGUILayout.HelpBox("Please assign an Ivy Profile Asset.", MessageType.Warning);
                if (GUILayout.Button("Create new Ivy Profile Asset..."))
                {
                    var newAsset = IvyCore.CreateNewAsset("");
                    if (newAsset != null)
                    {
                        ivyBehavior.profileAsset       = newAsset;
                        ivyBehavior.showProfileFoldout = true;
                        Selection.activeGameObject     = ivyBehavior.gameObject;
                    }
                }
                EditorGUILayout.EndVertical();
                return;
            }

            var ivyProfile = ivyBehavior.profileAsset.ivyProfile;

            if (!IvyCore.ivyBehaviors.Contains(ivyBehavior))
            {
                IvyCore.ivyBehaviors.Add(ivyBehavior);
            }

            GUIContent content = null;

            EditorGUI.indentLevel++;
            ivyBehavior.showProfileFoldout = EditorGUILayout.Foldout(ivyBehavior.showProfileFoldout, "Ivy Profile Settings", true);
            EditorGUI.indentLevel--;
            if (EditorGUILayout.BeginFadeGroup(ivyBehavior.showProfileFoldout ? 1 : 0))
            {
                ivyProfileEditor.OnInspectorGUI();
            }
            EditorGUILayout.EndFadeGroup();
            EditorGUILayout.EndVertical();

            DrawUILine();
            GUILayout.Label("Ivy Painter", EditorStyles.boldLabel);

            if (!isInARealScene)
            {
                EditorGUILayout.HelpBox("Painting / mesh generation only works in saved scenes on active game objects.\n- Save the scene?\n- Put this game object in a saved scene?\n- Make sure it is active?", MessageType.Error);
                GUI.enabled = false;
            }

            // plant root creation button
            var oldColor = GUI.color;

            GUI.color = isPlantingModeActive ? Color.yellow : Color.Lerp(Color.yellow, oldColor, 0.69f);
            content   = new GUIContent(!isPlantingModeActive ? "  Start Painting Ivy": "  Stop Painting Ivy", iconPaint, "while painting, left-click and drag in the Scene view on any collider");
            if (GUILayout.Button(content, GUILayout.Height(20)))
            {
                isPlantingModeActive = !isPlantingModeActive;
            }
            GUI.color = oldColor;

            content = new GUIContent(" Enable Growth Sim AI", "If disabled, then you can just paint ivy without simulation or AI, which is useful when you want small strokes or full control.");
            ivyBehavior.enableGrowthSim = EditorGUILayout.ToggleLeft(content, ivyBehavior.enableGrowthSim);

            content = new GUIContent(" Make Mesh During Painting / Growth", "Generate 3D ivy mesh during painting and growth. Very cool, but very processing intensive. If your computer gets very slow while painting, then disable this.");
            ivyBehavior.generateMeshDuringGrowth = EditorGUILayout.ToggleLeft(content, ivyBehavior.generateMeshDuringGrowth);

            int visibleIvy = ivyBehavior.ivyGraphs.Where(ivy => ivy.isVisible).Count();

            GUI.enabled = isInARealScene && visibleIvy > 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
            content = new GUIContent(" Re-mesh Visible", iconMesh, "Remake meshes for all visible ivy, all at once. Useful when you change your ivy profile settings, and want to see the new changes.");
            if (GUILayout.Button(content, EditorStyles.miniButtonLeft, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth * 0.45f), GUILayout.Height(16)))
            {
                if (EditorUtility.DisplayDialog("Hedera: Remake All Visible Meshes", string.Format("Are you sure you want to remake {0} meshes all at once? It also might be very slow or crash your editor.", visibleIvy), "YES!", "Maybe not..."))
                {
                    foreach (var ivy in ivyBehavior.ivyGraphs)
                    {
                        if (!ivy.isVisible)
                        {
                            continue;
                        }
                        if (ivy.rootGO != null)
                        {
                            Undo.RegisterFullObjectHierarchyUndo(ivy.rootGO, "Hedera > Re-mesh Visible");
                        }
                        else
                        {
                            IvyMesh.InitOrRefreshRoot(ivy, ivyProfile);
                            Undo.RegisterCreatedObjectUndo(ivy.rootGO, "Hedera > Re-mesh Visible");
                        }
                        IvyMesh.GenerateMesh(ivy, ivyProfile, ivyProfile.useLightmapping, true);
                    }
                }
            }

            content = new GUIContent(" Merge Visible", iconLeaf, "Merge all visible ivy into a single ivy / single mesh. This is (usually) good for optimizing the 3D performance of your scene, especially if you have a lot of ivy everywhere.");
            if (GUILayout.Button(content, EditorStyles.miniButtonRight, GUILayout.Height(16)))
            {
                if (EditorUtility.DisplayDialog("Hedera: Merge All Visible Ivy Strokes", string.Format("Are you sure you want to merge {0} ivy plants into one?", visibleIvy), "YES!", "Maybe not..."))
                {
                    Undo.RegisterCompleteObjectUndo(ivyBehavior, "Hedera > Merge Visible");
                    Undo.SetCurrentGroupName("Hedera > Merge Visible");

                    //var rootIvyB = IvyCore.StartDestructiveEdit(ivyBehavior, applyAllOverrides:true );
                    IvyCore.MergeVisibleIvyGraphs(ivyBehavior, ivyProfile);
                    // IvyCore.CommitDestructiveEdit();
                }
            }

            EditorGUILayout.EndHorizontal();
            GUI.enabled = isInARealScene;

            if (ivyBehavior.ivyGraphs.Count == 0)
            {
                EditorGUILayout.HelpBox("To paint Ivy, first click [Start Painting Ivy]... then hold down [Left Mouse Button] on a collider in the Scene view, and drag.", MessageType.Info);
            }

            lastMeshIDs.Clear();
            IvyGraph ivyGraphObjJob = null; // used to pull .OBJ export out of the for() loop
            var      oldBGColor     = GUI.backgroundColor;
            var      pulseColor     = Color.Lerp(oldBGColor, Color.yellow, Mathf.PingPong(System.Convert.ToSingle(EditorApplication.timeSinceStartup) * 2f, 1f));

            for (int i = 0; i < ivyBehavior.ivyGraphs.Count; i++)
            {
                GUI.enabled = isInARealScene;
                var ivy = ivyBehavior.ivyGraphs[i];
                if (ivy.isGrowing)
                {
                    GUI.backgroundColor = pulseColor;
                }
                lastMeshIDs.Add(ivy.leafMeshID);
                lastMeshIDs.Add(ivy.branchMeshID);
                EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
                GUI.backgroundColor = oldBGColor;

                GUI.color = ivy.isVisible ? oldColor : Color.gray;
                var eyeIcon = ivy.isVisible ? iconVisOn : iconVisOff;
                content = new GUIContent(eyeIcon, "Click to toggle visibility for this ivy plant.\n(Enable / disable the game object.)");
                if (GUILayout.Button(content, EditorStyles.miniButtonLeft, GUILayout.Height(16), GUILayout.Width(24)))
                {
                    ivy.isVisible = !ivy.isVisible;
                    if (ivy.rootGO != null)
                    {
                        ivy.rootGO.SetActive(ivy.isVisible);
                    }
                }
                GUI.color = oldColor;

                GUI.color = ivy != currentIvyGraphMove ? oldColor : Color.gray;
                content   = new GUIContent(iconMove, "Click to start moving the seed position for this ivy plant.");
                if (GUILayout.Button(content, EditorStyles.miniButtonRight, GUILayout.Height(16), GUILayout.Width(24)))
                {
                    if (ivy.rootGO != null)
                    {
                        ivy.rootGO.transform.position = ivy.seedPos;
                    }
                    currentIvyGraphMove = ivy == currentIvyGraphMove ? null : ivy;
                }
                GUI.color = oldColor;

                if (ivy.rootGO != null)
                {
                    GUI.enabled = false;
                    EditorGUILayout.ObjectField(ivy.rootGO, typeof(GameObject), true);
                    GUI.enabled = isInARealScene;
                }
                else
                {
                    string ivyLabel = string.Format(
                        "(no mesh) {0} ivy",
                        ivy.roots.Count,
                        ivy.seedPos
                        );
                    GUILayout.Label(ivyLabel, EditorStyles.miniLabel);
                }

                if (!ivy.isGrowing)
                {
                    content = new GUIContent(iconMesh, "Make (or remake) the 3D mesh for this ivy");
                    if (GUILayout.Button(content, EditorStyles.miniButtonLeft, GUILayout.Width(24), GUILayout.Height(16)))
                    {
                        if (ivy.rootGO != null)
                        {
                            Undo.RegisterFullObjectHierarchyUndo(ivy.rootGO, "Hedera > Make Mesh");
                        }
                        else
                        {
                            IvyMesh.InitOrRefreshRoot(ivy, ivyProfile);
                            Undo.RegisterCreatedObjectUndo(ivy.rootGO, "Hedera > Make Mesh");
                        }
                        IvyMesh.GenerateMesh(ivy, ivyProfile, ivyProfile.useLightmapping, true);
                        Repaint();
                    }
                    GUI.enabled = ivy.branchMF != null || ivy.leafMF != null;
                    content     = new GUIContent("OBJ", iconExport, "Export ivy mesh to .OBJ file\n(Note: .OBJs only support one UV channel so they cannot have lightmap UVs, Unity must unwrap them upon import)");
                    if (GUILayout.Button(content, EditorStyles.miniButtonMid, GUILayout.Width(24), GUILayout.Height(16)))
                    {
                        ivyGraphObjJob = ivy;
                    }
                    GUI.enabled = isInARealScene;
                    content     = new GUIContent(iconTrash, "Delete this ivy as well as its mesh objects.");
                    if (GUILayout.Button(content, EditorStyles.miniButtonRight, GUILayout.Width(24), GUILayout.Height(16)))
                    {
                        if (ivy.rootGO != null)
                        {
                            IvyCore.DestroyObject(ivy.rootGO);
                        }
                        IvyCore.TryToDestroyMeshes(ivyBehavior, ivy);
                        Undo.RegisterCompleteObjectUndo(ivyBehavior, "Hedera > Delete Ivy");
                        ivyBehavior.ivyGraphs.Remove(ivy);
                        EditorGUILayout.EndHorizontal();
                        i--;
                        continue;
                    }
                }
                else
                {
                    if (GUILayout.Button("Stop Growing", EditorStyles.miniButton))
                    {
                        ivy.isGrowing = false;
                    }
                }
                EditorGUILayout.EndHorizontal();
            }

            if (ivyBehavior.ivyGraphs.Where(ivy => ivy.isGrowing).Count() > 0)
            {
                EditorGUILayout.Space();
                GUI.color = pulseColor;
                if (GUILayout.Button("Stop All Growing"))
                {
                    IvyCore.ForceStopGrowing();
                }
                GUI.color = oldColor;
            }

            GUI.enabled = true;
            EditorGUILayout.Space();
            content = new GUIContent("Debug Color", "When ivy doesn't have a mesh, Hedera will visualize the ivy structure as a debug wireframe with this color in the Scene view.");
            ivyBehavior.debugColor = EditorGUILayout.ColorField(content, ivyBehavior.debugColor);
            EditorGUILayout.Space();

            // was getting GUI errors doing OBJ export inline, so let's do it outside of the for() loop

            /*
             * if ( ivyGraphObjJob != null) {
             *  var filename = ObjExport.SaveObjFile( new GameObject[] { ivyGraphObjJob.rootGO }, true );
             *  if ( isInARealScene
             *      && !string.IsNullOrEmpty(filename)
             *      && filename.StartsWith(Application.dataPath)
             *      && AssetDatabase.IsMainAssetAtPathLoaded("Assets" + filename.Substring( Application.dataPath.Length ))
             *  ) {
             *      int choice = EditorUtility.DisplayDialogComplex("Hedera: Instantiate .OBJ into scene?", "You just exported ivy into a .OBJ into your project.\nDo you want to replace the ivy with the .OBJ?", "Yes, and delete old ivy", "No, don't instantiate", "Yes, and hide old ivy");
             *
             *      if ( choice == 0 || choice == 2) {
             *          var prefab = AssetDatabase.LoadAssetAtPath<Object>( "Assets" + filename.Substring( Application.dataPath.Length ) );
             *          var newObj = (GameObject)PrefabUtility.InstantiatePrefab( prefab );
             *          Undo.RegisterCreatedObjectUndo( newObj, "Hedera > Instantiate OBJ" );
             *          newObj.transform.SetParent( ivyBehavior.transform );
             *          newObj.transform.position = ivyGraphObjJob.seedPos;
             *
             *          var renders = newObj.GetComponentsInChildren<Renderer>();
             *          renders[0].material = ivyProfile.branchMaterial;
             *          if ( renders.Length > 1) { renders[1].material = ivyProfile.leafMaterial; }
             *
             *          if ( choice == 0 ) { // remove old ivy
             *              if ( ivyGraphObjJob.rootGO != null) {
             *                  IvyCore.DestroyObject( ivyGraphObjJob.rootGO );
             *              }
             *              IvyCore.TryToDestroyMeshes( ivyBehavior, ivyGraphObjJob);
             *              Undo.RegisterCompleteObjectUndo( ivyBehavior, "Hedera > Instantiate OBJ" );
             *              ivyBehavior.ivyGraphs.Remove(ivyGraphObjJob);
             *          } else { // just turn off old ivy
             *              Undo.RegisterCompleteObjectUndo( ivyBehavior, "Hedera > Instantiate OBJ" );
             *              ivyGraphObjJob.isVisible = false;
             *              if ( ivyGraphObjJob.rootGO != null) {
             *                  ivyGraphObjJob.rootGO.SetActive( false );
             *              }
             *          }
             *      }
             *  }
             * }
             */
        }