Exemple #1
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine(EXENAME + " <filename>");
                return;
            }
            string fname = Environment.CurrentDirectory + "/" + args[0];

            if (!File.Exists(fname))
            {
                Console.WriteLine("Invalid filename.");
                Console.WriteLine(EXENAME + " <filename>");
                return;
            }
            AssimpContext ac = new AssimpContext();

            PT      = args.Length > 1 && args[1].ToLower().Contains("pretrans");
            TEXTURE = args.Length > 1 && args[1].ToLower().Contains("texture");
            Console.WriteLine("Pre-transform = " + PT);
            Console.WriteLine("Texture = " + TEXTURE);
            Scene fdata = ac.ImportFile(fname, PostProcessSteps.Triangulate | PostProcessSteps.FlipWindingOrder);

            if (File.Exists(fname + ".vmd"))
            {
                File.Delete(fname + ".vmd");
            }
            FileStream fs = File.OpenWrite(fname + ".vmd");

            File.WriteAllText(fname + ".skin", ExportModelData(fdata, fs));
            fs.Flush();
            fs.Close();
        }
        public void TestImportFromFile()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles/sphere.obj");

            AssimpContext importer = new AssimpContext();

            importer.SetConfig(new NormalSmoothingAngleConfig(55.0f));
            importer.Scale                    = .5f;
            importer.XAxisRotation            = 25.0f;
            importer.YAxisRotation            = 50.0f;
            LogStream.IsVerboseLoggingEnabled = true;

            Assert.IsTrue(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.RemoveConfigs();

            Assert.IsFalse(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.SetConfig(new NormalSmoothingAngleConfig(65.0f));
            importer.SetConfig(new NormalSmoothingAngleConfig(22.5f));
            importer.RemoveConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName);

            Assert.IsFalse(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.SetConfig(new NormalSmoothingAngleConfig(65.0f));

            Scene scene = importer.ImportFile(path, PostProcessPreset.TargetRealTimeMaximumQuality);

            Assert.IsNotNull(scene);
            Assert.IsTrue((scene.SceneFlags & SceneFlags.Incomplete) != SceneFlags.Incomplete);
        }
        private void OnLoadAssets_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog filePicker = new OpenFileDialog {
                Filter = "Any Assets|*.*"
            };

            if (filePicker.ShowDialog() == true)
            {
                string assetPath = filePicker.FileName;

                // Check for duplicates
                if (_assetPaths.LastIndexOf(assetPath) > -1)
                {
                    MessageBox.Show("This file has already been loaded!");
                    return;
                }

                _assetPaths.Add(assetPath);
                LoadedAssetsListbox.Items.Add(assetPath);

                AssimpContext importer = new AssimpContext();

                Scene scene = importer.ImportFile(assetPath, PostProcessSteps.None);
            }
        }
Exemple #4
0
    static void GainSphere()
    {
        AssimpContext c    = new AssimpContext();
        Scene         s    = c.ImportFile(@"C:\Users\jaken\Desktop\sphere.obj");
        string        text = "";

        foreach (Vector3D v in s.Meshes[0].Vertices)
        {
            //text += v.X.ToString() + "f, " + v.Y.ToString() + "f, " + v.Z.ToString() + "f,\n";
        }
        for (int i = 0; i < s.Meshes[0].GetIndices().Count(); i += 10)
        {
            text += s.Meshes[0].GetIndices()[i + 0].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 1].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 2].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 3].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 4].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 5].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 6].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 7].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 8].ToString() + ", ";
            text += s.Meshes[0].GetIndices()[i + 9].ToString() + ",\n";
        }



        File.WriteAllText(@"C:\Users\jaken\Desktop\sphere.txt", text);
    }
Exemple #5
0
        public ModelObject(string tag, string fileName, string shaderType)
        {
            m_ShaderType = shaderType;
            m_Tag        = tag;
            Scene         model;
            AssimpContext importer = new AssimpContext();

            importer.SetConfig(new Assimp.Configs.NormalSmoothingAngleConfig(66.0f));
            model            = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality);
            m_Geometry       = new Geometry[model.MeshCount];
            m_NumberOfMeshes = m_Geometry.Length;
            int count = 0;

            foreach (var item in model.Meshes)
            {
                List <Vector3D[]> vertList = new List <Vector3D[]>
                {
                    item.Vertices.ToArray(),
                         item.TextureCoordinateChannels[0].ToArray(),
                         item.Normals.ToArray(),
                         item.BiTangents.ToArray(),
                         item.Tangents.ToArray()
                };
                m_Geometry[count] = new Geometry(vertList, item.GetIndices(), item.VertexCount);
                count++;
            }
        }
