Esempio n. 1
0
            static void Postfix(VisEquipment __instance)
            {
                string path = Path.Combine($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}", "CustomMeshes");

                foreach (string file in Directory.GetFiles(path, "*.fbx"))
                {
                    GameObject obj = MeshImporter.Load(file);
                    obj.name = "player_fbx";
                    string name = Path.GetFileNameWithoutExtension(file);
                    if (name == "player_model_1")
                    {
                        Dbgl($"Adding mesh from {file}.");

                        Transform oldArmature = __instance.gameObject.transform.Find("Visual").Find("Armature");

                        GameObject newArmature = obj.transform.Find("Armature.003").gameObject;
                        newArmature.name = "Armature";

                        //Instantiate(newArmature, oldArmature.parent);
                        //Destroy(oldArmature.gameObject);


                        SkinnedMeshRenderer smr = __instance.m_models[0].GetComponentInChildren <SkinnedMeshRenderer>();
                        MeshFilter          mr  = obj.GetComponentInChildren <MeshFilter>();
                        smr.sharedMesh = mr.sharedMesh;
                    }
                }
            }
Esempio n. 2
0
        void Start()
        {
            // Import from a GameObject. In this case we're loading and assigning to the same GameObject, but you may
            // load and apply to different Objects as well.

            // Create a new MeshImporter
            var importer = new MeshImporter(gameObject);

            importer.Import();

            // Since we're loading and setting from the same object, it is necessary to create a new mesh to avoid
            // overwriting the mesh that is being read from.
            var filter = GetComponent <MeshFilter>();

            filter.sharedMesh = new Mesh();

            //Retrieve the create PB Mesh
            var mesh = gameObject.GetComponent <ProBuilderMesh>();

            // Do something with the pb_Object. Here we're extruding every face on the object by .25.
            mesh.Extrude(mesh.faces, ExtrudeMethod.IndividualFaces, .25f);

            // Apply the imported geometry to the pb_Object
            mesh.ToMesh();

            // Rebuild UVs, Collisions, Tangents, etc.
            mesh.Refresh();
        }
Esempio n. 3
0
        private static void ImportMesh(MeshFilter filter, ProBuilderMesh mesh, Vector2 uvScale)
        {
            MeshImporter importer = new MeshImporter(mesh);
            Renderer     renderer = mesh.GetComponent <Renderer>();

            importer.Import(filter.sharedMesh, renderer.sharedMaterials, m_defaultImportSettings);

            Dictionary <int, List <Face> > submeshIndexToFace = new Dictionary <int, List <Face> >();
            int submeshCount = filter.sharedMesh.subMeshCount;

            for (int i = 0; i < submeshCount; ++i)
            {
                submeshIndexToFace.Add(i, new List <Face>());
            }

            IList <Face> faces = mesh.faces;

            if (uvScale != Vector2.one)
            {
                AutoUnwrapSettings uv = AutoUnwrapSettings.defaultAutoUnwrapSettings;
                uv.scale = uvScale;
                for (int i = 0; i < mesh.faceCount; ++i)
                {
                    Face face = faces[i];
                    face.uv = uv;
                    submeshIndexToFace[face.submeshIndex].Add(face);
                }
            }
            else
            {
                for (int i = 0; i < mesh.faceCount; ++i)
                {
                    Face face = faces[i];
                    submeshIndexToFace[face.submeshIndex].Add(face);
                }
            }

            filter.sharedMesh = new Mesh();
            mesh.ToMesh();
            mesh.Refresh();

            Material[] materials = renderer.sharedMaterials;
            for (int i = 0; i < submeshCount && i < materials.Length; ++i)
            {
                List <Face> submeshFaces = submeshIndexToFace[i];
                Material    material     = materials[i];

                if (material != null)
                {
                    mesh.SetMaterial(submeshFaces, material);
                }
            }

            mesh.ToMesh();
            mesh.Refresh();
        }
        private static void ImportMesh(MeshFilter filter, ProBuilderMesh mesh)
        {
            MeshImporter importer = new MeshImporter(mesh);
            Renderer     renderer = mesh.GetComponent <Renderer>();

            importer.Import(filter.sharedMesh, renderer.sharedMaterials);

            filter.sharedMesh = new Mesh();

            mesh.ToMesh();
            mesh.Refresh();
        }