Exemple #6
0
        private void LoadModel(string fileName)
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets", fileName);

            using (AssimpContext importer = new AssimpContext()) {
                try {
                    importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
                    Scene scene = importer.ImportFile(path, PostProcessPreset.TargetRealTimeQuality | PostProcessSteps.FlipWindingOrder);

                    if (scene != null && scene.HasMeshes)
                    {
                        Console.WriteLine($"Loading {fileName}");
                    }
                    else
                    {
                        Console.WriteLine($"ERROR: Failed to load {fileName}");
                        return;
                    }

                    ProcessNode(scene.RootNode, scene);

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
                    settings.Formatting            = Formatting.Indented;

                    string modelData = JsonConvert.SerializeObject(meshes, settings);
                    System.IO.File.WriteAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets", fileName + ".json"), modelData);

                    Console.WriteLine($"Finished loading {fileName}");
                }
                catch (Exception e) {
                    Console.WriteLine($"ERROR: Somthing went wrong while loading the mesh {fileName}. " + e.Message);
                }
            }
        }
        public Model LoadModel(string filePath)
        {
            string path = Path.Combine(rootFolder, filePath);

            if (_loadedModels.TryGetValue(path, out var mesh))
            {
                return(mesh);
            }

            var model = new Model(filePath.ToLower());

            var context = new AssimpContext();
            var scene   = context.ImportFile(path, PostProcessSteps.Triangulate);

            if (scene.SceneFlags == SceneFlags.Incomplete)
            {
                throw new Exception("Assimp import error");
            }


            foreach (var aiMesh in scene.Meshes)
            {
                model.Meshes.Add(LoadMesh(aiMesh, scene));
            }


            //SetupModel(model);

            _loadedModels.Add(path, model);

            return(model);
        }
Exemple #8
0
        public Dictionary <string, EngineMaterial> LoadFromFile(string path)
        {
            string relativeLocation = Directory.GetParent(path).FullName;

            Dictionary <string, EngineMaterial> mats = new Dictionary <string, EngineMaterial>();
            List <Mesh> meshes = new List <Mesh>();

            AssimpContext context           = new AssimpContext();
            Scene         loadedAssimpScene = context.ImportFile(path, PostProcessSteps.OptimizeMeshes | PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs);

            if (loadedAssimpScene == null || loadedAssimpScene.SceneFlags == SceneFlags.Incomplete)
            {
                Console.WriteLine("Scene error");
            }

            List <AssimpMat> materials = loadedAssimpScene.Materials;

            foreach (var material in materials)
            {
                EngineMaterial _material = new EngineMaterial();
                _material.MaterialName = material.Name;
                TextureSlot[] textureSlots = material.GetAllMaterialTextures();
                if (material.HasTextureDiffuse)
                {
                    _material.DiffuseMap = "C:/Users/kpbil/source/models/mira/textures/Mira_bc2.jpg"; //Path.Combine(relativeLocation, material.TextureDiffuse.FilePath);
                }

                if (material.HasTextureNormal)
                {
                    _material.NormalMap = "C:/Users/kpbil/source/models/mira/textures/Mira_nm.jpg"; //Path.Combine(relativeLocation, material.TextureNormal.FilePath);
                }

                if (material.HasTextureAmbient)
                {
                    _material.AmbientMap = "C:/Users/kpbil/source/models/mira/textures/Mira_ao.jpg";//Path.Combine(relativeLocation, material.TextureAmbient.FilePath);
                }

                try
                {
                    _material.Metallic = "C:/Users/kpbil/source/models/mira/textures/Mira_metal.jpg";//Path.Combine(relativeLocation, textureSlots.Where(t => t.TextureType == TextureType.Unknown).FirstOrDefault().FilePath);
                }
                catch {
                    //TODO: add handling
                }

                try
                {
                    _material.Roughness = "C:/Users/kpbil/source/models/mira/textures/Mira_rou.jpg";//Path.Combine(relativeLocation, textureSlots.Where(t => t.TextureType == TextureType.Unknown).FirstOrDefault().FilePath);
                }
                catch
                {
                    //TODO: add handling
                }

                mats.Add(_material.MaterialName, _material);
            }

            return(mats);
        }
Exemple #9
0
        public static Assimp.Scene Load(string fileName)
        {
            Assimp.AssimpContext importer = new AssimpContext();
            importer.SetConfig(new Assimp.Configs.NormalSmoothingAngleConfig(0.66f));
            Scene model = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality);

            return(model);
        }
Exemple #10
0
 public static void Load(IEnumerable <string> paths)
 {
     foreach (var path in paths)
     {
         var name = Path.GetFileNameWithoutExtension(path);
         Models.Add(name, AssimpContext.ImportFile(path, Flags).Meshes);
     }
 }