Esempio n. 5
0
        /// <summary>
        /// Adds pb_Object component without duplicating the objcet. Is undo-able.
        /// </summary>
        /// <param name="selected"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static ActionResult DoProBuilderize(
            IEnumerable <MeshFilter> selected,
            MeshImportSettings settings)
        {
            int   i     = 0;
            float count = selected.Count();

            // Return immediately from the action so that the GUI can resolve. Displaying a progress bar interrupts the
            // event loop causing a layoutting error.
            EditorApplication.delayCall += () =>
            {
                foreach (var mf in selected)
                {
                    if (mf.sharedMesh == null)
                    {
                        continue;
                    }

                    GameObject go              = mf.gameObject;
                    Mesh       sourceMesh      = mf.sharedMesh;
                    Material[] sourceMaterials = go.GetComponent <MeshRenderer>()?.sharedMaterials;

                    try
                    {
                        var destination  = Undo.AddComponent <ProBuilderMesh>(go);
                        var meshImporter = new MeshImporter(sourceMesh, sourceMaterials, destination);
                        meshImporter.Import(settings);

                        destination.Rebuild();
                        destination.Optimize();

                        i++;
                    }
                    catch (System.Exception e)
                    {
                        Debug.LogWarning("Failed ProBuilderizing: " + go.name + "\n" + e.ToString());
                    }

                    UnityEditor.EditorUtility.DisplayProgressBar("ProBuilderizing", mf.gameObject.name, i / count);
                }

                UnityEditor.EditorUtility.ClearProgressBar();
                MeshSelection.OnObjectSelectionChanged();
                ProBuilderEditor.Refresh();
            };

            if (i < 1)
            {
                return(new ActionResult(ActionResult.Status.Canceled, "Nothing Selected"));
            }
            return(new ActionResult(ActionResult.Status.Success, "ProBuilderize " + i + (i > 1 ? " Objects" : " Object").ToString()));
        }
    // Generating particle array
    public Vector3[] GetTargetParticlePositions()
    {
        switch (targetObjectMode)
        {
        case TargetObjectMode.ImportedObject:
            importedObjectMesh = importedObject.GetComponentInChildren <MeshFilter>().mesh;
            meshModelData      = MeshImporter.GetModelData(importedObjectMesh);
            return(meshModelData.particlePositions);

        case TargetObjectMode.RectangularCloth:
            return(GenerateParticlesRectangularCloth());
        }

        return(default);
Esempio n. 7
0
        static ActionResult MenuBooleanOperation(BooleanOperation operation, ProBuilderMesh lhs, ProBuilderMesh rhs)
        {
            if (lhs == null || rhs == null)
            {
                return(new ActionResult(ActionResult.Status.Failure, "Must Select 2 Objects"));
            }

            string op_string = operation == BooleanOperation.Union ? "Union" : (operation == BooleanOperation.Subtract ? "Subtract" : "Intersect");

            ProBuilderMesh[] sel = new ProBuilderMesh[] { lhs, rhs };

            UndoUtility.RecordSelection(sel, op_string);

            UnityEngine.ProBuilder.Csg.Model result;

            switch (operation)
            {
            case BooleanOperation.Union:
                result = Boolean.Union(lhs.gameObject, rhs.gameObject);
                break;

            case BooleanOperation.Subtract:
                result = Boolean.Subtract(lhs.gameObject, rhs.gameObject);
                break;

            default:
                result = Boolean.Intersect(lhs.gameObject, rhs.gameObject);
                break;
            }

            var            materials = result.materials.ToArray();
            ProBuilderMesh pb        = ProBuilderMesh.Create();

            pb.GetComponent <MeshFilter>().sharedMesh        = (Mesh)result;
            pb.GetComponent <MeshRenderer>().sharedMaterials = materials;
            MeshImporter importer = new MeshImporter(pb.gameObject);

            importer.Import(new MeshImportSettings()
            {
                quads = true, smoothing = true, smoothingAngle = 1f
            });
            pb.Rebuild();
            pb.CenterPivot(null);
            Selection.objects = new Object[] { pb.gameObject };

            return(new ActionResult(ActionResult.Status.Success, op_string));
        }
        private static void ImportMesh(MeshFilter filter, ProBuilderMesh mesh)
        {
            MeshImporter importer = new MeshImporter(mesh);
            Renderer     renderer = mesh.GetComponent <Renderer>();

            importer.Import(filter.sharedMesh, renderer.sharedMaterials);

            filter.sharedMesh = new Mesh();

            foreach (Face face in mesh.faces)
            {
                face.manualUV = false;
            }

            mesh.ToMesh();
            mesh.Refresh();
        }
Esempio n. 9
0
        void Awake()
        {
            // Root object
            _root = GameObject.Find("Root");

            // UI
            _loadCanvas      = GameObject.Find("LoadCanvas");
            _errorCanvas     = GameObject.Find("ErrorCanvas");
            _errorText       = GameObject.Find("ErrorText");
            _scaleInputField = GameObject.Find("ScaleInputField");
            _scaleSlider     = GameObject.Find("ScaleSlider");
            _scaleSlider.GetComponent <Slider>().onValueChanged.AddListener((value) => { _meshScale = value; });

            var loadButton = GameObject.Find("LoadButton").GetComponent <Button>();

            loadButton.onClick.AddListener(() =>
            {
                _loadCanvas.GetComponent <Canvas>().enabled = false;

                SimpleFileBrowser.FileBrowser.ShowLoadDialog((path) =>
                {
                    try
                    {
                        var ob = MeshImporter.Load(path, _meshScale, _meshScale, _meshScale);
                        ob.transform.SetParent(_root.transform, false);
                    }
                    catch (Exception e)
                    {
                        _errorCanvas.GetComponent <Canvas>().enabled = true;
                        _errorText.GetComponent <Text>().text        = String.Format("Failed to load: {0}\n{1}", path, e.Message);
                        return;
                    }

                    _loadCanvas.GetComponent <Canvas>().enabled = false;
                }, null, false);
            });

            var clearButton = GameObject.Find("ClearButton").GetComponent <Button>();

            clearButton.onClick.AddListener(() => { Clear(); });

            var okayButton = GameObject.Find("OKButton").GetComponent <Button>();

            okayButton.onClick.AddListener(() => { _errorCanvas.GetComponent <Canvas>().enabled = false; });
        }
Esempio n. 10
0
        static IEnumerator LoadMeshes(VRMImporterContext context)
        {
            var meshImporter = new MeshImporter();

            for (int i = 0; i < context.GLTF.meshes.Count; ++i)
            {
                var meshContext       = meshImporter.ReadMesh(context, i);
                var meshWithMaterials = gltfImporter.BuildMesh(context, meshContext);
                var mesh = meshWithMaterials.Mesh;
                if (string.IsNullOrEmpty(mesh.name))
                {
                    mesh.name = string.Format("UniGLTF import#{0}", i);
                }
                context.Meshes.Add(meshWithMaterials);

                yield return(null);
            }
        }
        public static void CubeSurvivesRoundTrip()
        {
            var pb = ShapeGenerator.CreateShape(ShapeType.Cube);

            try
            {
                var dup      = new GameObject().AddComponent <ProBuilderMesh>();
                var importer = new MeshImporter(dup);
                importer.Import(pb.gameObject);
                dup.ToMesh();
                dup.Refresh();
                TestUtility.AssertAreEqual(pb.mesh, dup.mesh, message: pb.name);
            }
            catch
            {
                UnityEngine.Object.DestroyImmediate(pb.gameObject);
            }
        }
    public static void ImportCube_MatchesDefaultCube()
    {
        var pb = ShapeGenerator.CreateShape(ShapeType.Cube);

        try
        {
#pragma warning disable 612
            var dup      = new GameObject().AddComponent <ProBuilderMesh>();
            var importer = new MeshImporter(dup);
            importer.Import(pb.gameObject);
#pragma warning restore 612
            dup.ToMesh();
            dup.Refresh();
            TestUtility.AssertAreEqual(pb.mesh, dup.mesh, message: pb.name);
        }
        catch
        {
            UnityEngine.Object.DestroyImmediate(pb.gameObject);
        }
    }
Esempio n. 13
0
        private static GameObject CreateMeshVisualRuntime(Link.Geometry.Mesh mesh)
        {
            GameObject meshObject = null;

            if (!string.IsNullOrEmpty(mesh.filename))
            {
                try
                {
                    string meshFilePath = UrdfAssetPathHandler.GetRelativeAssetPathFromUrdfPath(mesh.filename, false);
                    if (meshFilePath.ToLower().EndsWith(".stl"))
                    {
                        meshObject = StlAssetPostProcessor.CreateStlGameObjectRuntime(meshFilePath);
                    }
                    else if (meshFilePath.ToLower().EndsWith(".dae"))
                    {
                        float globalScale = ColladaAssetPostProcessor.ReadGlobalScale(meshFilePath);
                        meshObject = MeshImporter.Load(meshFilePath, globalScale, globalScale, globalScale);
                        if (meshObject != null)
                        {
                            ColladaAssetPostProcessor.ApplyColladaOrientation(meshObject, meshFilePath);
                        }
                    }
                    else if (meshFilePath.ToLower().EndsWith(".obj"))
                    {
                        meshObject = MeshImporter.Load(meshFilePath);
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogAssertion(ex);
                }

                if (meshObject == null)
                {
                    Debug.LogError("Unable to load visual mesh: " + mesh.filename);
                }
            }
            return(meshObject);
        }
Esempio n. 14
0
        public SceneComposer()
        {
            _renderer = new Renderer();

            _meshes = MeshImporter.LoadBabylonFile($@"..\..\..\Data\coloredSuzanne.babylon");
            _camera = new Camera
            {
                Position = new Vector3(1, 5, 10),
                Target   = new Vector3(),
            };

            _coordinateAxes = new Mesh(
                new List <Vertex>
            {
                new Vertex(new Vector3(-100, 0, 0), Color.Red),
                new Vertex(new Vector3(100, 0, 0), Color.Red),
                new Vertex(new Vector3(0, 0, 0), Color.Red),
                new Vertex(new Vector3(0, -100, 0), Color.Green),
                new Vertex(new Vector3(0, 100, 0), Color.Green),
                new Vertex(new Vector3(0, 0, 0), Color.Green),
                new Vertex(new Vector3(0, 0, -100), Color.Blue),
                new Vertex(new Vector3(0, 0, 100), Color.Blue),
                new Vertex(new Vector3(0, 0, 0), Color.Blue),
            },
                new List <Face>
            {
                new Face {
                    A = 0, B = 1, C = 2
                },
                new Face {
                    A = 3, B = 4, C = 5
                },
                new Face {
                    A = 6, B = 7, C = 8
                },
            }
                );
        }
        public static void QuadsImportWithCorrectWinding()
        {
            var srcPath = TestUtility.TemporarySavedAssetsDirectory + "maya-cube-quads.fbx";

            // do this song and dance because AssetDatabase.LoadAssetAtPath doesn't seem to work with models in the
            // Package directories
            File.Copy(TestUtility.TemplatesDirectory + "MeshImporter/maya-cube-quads.fbx", srcPath);
            AssetDatabase.Refresh();
            var source       = AssetDatabase.LoadMainAssetAtPath(srcPath);
            var meshImporter = (ModelImporter)AssetImporter.GetAtPath(srcPath);

            meshImporter.globalScale = 100f;
            meshImporter.isReadable  = true;
            meshImporter.SaveAndReimport();

            Assert.IsNotNull(source);

            var instance = (GameObject)UObject.Instantiate(source);
            var result   = new GameObject().AddComponent <ProBuilderMesh>();
            var importer = new MeshImporter(result);

            Assert.IsTrue(importer.Import(instance, new MeshImportSettings()
            {
                quads          = true,
                smoothing      = false,
                smoothingAngle = 1f
            }), "Failed importing mesh");

            result.Rebuild();

            // Assert.IsNotNull doesn't work with  UnityObject magic
            Assert.IsFalse(result.mesh == null);

#if PB_CREATE_TEST_MESH_TEMPLATES
            TestUtility.SaveAssetTemplate(result.mesh, "imported-cube-triangles");
#endif

            TestUtility.AssertMeshesAreEqual(TestUtility.GetAssetTemplate <Mesh>("imported-cube-triangles"), result.mesh);

            UObject.DestroyImmediate(result);

            UObject.DestroyImmediate(instance);
            meshImporter.keepQuads = true;
            meshImporter.SaveAndReimport();
            instance = (GameObject)UObject.Instantiate(source);

            var quadMesh = instance.GetComponent <MeshFilter>().sharedMesh;
            Assert.AreEqual(MeshTopology.Quads, quadMesh.GetTopology(0));

            result   = new GameObject().AddComponent <ProBuilderMesh>();
            importer = new MeshImporter(result);

            Assert.IsTrue(importer.Import(instance, new MeshImportSettings()
            {
                quads          = true,
                smoothing      = false,
                smoothingAngle = 1f
            }), "Failed importing mesh");

            result.Rebuild();

#if PB_CREATE_TEST_MESH_TEMPLATES
            TestUtility.SaveAssetTemplate(result.mesh, "imported-cube-quads");
#endif

            TestUtility.AssertMeshesAreEqual(TestUtility.GetAssetTemplate <Mesh>("imported-cube-quads"), result.mesh);
            UObject.DestroyImmediate(result);
            AssetDatabase.DeleteAsset(TestUtility.TemporarySavedAssetsDirectory + "maya-cube-quads.fbx");
        }
Esempio n. 16
0
        private static Schedulable <GameObject> LoadVrmAsyncInternal(VRMImporterContext ctx, bool show)
        {
            return(Schedulable.Create()
                   .AddTask(Scheduler.ThreadPool, () =>
            {
                using (ctx.MeasureTime("glTF_VRM_Material.Parse"))
                {
                    return glTF_VRM_Material.Parse(ctx.Json);
                }
            })
                   .ContinueWith(Scheduler.MainThread, gltfMaterials =>
            {
                using (ctx.MeasureTime("new VRMMaterialImporter"))
                {
                    ctx.MaterialImporter = new VRMMaterialImporter(ctx, gltfMaterials);
                }
            })
                   .OnExecute(Scheduler.ThreadPool, parent =>
            {
                // textures
                for (int i = 0; i < ctx.GLTF.textures.Count; ++i)
                {
                    var index = i;
                    parent.AddTask(Scheduler.MainThread,
                                   () =>
                    {
                        using (ctx.MeasureTime("texture.Process"))
                        {
                            var texture = new TextureItem(ctx.GLTF, index);
                            texture.Process(ctx.GLTF, ctx.Storage);
                            return texture;
                        }
                    })
                    .ContinueWith(Scheduler.ThreadPool, x => ctx.AddTexture(x));
                }
            })
                   .ContinueWithCoroutine(Scheduler.MainThread, () => LoadMaterials(ctx))
                   .OnExecute(Scheduler.ThreadPool, parent =>
            {
                // meshes
                var meshImporter = new MeshImporter();
                for (int i = 0; i < ctx.GLTF.meshes.Count; ++i)
                {
                    var index = i;
                    parent.AddTask(Scheduler.ThreadPool,
                                   () =>
                    {
                        using (ctx.MeasureTime("ReadMesh"))
                        {
                            return meshImporter.ReadMesh(ctx, index);
                        }
                    })
                    .ContinueWith(Scheduler.MainThread, x =>
                    {
                        using (ctx.MeasureTime("BuildMesh"))
                        {
                            return gltfImporter.BuildMesh(ctx, x);
                        }
                    })
                    .ContinueWith(Scheduler.ThreadPool, x => ctx.Meshes.Add(x))
                    ;
                }
            })
                   .ContinueWithCoroutine(Scheduler.MainThread, () =>
            {
                using (ctx.MeasureTime("LoadNodes"))
                {
                    return LoadNodes(ctx);
                }
            })
                   .ContinueWithCoroutine(Scheduler.MainThread, () =>
            {
                using (ctx.MeasureTime("BuildHierarchy"))
                {
                    return BuildHierarchy(ctx);
                }
            })
                   .ContinueWith(Scheduler.CurrentThread, _ =>
            {
                //using (ctx.MeasureTime("OnLoadModel"))
                {
                    return VRMImporter.OnLoadModel(ctx);
                }
            })
                   .ContinueWith(Scheduler.CurrentThread,
                                 _ =>
            {
                ctx.Root.name = "VRM";

                if (show)
                {
                    ctx.ShowMeshes();
                }

                Debug.Log(ctx.GetSpeedLog());
                return ctx.Root;
            }));
        }
        public GameObject CreateMesh(GameObject root, string meshFile, float sx, float sy, float sz, bool flipYz = false)
        {
            // meshFile is file name without file extension related to Resources directory
            // sx, sy, sz is scale
            MeshUpAxis meshUpAxis = MeshUpAxis.YUp;
            GameObject mesh       = null;

            if (_meshCache.ContainsKey(meshFile) && _meshCache[meshFile] != null)
            {
            }
            else
            {
                if (!File.Exists(meshFile))
                {
                    new RsuException(new Exception(), "Cannot find mesh file: " + meshFile);
                }

                string fileExtension = Path.GetExtension(meshFile);
                var    loadedMesh    = MeshImporter.Load(meshFile);

                // check up axis (for dae)
                if (fileExtension == ".dae")
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    if (xmlDoc != null)
                    {
                        xmlDoc.Load(meshFile);
                        var upAxisNode = xmlDoc.DocumentElement.SelectSingleNode("//*[contains(local-name(), 'up_axis')]").LastChild;

                        if (upAxisNode != null && !string.IsNullOrEmpty(upAxisNode.Value))
                        {
                            if (upAxisNode.Value == "Z_UP")
                            {
                                meshUpAxis = MeshUpAxis.ZUp;
                            }
                            else if (upAxisNode.Value == "Y_UP")
                            {
                                meshUpAxis = MeshUpAxis.YUp;
                            }
                            else
                            {
                                meshUpAxis = MeshUpAxis.XUp;
                            }
                        }
                    }
                }

                // save to cache
                loadedMesh.name = meshFile;
                loadedMesh.transform.SetParent(_objectCache.transform, false);
                loadedMesh.SetActive(false);
                loadedMesh.GetComponentInChildren <Renderer>().material.shader = _standardShader;
                _meshCache.Add(meshFile, new Tuple <GameObject, MeshUpAxis>(loadedMesh, meshUpAxis));
            }

            var cachedMesh = _meshCache[meshFile];

            mesh = GameObject.Instantiate(cachedMesh.Item1);
            if (mesh == null)
            {
                new RsuException(new Exception(), "Cannot load mesh file: " + meshFile);
            }

            mesh.SetActive(true);
            mesh.name = "mesh";
            mesh.transform.SetParent(root.transform, false);
            Vector3 originalScale = mesh.transform.localScale;

            mesh.transform.localScale = new Vector3((float)sx * originalScale[0], (float)sy * originalScale[1], (float)sz * originalScale[2]);

            if (cachedMesh.Item2 == MeshUpAxis.ZUp)
            {
            }
            else if (cachedMesh.Item2 == MeshUpAxis.YUp)
            {
                mesh.transform.localRotation = new Quaternion(-0.7071f, 0, 0, 0.7071f) * mesh.transform.localRotation;
            }
            else if (cachedMesh.Item2 == MeshUpAxis.XUp)
            {
                mesh.transform.localRotation = new Quaternion(0, 0, 0.7071f, 0.7071f) * mesh.transform.localRotation;
            }

            // add collider to children
            foreach (Transform children in mesh.transform)
            {
                children.gameObject.AddComponent <MeshCollider>();
            }
            return(mesh);
        }
Esempio n. 18
0
 public void Shutdown()
 {
     MeshImporter.Dispose();
 }
Esempio n. 19
0
        private static void PreloadMeshes()
        {
            foreach (AssetBundle ab in customAssetBundles.Values)
            {
                ab.Unload(true);
            }
            customMeshes.Clear();
            customGameObjects.Clear();
            customAssetBundles.Clear();

            Dbgl($"Importing meshes");

            string path = Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath), "CustomMeshes");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                return;
            }

            foreach (string dir in Directory.GetDirectories(path))
            {
                string dirName = Path.GetFileName(dir);
                Dbgl($"Importing meshes: {dirName}");

                customMeshes[dirName]      = new Dictionary <string, Dictionary <string, CustomMeshData> >();
                customGameObjects[dirName] = new Dictionary <string, Dictionary <string, GameObject> >();

                foreach (string subdir in Directory.GetDirectories(dir))
                {
                    string subdirName = Path.GetFileName(subdir);
                    Dbgl($"Importing meshes: {dirName}\\{subdirName}");

                    customMeshes[dirName][subdirName]      = new Dictionary <string, CustomMeshData>();
                    customGameObjects[dirName][subdirName] = new Dictionary <string, GameObject>();

                    foreach (string file in Directory.GetFiles(subdir))
                    {
                        try
                        {
                            SkinnedMeshRenderer renderer = null;
                            Mesh mesh = null;
                            Dbgl($"Importing {file} {Path.GetFileNameWithoutExtension(file)} {Path.GetFileName(file)} {Path.GetExtension(file).ToLower()}");
                            string name = Path.GetFileNameWithoutExtension(file);
                            if (name == Path.GetFileName(file))
                            {
                                AssetBundle ab = AssetBundle.LoadFromFile(file);
                                customAssetBundles.Add(name, ab);

                                GameObject prefab = ab.LoadAsset <GameObject>("Player");
                                if (prefab != null)
                                {
                                    renderer = prefab.GetComponentInChildren <SkinnedMeshRenderer>();
                                    if (renderer != null)
                                    {
                                        mesh = renderer.sharedMesh;
                                        Dbgl($"Importing {file} asset bundle as player");
                                    }
                                    else
                                    {
                                        Dbgl($"No SkinnedMeshRenderer on {prefab}");
                                    }
                                    if (mesh == null)
                                    {
                                        mesh = ab.LoadAsset <Mesh>("body");
                                    }
                                }
                                else
                                {
                                    mesh = ab.LoadAsset <Mesh>("body");

                                    if (mesh != null)
                                    {
                                        Dbgl($"Importing {file} asset bundle as mesh");
                                    }
                                    else
                                    {
                                        Dbgl("Failed to find body");
                                    }
                                }
                            }
                            else if (Path.GetExtension(file).ToLower() == ".fbx")
                            {
                                GameObject obj  = MeshImporter.Load(file);
                                GameObject obj2 = obj?.transform.Find("Player")?.Find("Visual")?.gameObject;
                                //

                                /*
                                 * int children = obj.transform.childCount;
                                 * for(int i = 0; i < children; i++)
                                 * {
                                 *  Dbgl($"fbx child: {obj.transform.GetChild(i).name}");
                                 * }
                                 */
                                mesh = obj.GetComponentInChildren <MeshFilter>().mesh;
                                if (obj2 != null)
                                {
                                    renderer = obj2.GetComponentInChildren <SkinnedMeshRenderer>();
                                }
                                if (mesh != null)
                                {
                                    if (renderer != null)
                                    {
                                        Dbgl($"Importing {file} fbx as player");
                                    }
                                    else
                                    {
                                        Dbgl($"Importing {file} fbx as mesh");
                                    }
                                }
                            }
                            else if (Path.GetExtension(file).ToLower() == ".obj")
                            {
                                mesh = new ObjImporter().ImportFile(file);
                                if (mesh != null)
                                {
                                    Dbgl($"Imported {file} obj as mesh");
                                }
                            }
                            if (mesh != null)
                            {
                                customMeshes[dirName][subdirName].Add(name, new CustomMeshData(dirName, name, mesh, renderer));
                                Dbgl($"Added mesh data to customMeshes[{dirName}][{subdirName}][{name}]");
                            }
                        }
                        catch { }
                    }
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Adds pb_Object component without duplicating the objcet. Is undo-able.
        /// </summary>
        /// <param name="selected"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static ActionResult DoProBuilderize(
            IEnumerable <MeshFilter> selected,
            MeshImportSettings settings)
        {
            int   i     = 0;
            float count = selected.Count();

            foreach (var mf in selected)
            {
                if (mf.sharedMesh == null)
                {
                    continue;
                }

                GameObject go           = mf.gameObject;
                Mesh       originalMesh = mf.sharedMesh;

                try
                {
                    ProBuilderMesh pb = Undo.AddComponent <ProBuilderMesh>(go);

                    MeshImporter meshImporter = new MeshImporter(pb);
                    meshImporter.Import(go, settings);

                    // if this was previously a pb_Object, or similarly any other instance asset, destroy it.
                    // if it is backed by saved asset, leave the mesh asset alone but assign a new mesh to the
                    // renderer so that we don't modify the asset.
                    if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(originalMesh)))
                    {
                        Undo.DestroyObjectImmediate(originalMesh);
                    }
                    else
                    {
                        go.GetComponent <MeshFilter>().sharedMesh = new Mesh();
                    }

                    pb.ToMesh();
                    pb.Refresh();
                    pb.Optimize();

                    i++;
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning("Failed ProBuilderizing: " + go.name + "\n" + e.ToString());
                }

                UnityEditor.EditorUtility.DisplayProgressBar("ProBuilderizing", mf.gameObject.name, i / count);
            }

            UnityEditor.EditorUtility.ClearProgressBar();
            MeshSelection.OnObjectSelectionChanged();
            ProBuilderEditor.Refresh();

            if (i < 1)
            {
                return(new ActionResult(ActionResult.Status.Canceled, "Nothing Selected"));
            }
            else
            {
                return(new ActionResult(ActionResult.Status.Success, "ProBuilderize " + i + (i > 1 ? " Objects" : " Object").ToString()));
            }
        }