Exemple #11
0
 public static ImportedAnimation ImportFBX(string fbxPath, AnimationImportSettings settings)
 {
     using (var context = new AssimpContext())
     {
         var fbx = context.ImportFile(fbxPath, PostProcessSteps.CalculateTangentSpace | PostProcessSteps.GlobalScale);
         return(ImportFromAssimpScene(fbx, settings));
     }
 }
Exemple #12
0
        public Mesh(string FileName)
        {
            Vertices = new ModelPart <Vertex>();

            Indices = new ModelPart <int>();


            PostProcessSteps Flags = PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate;

            AssimpContext importer = new AssimpContext();

            Scene model = importer.ImportFile(FileName, Flags);


            foreach (Assimp.Mesh mesh in model.Meshes)
            {
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    Vector3D Pos    = mesh.Vertices[i];
                    Vector3D Normal = mesh.Normals[i];
                    Vector3D Tex    = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : new Vector3D();

                    Vertices.Data.Add(new Vertex(new Vector3(Pos.X, Pos.Y, Pos.Z), new Vector3(Normal.X, Normal.Y, Normal.Z), new Vector2(Tex.X, Tex.Y)));
                }



                int indexBase = Indices.Data.Count();

                foreach (Face Faces in mesh.Faces)
                {
                    if (Faces.IndexCount != 3)
                    {
                        continue;
                    }

                    Indices.Data.Add(indexBase + Faces.Indices[0]);
                    Indices.Data.Add(indexBase + Faces.Indices[1]);
                    Indices.Data.Add(indexBase + Faces.Indices[2]);
                }
            }



            Vertices.Count = Vertices.Data.Count();

            Vertices.SizeInBytes = Utilities.SizeOf <Vertex>() * Vertices.Data.Count();

            Vertices.Size = Utilities.SizeOf <Vertex>();



            Indices.Count = Indices.Data.Count();

            Indices.SizeInBytes = Utilities.SizeOf <int>() * Indices.Data.Count();

            Indices.Size = Utilities.SizeOf <int>();
        }
Exemple #13
0
        /// <summary>
        /// Load an FBX file from a file on disk.
        /// </summary>
        /// <param name="filename">
        /// The filename of the FBX file to load.
        /// </param>
        /// <param name="additionalAnimationFiles">
        /// A dictionary mapping of animation names to filenames for additional FBX files to load.
        /// </param>
        /// <returns>
        /// The loaded <see cref="IModel"/>.
        /// </returns>
        public IModel Load(string filename, Dictionary <string, string> additionalAnimationFiles)
        {
            this.LoadAssimpLibrary();

            // Import the scene via AssImp.
            var importer = new AssimpContext();
            const PostProcessSteps ProcessFlags = 0
                                                  | PostProcessSteps.FlipUVs
                                                  | PostProcessSteps.FlipWindingOrder
            ;
            var scene = importer.ImportFile(filename, ProcessFlags);

            VertexPositionNormalTextureBlendable[] vertexes;
            int[]      indices;
            IModelBone boneHierarchy;

            if (scene.MeshCount >= 1)
            {
                var boneWeightingMap = this.BuildBoneWeightingMap(scene);

                boneHierarchy = this.ImportBoneHierarchy(scene.RootNode, scene.Meshes[0]);

                vertexes = this.ImportVertexes(scene, boneWeightingMap);
                indices  = this.ImportIndices(scene);
            }
            else
            {
                boneHierarchy = this.ImportBoneHierarchy(scene.RootNode, null);
                vertexes      = new VertexPositionNormalTextureBlendable[0];
                indices       = new int[0];
            }

            // Create the list of animations, including the null animation.
            var animations = new List <IAnimation>();

            // Import the basic animation.
            if (scene.AnimationCount > 0)
            {
                animations.AddRange(
                    scene.Animations.Select(
                        assimpAnimation => this.ImportAnimation(assimpAnimation.Name, assimpAnimation)));
            }

            // For each additional animation file, import that and add the animation to the existing scene.
            animations.AddRange(
                from kv in additionalAnimationFiles
                let animationImporter = new AssimpContext()
                                        let additionalScene = animationImporter.ImportFile(kv.Value, ProcessFlags)
                                                              where additionalScene.AnimationCount == 1
                                                              select this.ImportAnimation(kv.Key, additionalScene.Animations[0]));

            // Return the resulting model.
            return(new Model(
                       new AnimationCollection(animations),
                       boneHierarchy,
                       vertexes,
                       indices));
        }
Exemple #14
0
        public static void Start()
        {
            Cam = new Object3D("Camera", new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Component3D[] { new Camera3DComponent(75) });

            AssimpContext imp = new AssimpContext();
            Scene         scn = imp.ImportFile(ContentLoader.ContentPath + "/Defaults/Cube.dae");

            Cube = new Object3D("Cube", new Vector3(0, 0, 5), new Vector3(1, 1, 1), new Vector3(0, 0, 0), new Component3D[] { new Renderer3DComponent(scn.Meshes[0], new Vector3(0.1f, 0.1f, 0.1f), new Vector3(1, 0, 0)) });
        }
Exemple #15
0
        public void LoadFile(string FileName)
        {
            AssimpContext Importer = new AssimpContext();

            scene = Importer.ImportFile(FileName, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices
                 | PostProcessSteps.FlipUVs | PostProcessSteps.ValidateDataStructure |
               PostProcessSteps.CalculateTangentSpace | PostProcessSteps.GenerateNormals);
            LoadMeshes();
        }
Exemple #16
0
 public static G3D LoadAssimpFile(string filePath)
 {
     using (var context = new AssimpContext())
     {
         var scene = context.ImportFile(filePath);
         Assert.AreEqual(1, scene.Meshes.Count);
         return(scene.Meshes[0].ToG3D());
     }
 }
Exemple #17
0
        private void Load(string path)
        {
            AssimpContext importer = new AssimpContext();
            Scene         scene    = importer.ImportFile(path, PostProcessSteps.Triangulate);

            //directory = path.(0, path.find_last_of('/'));

            ProcessNode(scene.RootNode, scene);
        }
        static void Main()
        {
            String fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "duck.dae");

            AssimpContext importer = new AssimpContext();
            var           m_model  = importer.ImportFile(fileName);

            return;
        }
        public void TestExportToFile()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\ExportedTriangle.obj");

            //Create a very simple scene a single node with a mesh that has a single face, a triangle and a default material
            Scene scene = new Scene();

            scene.RootNode = new Node("Root");

            Mesh triangle = new Mesh("", PrimitiveType.Triangle);

            triangle.Vertices.Add(new Vector3D(1, 0, 0));
            triangle.Vertices.Add(new Vector3D(5, 5, 0));
            triangle.Vertices.Add(new Vector3D(10, 0, 0));
            triangle.Faces.Add(new Face(new int[] { 0, 1, 2 }));
            triangle.MaterialIndex = 0;

            scene.Meshes.Add(triangle);
            scene.RootNode.MeshIndices.Add(0);

            Material mat = new Material();

            mat.Name = "MyMaterial";
            scene.Materials.Add(mat);

            //Export the scene then read it in and compare!

            AssimpContext context = new AssimpContext();

            Assert.IsTrue(context.ExportFile(scene, path, "obj"));

            Scene importedScene = context.ImportFile(path);

            Assert.IsTrue(importedScene.MeshCount == scene.MeshCount);
            Assert.IsTrue(importedScene.MaterialCount == 2); //Always has the default material, should also have our material

            //Compare the meshes
            Mesh importedTriangle = importedScene.Meshes[0];

            Assert.IsTrue(importedTriangle.VertexCount == triangle.VertexCount);
            for (int i = 0; i < importedTriangle.VertexCount; i++)
            {
                Assert.IsTrue(importedTriangle.Vertices[i].Equals(triangle.Vertices[i]));
            }

            Assert.IsTrue(importedTriangle.FaceCount == triangle.FaceCount);
            for (int i = 0; i < importedTriangle.FaceCount; i++)
            {
                Face importedFace = importedTriangle.Faces[i];
                Face face         = triangle.Faces[i];

                for (int j = 0; j < importedFace.IndexCount; j++)
                {
                    Assert.IsTrue(importedFace.Indices[j] == face.Indices[j]);
                }
            }
        }
Exemple #20
0
        static void Main(string[] args)
        {
            AssimpContext c = new AssimpContext();

            c.SetConfig(new NormalSmoothingAngleConfig(66));
            Scene s = c.ImportFile("test.fbx");

            Console.WriteLine("Hello World!");
        }
Exemple #21
0
        private void loadModel(string path)
        {
            AssimpContext importer = new AssimpContext();

            Assimp.Scene scene = new Assimp.Scene();
            scene = importer.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs);

            directory = path.Substring(0, path.LastIndexOf('/'));
            processNode(scene.RootNode, scene);
        }
Exemple #22
0
        public Model(string path)
        {
            var importer = new AssimpContext();

            importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));

            var scene = importer.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs);

            processNode(scene.RootNode, scene);
        }