Esempio n. 21
0
 protected override Schedulable <Unit> LoadAsync()
 {
     return(Schedulable.Create()
            .AddTask(Scheduler.ThreadPool, () =>
     {
         using (MeasureTime("glTF_VRM_Material.Parse"))
         {
             return glTF_VRM_Material.Parse(Json);
         }
     })
            .ContinueWith(Scheduler.MainThread, gltfMaterials =>
     {
         using (MeasureTime("new VRMMaterialImporter"))
         {
             SetMaterialImporter(new VRMMaterialImporter(this, gltfMaterials));
         }
     })
            .OnExecute(Scheduler.ThreadPool, parent =>
     {
         // textures
         for (int i = 0; i < GLTF.textures.Count; ++i)
         {
             var index = i;
             parent.AddTask(Scheduler.MainThread,
                            () =>
             {
                 using (MeasureTime("texture.Process"))
                 {
                     var texture = new TextureItem(index);
                     texture.Process(GLTF, Storage);
                     return texture;
                 }
             })
             .ContinueWith(Scheduler.ThreadPool, x => AddTexture(x));
         }
     })
            .ContinueWithCoroutine(Scheduler.MainThread, () => LoadMaterials())
            .OnExecute(Scheduler.ThreadPool, parent =>
     {
         // meshes
         var meshImporter = new MeshImporter();
         for (int i = 0; i < GLTF.meshes.Count; ++i)
         {
             var index = i;
             parent.AddTask(Scheduler.ThreadPool,
                            () =>
             {
                 using (MeasureTime("ReadMesh"))
                 {
                     return meshImporter.ReadMesh(this, index);
                 }
             })
             .ContinueWith(Scheduler.MainThread, x =>
             {
                 using (MeasureTime("BuildMesh"))
                 {
                     return MeshImporter.BuildMesh(this, x);
                 }
             })
             .ContinueWith(Scheduler.ThreadPool, x => Meshes.Add(x))
             ;
         }
     })
            .ContinueWithCoroutine(Scheduler.MainThread, () =>
     {
         using (MeasureTime("LoadNodes"))
         {
             return LoadNodes();
         }
     })
            .ContinueWithCoroutine(Scheduler.MainThread, () =>
     {
         using (MeasureTime("BuildHierarchy"))
         {
             return BuildHierarchy();
         }
     })
            .ContinueWith(Scheduler.CurrentThread, _ =>
     {
         //using (MeasureTime("OnLoadModel"))
         {
             OnLoadModel();
             return Unit.Default;
         }
     })
            .ContinueWith(Scheduler.CurrentThread,
                          _ =>
     {
         Root.name = "VRM";
         Debug.Log(GetSpeedLog());
         return Unit.Default;
     }));
 }