Exemple #23
0
 public static Mesh LoadFromModel(string Filename)
 {
     if (Cache.ContainsKey(Filename))
     {
         return(Cache[Filename]);
     }
     Assimp.Scene scene = Context.ImportFile(Filename, PostProcess);
     Cache.Add(Filename, GetMesh(scene));
     return(Cache[Filename]);
 }
Exemple #24
0
        public void LoadAssimpFile(string filePath)
        {
            var scene = context.ImportFile(filePath, PostProcessSteps.Triangulate);

            LoadedMeshes = scene.Meshes
                           .Select(ToMeshData)
                           .ToList();
            CollectInstances(scene.RootNode, Matrix4x4.Identity, LoadedInstances);
            meshesLoaded = true;
        }
        public void TestImportExportFile()
        {
            String colladaPath = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.dae");
            String plyPath     = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.ply");

            AssimpContext context = new AssimpContext();
            Scene         ducky   = context.ImportFile(colladaPath);

            context.ExportFile(ducky, plyPath, "ply");
        }
Exemple #26
0
        private void LoadModel(string path)
        {
            using var importer = new AssimpContext();
            string fullPath = Path.Combine(AppContext.BaseDirectory, path);

            Directory = fullPath.Substring(0, fullPath.LastIndexOf('/'));
            Scene scene = importer.ImportFile(fullPath, PostProcessSteps.ValidateDataStructure | PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.GenerateSmoothNormals);

            ProcessNode(scene.RootNode, scene);
        }
Exemple #27
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            var identity = new ContentIdentity(filename, GetType().Name);

            using (var importer = new AssimpContext())
            {
                _scene = importer.ImportFile(filename,
                                             //PostProcessSteps.FindInstances | // No effect + slow?
                                             PostProcessSteps.FindInvalidData |
                                             PostProcessSteps.FlipUVs |
                                             PostProcessSteps.FlipWindingOrder |
                                             //PostProcessSteps.MakeLeftHanded | // Appears to just mess things up
                                             PostProcessSteps.JoinIdenticalVertices |
                                             PostProcessSteps.ImproveCacheLocality |
                                             PostProcessSteps.OptimizeMeshes |
                                             //PostProcessSteps.OptimizeGraph | // Will eliminate helper nodes
                                             PostProcessSteps.RemoveRedundantMaterials |
                                             PostProcessSteps.Triangulate
                                             );

                _globalInverseXform = _scene.RootNode.Transform;
                _globalInverseXform.Inverse();

                _rootNode = new NodeContent
                {
                    Name      = _scene.RootNode.Name,
                    Identity  = identity,
                    Transform = ToXna(_scene.RootNode.Transform)
                };

                _materials = ImportMaterials(identity, _scene);

                FindMeshes(_scene.RootNode, _scene.RootNode.Transform);

                if (_scene.HasAnimations)
                {
                    var skeleton = CreateSkeleton();
                    CreateAnimation(skeleton);
                }

                // If we have a simple hierarchy with no bones and just the one
                // mesh, we can flatten it out so the mesh is the root node.
                if (_rootNode.Children.Count == 1 && _rootNode.Children[0] is MeshContent)
                {
                    var absXform = _rootNode.Children[0].AbsoluteTransform;
                    _rootNode           = _rootNode.Children[0];
                    _rootNode.Identity  = identity;
                    _rootNode.Transform = absXform;
                }

                _scene.Clear();
            }

            return(_rootNode);
        }
        /// <summary>
        /// loads models, materials, ... based on info in PartData
        /// </summary>
        public override void LoadMesh()
        {
            try
            {
                var lod = partData.Renderable.LodList.First();

                Scene meshScene = assimpImporter.ImportFile(PathResolver.ResolvePath(lod.Mesh, this.mod?.ModFolderPath));
                this.subMeshes = meshScene.Meshes.Select(mesh => ConvertMesh(mesh)).ToArray();


                if (lod.SubMeshList != null)
                {
                    this.materials = lod.SubMeshList.Select(submesh => submesh.Material).ToArray();
                }
                if (lod.SubMeshMap != null)
                {
                    this.materials = meshScene.Materials.Select(material => lod.SubMeshMap[material.Name]?.Material).ToArray();
                }

                if (lod.Pose0 != null && false)
                {
                    Scene pose0Scene = assimpImporter.ImportFile(PathResolver.ResolvePath(lod.Pose0, this.mod?.ModFolderPath));
                    this.pose0 = pose0Scene.Meshes.Select(mesh => ConvertMesh(mesh)).ToArray();
                }
                if (lod.Pose1 != null && false)
                {
                    Scene pose1Scene = assimpImporter.ImportFile(PathResolver.ResolvePath(lod.Pose1, this.mod?.ModFolderPath));
                    this.pose1 = pose1Scene.Meshes.Select(mesh => ConvertMesh(mesh)).ToArray();
                }
                if (lod.Pose2 != null && false)
                {
                    Scene pose2Scene = assimpImporter.ImportFile(PathResolver.ResolvePath(lod.Pose2, this.mod?.ModFolderPath));
                    this.pose2 = pose2Scene.Meshes.Select(mesh => ConvertMesh(mesh)).ToArray();
                }
            }
            catch (Exception e)
            {
                Debug.LogException(new Exception($"\nFailed loading model for part {partData.Uuid}", e));
                // use cuboid from prefab, stretch if bounds found in partdata
                // use diffuse & normal from prefab
            }
        }
        public void TestObjLoad()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\sphere.obj");

            AssimpContext importer = new AssimpContext();
            Scene scene = importer.ImportFile(path);

            Assert.IsNotNull(scene);
            Assert.IsNotNull(scene.RootNode);
            Assert.IsTrue(scene.RootNode.Name.Equals("sphere.obj"));
        }
Exemple #30
0
        public void TestObjLoad()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\sphere.obj");

            AssimpContext importer = new AssimpContext();
            Scene         scene    = importer.ImportFile(path);

            Assert.IsNotNull(scene);
            Assert.IsNotNull(scene.RootNode);
            Assert.IsTrue(scene.RootNode.Name.Equals("sphere.obj"));
        }
Exemple #31
0
        public static Mesh LoadMesh(string path, Material meshMaterial)
        {
            Scene scene = importer.ImportFile(path, PostProcessSteps.MakeLeftHanded | PostProcessSteps.GenerateSmoothNormals);

            Buffer vertexBuffer = MeshLoader.CreateVertexBufferFromMesh(scene.Meshes[0]);
            Buffer indexBuffer  = MeshLoader.CreateIndexBufferFromMesh(scene.Meshes[0]);

            Mesh createdMesh = new Mesh(vertexBuffer, indexBuffer, meshMaterial, 0, scene.Meshes[0].GetIndices().Length);

            return(createdMesh);
        }
        public SimpleOpenGLSample()
            : base()
        {
            Title = "Quack! - AssimpNet Simple OpenGL Sample";

            String fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "duck.dae");

            AssimpContext importer = new AssimpContext();
            importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
            m_model = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality);
            ComputeBoundingBox();
        }
        public void TestMultiSearchDirectoryLoad()
        {
            String fileName = "fenris.lws";
            String[] searchPaths = { Path.Combine(TestHelper.RootPath, "TestFiles\\fenris\\scenes"), Path.Combine(TestHelper.RootPath, "TestFiles\\fenris\\objects") };
            FileIOSystem ioSystem = new FileIOSystem(searchPaths);

            AssimpContext importer = new AssimpContext();
            importer.SetIOSystem(ioSystem);

            //None, using the "target high quality flags caused a crash with this model.
            Scene scene = importer.ImportFile(fileName, PostProcessSteps.None);
            Assert.IsNotNull(scene);
        }
        public void TestIOSystemError()
        {
            String fileName = "duckduck.dae"; //GOOSE!
            String[] searchPaths = { Path.Combine(TestHelper.RootPath, "TestFiles") };
            FileIOSystem ioSystem = new FileIOSystem(searchPaths);

            AssimpContext importer = new AssimpContext();
            importer.SetIOSystem(ioSystem);
            Assert.Throws<AssimpException>(delegate()
            {
                importer.ImportFile(fileName, PostProcessSteps.None);
            });
        }
        public void TestExportToBlob()
        {
            String colladaPath = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.dae");

            AssimpContext context = new AssimpContext();
            Scene ducky = context.ImportFile(colladaPath);
            ExportDataBlob blob = context.ExportToBlob(ducky, "obj");

            Assert.IsTrue(blob.HasData);
            Assert.IsTrue(blob.NextBlob != null);
            Assert.IsTrue(blob.NextBlob.Name.Equals("mtl"));
        }
        public void TestImportExportImportFile()
        {
            String colladaPath = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.dae");
            String plyPath = Path.Combine(TestHelper.RootPath, "TestFiles\\duck2.dae");

            AssimpContext context = new AssimpContext();
            Scene ducky = context.ImportFile(colladaPath);
            context.ExportFile(ducky, plyPath, "collada");

            Scene ducky2 = context.ImportFile(plyPath);
            Assert.IsNotNull(ducky2);
        }
        public void TestExportToFile()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\ExportedTriangle.obj");

            //Create a very simple scene a single node with a mesh that has a single face, a triangle and a default material
            Scene scene = new Scene();
            scene.RootNode = new Node("Root");

            Mesh triangle = new Mesh("", PrimitiveType.Triangle);
            triangle.Vertices.Add(new Vector3D(1, 0, 0));
            triangle.Vertices.Add(new Vector3D(5, 5, 0));
            triangle.Vertices.Add(new Vector3D(10, 0, 0));
            triangle.Faces.Add(new Face(new int[] { 0, 1, 2 }));
            triangle.MaterialIndex = 0;

            scene.Meshes.Add(triangle);
            scene.RootNode.MeshIndices.Add(0);

            Material mat = new Material();
            mat.Name = "MyMaterial";
            scene.Materials.Add(mat);

            //Export the scene then read it in and compare!

            AssimpContext context = new AssimpContext();
            Assert.IsTrue(context.ExportFile(scene, path, "obj"));

            Scene importedScene = context.ImportFile(path);
            Assert.IsTrue(importedScene.MeshCount == scene.MeshCount);
            Assert.IsTrue(importedScene.MaterialCount == 2); //Always has the default material, should also have our material

            //Compare the meshes
            Mesh importedTriangle = importedScene.Meshes[0];

            Assert.IsTrue(importedTriangle.VertexCount == triangle.VertexCount);
            for(int i = 0; i < importedTriangle.VertexCount; i++)
            {
                Assert.IsTrue(importedTriangle.Vertices[i].Equals(triangle.Vertices[i]));
            }

            Assert.IsTrue(importedTriangle.FaceCount == triangle.FaceCount);
            for(int i = 0; i < importedTriangle.FaceCount; i++)
            {
                Face importedFace = importedTriangle.Faces[i];
                Face face = triangle.Faces[i];

                for(int j = 0; j < importedFace.IndexCount; j++)
                {
                    Assert.IsTrue(importedFace.Indices[j] == face.Indices[j]);
                }
            }
        }
        public void TestImportFromFile()
        {
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\sphere.obj");

            AssimpContext importer = new AssimpContext();

            importer.SetConfig(new NormalSmoothingAngleConfig(55.0f));
            importer.Scale = .5f;
            importer.XAxisRotation = 25.0f;
            importer.YAxisRotation = 50.0f;
            LogStream.IsVerboseLoggingEnabled = true;

            Assert.IsTrue(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.RemoveConfigs();

            Assert.IsFalse(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.SetConfig(new NormalSmoothingAngleConfig(65.0f));
            importer.SetConfig(new NormalSmoothingAngleConfig(22.5f));
            importer.RemoveConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName);

            Assert.IsFalse(importer.ContainsConfig(NormalSmoothingAngleConfig.NormalSmoothingAngleConfigName));

            importer.SetConfig(new NormalSmoothingAngleConfig(65.0f));

            Scene scene = importer.ImportFile(path, PostProcessPreset.TargetRealTimeMaximumQuality);

            Assert.IsNotNull(scene);
            Assert.IsTrue((scene.SceneFlags & SceneFlags.Incomplete) != SceneFlags.Incomplete);
        }
        public void TestLoadFreeLibrary()
        {
            if(AssimpLibrary.Instance.IsLibraryLoaded)
                AssimpLibrary.Instance.FreeLibrary();

            AssimpLibrary.Instance.LoadLibrary();

            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.dae");
            AssimpContext importer = new AssimpContext();
            importer.ImportFile(path);
            importer.Dispose();

            AssimpLibrary.Instance.FreeLibrary();
        }
        static void ExportFile(string fileName, string destFolder)
        {
            String targetMeshFile = Path.GetFileNameWithoutExtension(fileName) + ".mesh";
            String targetAnimFile = Path.GetFileNameWithoutExtension(fileName) + ".anim";

            Console.WriteLine("Exporting " + targetMeshFile + "...");

            AssimpContext importer = new AssimpContext();
            importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
            importer.SetConfig(new VertexBoneWeightLimitConfig(4));
            Scene scene = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality | PostProcessSteps.FlipUVs);

            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";

            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

            FileStream fs = new FileStream(Path.Combine(destFolder, targetMeshFile), FileMode.Create);
            BinaryWriter dest = new BinaryWriter(fs);

            MeshBlock meshBlock = new MeshBlock(dest, "MX3D");

            List<MeshNode> nodes = new List<MeshNode>();
            addNodes(nodes, scene.RootNode, scene.Meshes[0]);

            for (int j = 0; j < 1; j++)
            {
                MeshBlock groupBlock = new MeshBlock(dest, "XGRP");

                exportGroup(dest, scene.Meshes[j], scene, nodes);

                groupBlock.EndBlock(dest);
            }

            MeshBlock skeletonDataBlock;
            skeletonDataBlock = new MeshBlock(dest, "XSKL");

            UInt32 boneCount = (UInt32)nodes.Count;
            dest.Write(boneCount);

            for (int j = 0; j < nodes.Count; j++)
            {
                exportBone(dest, nodes[j], scene, j);
            }

            skeletonDataBlock.EndBlock(dest);

            meshBlock.EndBlock(dest);

            dest.Close();
            fs.Close();

            for (int i = 0; i < scene.AnimationCount; i++)
            {
                Animation animation = scene.Animations[i];
                String name = animation.Name;
                if (name.Length <= 0)
                {
                    name = Path.GetFileNameWithoutExtension(targetAnimFile);
                    int p = name.LastIndexOf("@");
                    if (p >= 0)
                    {
                        name = name.Substring(p + 1);
                    }
                }

                Console.WriteLine("Exporting " + name + " animation...");

                fs = new FileStream(Path.Combine(destFolder, targetAnimFile), FileMode.Create);
                dest = new BinaryWriter(fs);

                byte[] tagData = Encoding.ASCII.GetBytes("ANIM");
                dest.Write(tagData);

                float FPS = (float)animation.TicksPerSecond;
                dest.Write(FPS);
                byte loop = 1;
                dest.Write(loop);
                float loopPoint = 0.0f;
                dest.Write(loopPoint);
                float animSpeed = 1.0f;
                dest.Write(animSpeed);

                String nextAnim = "";
                exportString(dest, nextAnim);

                UInt32 channelCount = (UInt32)animation.NodeAnimationChannelCount;
                dest.Write(channelCount);
                for (int j = 0; j < channelCount; j++)
                {
                    NodeAnimationChannel channel = animation.NodeAnimationChannels[j];
                    exportString(dest, channel.NodeName);

                    UInt32 posCount = (UInt32)channel.PositionKeyCount;
                    dest.Write(posCount);
                    for (int k = 0; k < posCount; k++)
                    {
                        float t = (float)channel.PositionKeys[k].Time;
                        float x = channel.PositionKeys[k].Value.X;
                        float y = channel.PositionKeys[k].Value.Y;
                        float z = channel.PositionKeys[k].Value.Z;
                        float w = 1.0f;

                        dest.Write(t);
                        dest.Write(x);
                        dest.Write(y);
                        dest.Write(z);
                        dest.Write(w);
                    }

                    UInt32 rotCount = (UInt32)channel.RotationKeyCount;
                    dest.Write(rotCount);
                    for (int k = 0; k < rotCount; k++)
                    {
                        float t = (float)channel.RotationKeys[k].Time;
                        float x = channel.RotationKeys[k].Value.X;
                        float y = channel.RotationKeys[k].Value.Y;
                        float z = channel.RotationKeys[k].Value.Z;
                        float w = channel.RotationKeys[k].Value.W;

                        dest.Write(t);
                        dest.Write(x);
                        dest.Write(y);
                        dest.Write(z);
                        dest.Write(w);
                    }

                    UInt32 scaleCount = (UInt32)channel.ScalingKeyCount;
                    dest.Write(scaleCount);
                    for (int k = 0; k < scaleCount; k++)
                    {
                        float t = (float)channel.ScalingKeys[k].Time;
                        float x = channel.ScalingKeys[k].Value.X;
                        float y = channel.ScalingKeys[k].Value.Y;
                        float z = channel.ScalingKeys[k].Value.Z;
                        float w = 1.0f;

                        dest.Write(t);
                        dest.Write(x);
                        dest.Write(y);
                        dest.Write(z);
                        dest.Write(w);
                    }

                }

                dest.Close();
                fs.Close();
            }
        }
        private void LoadSceneA()
        {
            Console.WriteLine("Thread A: Starting import.");
            AssimpContext importer = new AssimpContext();
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\Bob.md5mesh");

            new ConsoleLogStream("Thread A:").Attach();
            Console.WriteLine("Thread A: Importing");
            Scene scene = importer.ImportFile(path);
            Console.WriteLine("Thread A: Done importing");
        }
        private void LoadSceneB()
        {
            Console.WriteLine("Thread B: Starting import.");
            AssimpContext importer = new AssimpContext();
            String path = Path.Combine(TestHelper.RootPath, "TestFiles\\duck.dae");

            new ConsoleLogStream("Thread B:").Attach();
            importer.SetConfig(new NormalSmoothingAngleConfig(55.0f));
            Console.WriteLine("Thread B: Importing");
            Scene scene = importer.ImportFile(path);
            Console.WriteLine("Thread B: Done importing");
        }