Esempio n. 22
0
        private void _initMoverAxis()
        {
            _axisXMoverMaterial = new Material()
            {
                HasColorAmbient = true,
                ColorAmbient    = Color4.Red,
                HasColorDiffuse = true,
                ColorDiffuse    = Color4.Red,
                ShaderProgram   = new ObjectAxisShader()
            };

            _axisYMoverMaterial = new Material()
            {
                HasColorAmbient = true,
                ColorAmbient    = Color4.Green,
                HasColorDiffuse = true,
                ColorDiffuse    = Color4.Green,
                ShaderProgram   = new ObjectAxisShader()
            };

            _axisZMoverMaterial = new Material()
            {
                HasColorAmbient = true,
                ColorAmbient    = Color4.Blue,
                HasColorDiffuse = true,
                ColorDiffuse    = Color4.Blue,
                ShaderProgram   = new ObjectAxisShader()
            };

            var arrow = MeshImporter.ImportMesh("Assets/alienEngineSceneEditorObjectMover.obj");

            _axisXMoverMeshRenderer = new MeshRenderer()
            {
                Visible    = false,
                MeshFilter = new MeshFilter(arrow, arrow.RootNode.Meshes[0])
            };

            _axisYMoverMeshRenderer = new MeshRenderer()
            {
                Visible    = false,
                MeshFilter = new MeshFilter(arrow, arrow.RootNode.Meshes[0])
            };

            _axisZMoverMeshRenderer = new MeshRenderer()
            {
                Visible    = false,
                MeshFilter = new MeshFilter(arrow, arrow.RootNode.Meshes[0])
            };

            _sceneEditorObjectAxisMoverX = new GameElement("axisMoverX__sceneEditorElement");
            _sceneEditorObjectAxisMoverY = new GameElement("axisMoverY__sceneEditorElement");
            _sceneEditorObjectAxisMoverZ = new GameElement("axisMoverZ__sceneEditorElement");

            PickableObject xPicker = new PickableObject();

            xPicker.Hover     += _xPickerOnHover;
            xPicker.LostHover += _xPickerOnLostHover;
            xPicker.Picking   += _xPickerOnPicking;
            xPicker.Unpick    += _xPickerOnUnpick;

            PickableObject yPicker = new PickableObject();

            yPicker.Hover     += _yPickerOnHover;
            yPicker.LostHover += _yPickerOnLostHover;
            yPicker.Picking   += _yPickerOnPicking;
            yPicker.Unpick    += _yPickerOnUnpick;

            PickableObject zPicker = new PickableObject();

            zPicker.Hover     += _zPickerOnHover;
            zPicker.LostHover += _zPickerOnLostHover;
            zPicker.Picking   += _zPickerOnPicking;
            zPicker.Unpick    += _zPickerOnUnpick;

            _sceneEditorObjectAxisMoverX.AttachComponent(xPicker);
            _sceneEditorObjectAxisMoverX.AttachComponent(_axisXMoverMaterial);
            _sceneEditorObjectAxisMoverX.AttachComponent(_axisXMoverMeshRenderer);

            _sceneEditorObjectAxisMoverY.AttachComponent(yPicker);
            _sceneEditorObjectAxisMoverY.AttachComponent(_axisYMoverMaterial);
            _sceneEditorObjectAxisMoverY.AttachComponent(_axisYMoverMeshRenderer);

            _sceneEditorObjectAxisMoverZ.AttachComponent(zPicker);
            _sceneEditorObjectAxisMoverZ.AttachComponent(_axisZMoverMaterial);
            _sceneEditorObjectAxisMoverZ.AttachComponent(_axisZMoverMeshRenderer);

            _sceneEditorObjectAxisMoverX.LocalTransform.SetRotationZ(-90.0f);
            _sceneEditorObjectAxisMoverZ.LocalTransform.SetRotationX(+90.0f);

            _sceneEditorObjectAxisMover = new GameElement("axisMover__sceneEditorElement");
            _sceneEditorObjectAxisMover.AddChild(_sceneEditorObjectAxisMoverX);
            _sceneEditorObjectAxisMover.AddChild(_sceneEditorObjectAxisMoverY);
            _sceneEditorObjectAxisMover.AddChild(_sceneEditorObjectAxisMoverZ);

            ParentScene.AddGameElement(_sceneEditorObjectAxisMover);
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            var gameWidth  = 800;
            var gameHeight = 600;

            var solarSystemGame = Game.CreateGame("Space", gameWidth, gameHeight, true);

            var testModel = MeshImporter.ImportModelFromFile("Models/Earth/Earth.obj");
            var planet    = testModel[0];
            var tableMesh = MeshImporter.ImportModelFromFile("Models/Table/table.obj")[0];

            solarSystemGame.CurrentWorld = new World("Solar System");

            SetupInput(solarSystemGame.InputManager);

            var center = new WorldObject(objectName: "System center")
            {
                WorldLocation = Vector3.Up * 400
            };

            var CameraLocation = new Vector3(0, 1000, 2000);
            var camera         = new SimpleControllableCamera(objectName: "Camera")
            {
                ForwardAxis   = "Forward",
                RightAxis     = "Right",
                UpAxis        = "Up",
                TurnRightAxis = "Turn Right",
                TurnUpAxis    = "Turn Up",
                WorldLocation = CameraLocation,
                WorldRotation = Quaternion.Invert(Quaternion.LookAtRH(CameraLocation, center.WorldLocation, Vector3.Up)),
            };

            var table          = new WorldObject(objectName: "Table mesh");
            var tableComponent = new StaticMeshComponent(table)
            {
                Mesh          = tableMesh,
                DefaultShader = new PhongVertexColorShader()
                {
                    AmbientReflection  = .23125f,
                    DiffuseReflection  = 0.2775f,
                    SpecularReflection = .1f,
                    Shininess          = 6.0f,
                },
            };

            var sun = new Planet(0, planet, center, "Sun")
            {
                PlanetSize           = 100,
                RotationAngularSpeed = 0.0f,
                TurningAngularSpeed  = 1.0f,
            };
            var mercury = new Planet(400, planet, center, "Mercury")
            {
                PlanetSize           = 9,
                RotationAngularSpeed = 5.0f,
                TurningAngularSpeed  = 2.0f,
            };
            var venus = new Planet(700, planet, center, "Venus")
            {
                PlanetSize           = 27,
                RotationAngularSpeed = 3.0f,
                TurningAngularSpeed  = -1.0f,
            };
            var earth = new Planet(1000, planet, center, "Earth")
            {
                PlanetSize           = 30,
                RotationAngularSpeed = 1.0f,
                TurningAngularSpeed  = 1.0f,
            };
            var moon = new Planet(6, planet, earth.PlanetCenter, "Moon")
            {
                PlanetSize           = 6,
                RotationAngularSpeed = 2.0f,
                TurningAngularSpeed  = 1.0f,
            };
            var mars = new Planet(1500, planet, center, "Mars")
            {
                PlanetSize           = 15,
                RotationAngularSpeed = 1.0f,
                TurningAngularSpeed  = 0.8f,
            };

            var directionalLight = new DirectionalLightComponent(center)
            {
                Direction = Vector3.Normalize(Vector3.Down + Vector3.Right),
                Intensity = 3,
            };
            var moonPointLight = new PointLightComponent(moon.PlanetCenter)
            {
                Intensity = 2
            };
            var sunPointLight = new PointLightComponent(sun)
            {
                Intensity = 10,
            };

            solarSystemGame.GameRenderer.LightingModel.AddDirectionalLight(directionalLight);
            solarSystemGame.GameRenderer.LightingModel.AddPointLight(sunPointLight);
            solarSystemGame.GameRenderer.LightingModel.AddPointLight(moonPointLight);
            solarSystemGame.StartGame();
            solarSystemGame.Dispose();

            Console.WriteLine();
            Console.WriteLine("Game finished. Press Enter.");
            Console.ReadLine();
        }