Beispiel #1
0
    public CustomAssetImporter()
    {
        // Import Settings
        importer = new Assimp.AssimpContext();
        importer.SetConfig(new Assimp.Configs.MeshVertexLimitConfig(60000));
        importer.SetConfig(new Assimp.Configs.MeshTriangleLimitConfig(60000));
        importer.SetConfig(new Assimp.Configs.RemoveDegeneratePrimitivesConfig(true));
        importer.SetConfig(new Assimp.Configs.SortByPrimitiveTypeConfig(Assimp.PrimitiveType.Line | Assimp.PrimitiveType.Point));

        postProcessSteps = Assimp.PostProcessPreset.TargetRealTimeMaximumQuality | Assimp.PostProcessSteps.MakeLeftHanded | Assimp.PostProcessSteps.FlipWindingOrder;
    }
Beispiel #2
0
        public static Ai.Scene Import(string fileName)
        {
            var aiContext = new Ai.AssimpContext();

            aiContext.SetConfig(new Ai.Configs.MeshVertexLimitConfig(32768));
            aiContext.SetConfig(new Ai.Configs.VertexCacheSizeConfig(63));
            aiContext.SetConfig(new Ai.Configs.MaxBoneCountConfig(48));

            var postProcessSteps = (Ai.PostProcessPreset.TargetRealTimeMaximumQuality | Ai.PostProcessSteps.SplitByBoneCount) & ~Ai.PostProcessSteps.FindInstances;

            return(aiContext.ImportFile(fileName, postProcessSteps));
        }
Beispiel #3
0
        public static Ai.Scene Import(string fileName)
        {
            var aiContext = new Ai.AssimpContext();

            aiContext.SetConfig(new Ai.Configs.MeshVertexLimitConfig(32768));
            aiContext.SetConfig(new Ai.Configs.VertexCacheSizeConfig(63));
            aiContext.SetConfig(new Ai.Configs.MaxBoneCountConfig(48));

            return(aiContext.ImportFile(fileName,
                                        Ai.PostProcessSteps.CalculateTangentSpace | Ai.PostProcessSteps.Triangulate |
                                        Ai.PostProcessSteps.SplitLargeMeshes | Ai.PostProcessSteps.ImproveCacheLocality |
                                        Ai.PostProcessSteps.SortByPrimitiveType | Ai.PostProcessSteps.SplitByBoneCount));
        }
Beispiel #4
0
        public static Model Load(Arguments args)
        {
            string extension = Path.GetExtension(args.input_path);
            Model  output    = null;

            if (extension == ".bmd" || extension == ".bdl")
            {
                using (FileStream str = new FileStream(args.input_path, FileMode.Open, FileAccess.Read))
                {
                    EndianBinaryReader reader = new EndianBinaryReader(str, Endian.Big);
                    output = new Model(reader);
                }
            }
            else
            {
                Assimp.AssimpContext cont = new Assimp.AssimpContext();

                // AssImp adds dummy nodes for pivots from FBX, so we'll force them off
                cont.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(false));
                Assimp.Scene aiScene = cont.ImportFile(args.input_path, Assimp.PostProcessSteps.Triangulate);

                output = new Model(aiScene, args);
            }

            return(output);
        }
Beispiel #5
0
        public static Model Load(Arguments args)
        {
            string extension = Path.GetExtension(args.input_path);
            Model  output    = null;

            if (extension == ".bmd" || extension == ".bdl")
            {
                using (FileStream str = new FileStream(args.input_path, FileMode.Open, FileAccess.Read))
                {
                    EndianBinaryReader reader = new EndianBinaryReader(str, Endian.Big);
                    output = new Model(reader, args);
                }
            }
            else
            {
                Assimp.AssimpContext cont = new Assimp.AssimpContext();

                // AssImp adds dummy nodes for pivots from FBX, so we'll force them off
                cont.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(false));

                Assimp.PostProcessSteps postprocess = Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.JoinIdenticalVertices;

                if (args.tristrip_mode == "none")
                {
                    // By not joining identical vertices, the Tri Strip algorithm we use cannot make tristrips,
                    // effectively disabling tri stripping
                    postprocess = Assimp.PostProcessSteps.Triangulate;
                }
                Assimp.Scene aiScene = cont.ImportFile(args.input_path, postprocess);

                output = new Model(aiScene, args);
            }

            return(output);
        }
        public static Ai.Scene ImportFile(string filePath)
        {
            // Set up Assimp context
            var aiContext = new Ai.AssimpContext();

            aiContext.SetConfig(new Ai.Configs.MeshVertexLimitConfig(1500));   // estimate
            aiContext.SetConfig(new Ai.Configs.MeshTriangleLimitConfig(3000)); // estimate
            aiContext.SetConfig(new Ai.Configs.VertexCacheSizeConfig(63));     // PS3/RSX vertex cache size

            // Apply ALL the optimizations
            var postProcessSteps = Ai.PostProcessSteps.ImproveCacheLocality | Ai.PostProcessSteps.FindInvalidData | Ai.PostProcessSteps.FlipUVs | Ai.PostProcessSteps.JoinIdenticalVertices |
                                   Ai.PostProcessSteps.LimitBoneWeights | Ai.PostProcessSteps.Triangulate | Ai.PostProcessSteps.GenerateSmoothNormals | Ai.PostProcessSteps.OptimizeMeshes;

            var aiScene = aiContext.ImportFile(filePath, postProcessSteps);

            return(aiScene);
        }
Beispiel #7
0
        public String Load(string file)
        {
            string result = "";

            this.file = file;
            bb.Max    = Vector3.Zero;
            bb.Min    = Vector3.Zero;
            tex       = null;

            var ctx = new Assimp.AssimpContext();

            var conf = new Assimp.Configs.MeshVertexLimitConfig(ushort.MaxValue);

            ctx.SetConfig(conf);

            try
            {
                oScene = ctx.ImportFile(file,
                                        PostProcessSteps.GenerateNormals |
                                        PostProcessSteps.FindInstances |
                                        PostProcessSteps.FindInvalidData |
                                        PostProcessSteps.FlipUVs |
                                        PostProcessSteps.JoinIdenticalVertices |
                                        PostProcessSteps.ImproveCacheLocality |
                                        PostProcessSteps.OptimizeMeshes |
                                        PostProcessSteps.OptimizeGraph |
                                        PostProcessSteps.RemoveRedundantMaterials |
                                        PostProcessSteps.Triangulate |
                                        PostProcessSteps.SplitLargeMeshes
                                        );

                SetUpVertices();

                if (oScene.MaterialCount > 0)
                {
                    var lstMtl = oScene.Materials[0].GetAllMaterialTextures();

                    if (lstMtl != null && lstMtl.Length > 0)
                    {
                        tex = LoadTextureStream(string.Concat(Path.GetDirectoryName(file), "\\", lstMtl[0].FilePath));
                    }
                }
            }
            catch (Exception e)
            {
                result = e.Message;
            }

            return(result);
        }
        public static Ai.Scene Import(string filePath)
        {
            var aiContext = new Ai.AssimpContext();

            aiContext.SetConfig(new FBXPreservePivotsConfig(false));
            aiContext.SetConfig(new MaxBoneCountConfig(64));
            aiContext.SetConfig(new MeshTriangleLimitConfig(524288));
            aiContext.SetConfig(new MeshVertexLimitConfig(32768));
            aiContext.SetConfig(new VertexBoneWeightLimitConfig(4));
            aiContext.SetConfig(new VertexCacheSizeConfig(63));

            return(aiContext.ImportFile(filePath,
                                        Ai.PostProcessSteps.JoinIdenticalVertices | Ai.PostProcessSteps.Triangulate |
                                        Ai.PostProcessSteps.SplitLargeMeshes | Ai.PostProcessSteps.LimitBoneWeights |
                                        Ai.PostProcessSteps.ImproveCacheLocality | Ai.PostProcessSteps.SortByPrimitiveType |
                                        Ai.PostProcessSteps.SplitByBoneCount | Ai.PostProcessSteps.FlipUVs));
        }
Beispiel #9
0
        public static Model Load(
            string filePath, List <Materials.Material> mat_presets = null,
            TristripOption triopt = TristripOption.DoNotTriStrip,
            bool flipAxis         = false, bool fixNormals = false, string additionalTexPath = null)
        {
            string extension = Path.GetExtension(filePath);
            Model  output    = null;

            if (extension == ".bmd" || extension == ".bdl")
            {
                using (FileStream str = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    EndianBinaryReader reader = new EndianBinaryReader(str, Endian.Big);
                    output = new Model(reader, mat_presets);
                }
            }
            else
            {
                Assimp.AssimpContext cont = new Assimp.AssimpContext();

                // AssImp adds dummy nodes for pivots from FBX, so we'll force them off
                cont.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(false));

                Assimp.PostProcessSteps postprocess = Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.JoinIdenticalVertices;

                if (triopt == TristripOption.DoNotTriStrip)
                {
                    // By not joining identical vertices, the Tri Strip algorithm we use cannot make tristrips,
                    // effectively disabling tri stripping
                    postprocess = Assimp.PostProcessSteps.Triangulate;
                }
                Assimp.Scene aiScene = cont.ImportFile(filePath, postprocess);

                output = new Model(aiScene, filePath, mat_presets, triopt, flipAxis, fixNormals, additionalTexPath);
            }

            return(output);
        }
Beispiel #10
0
 private AssimpContext GetImporter()
 {
     AssimpContext importer = new AssimpContext();
     importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
     return importer;
 }
Beispiel #11
0
		static public AssimpVolume LoadFromFile(string filename)
		{
			string path = Path.Combine("Assets", "Models", filename);

			AssimpContext importer = new AssimpContext();

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

			LogStream logStream = new LogStream
			(
				delegate(string message, string userData)
				{
					Console.Write(message);
				}
			);
			logStream.Attach();

			Scene model = importer.ImportFile(path, PostProcessPreset.TargetRealTimeMaximumQuality);
			Mesh mesh = model.Meshes[0];

			AssimpVolume v = new AssimpVolume();

			List<Vector3> newVertices = new List<Vector3>();
			foreach (Assimp.Vector3D vert in mesh.Vertices)
			{
				newVertices.Add(new Vector3(vert.X, vert.Y, vert.Z));
			}
			v.vertices = newVertices.ToArray();

			v.indices = mesh.GetIndices();

			if (mesh.HasNormals)
			{
				v.generateNormals = false;
				List<Vector3> newNormals = new List<Vector3>();
				foreach (Assimp.Vector3D n in mesh.Normals)
				{
					newNormals.Add(new Vector3(n.X, n.Y, n.Z));
				}
				v.normals = newNormals.ToArray();
			}

			if (mesh.HasTextureCoords(0))
			{
				List<Vector2> newTextureCoords = new List<Vector2>();
				foreach (Assimp.Vector3D tc in mesh.TextureCoordinateChannels[0])
				{
					newTextureCoords.Add(new Vector2(tc.X, tc.Y));
				}
				v.textureCoords = newTextureCoords.ToArray();
			}

			if (mesh.HasVertexColors(0))
			{
				List<Vector3> newColors = new List<Vector3>();
				foreach (Assimp.Color4D c in mesh.VertexColorChannels[0])
				{
					newColors.Add(new Vector3(c.R, c.G, c.B));
				}
				v.colors = newColors.ToArray();
			}

			importer.Dispose();
			return v;
		}
Beispiel #12
0
        public override Node3D LoadAnimNode(string path)
        {
            if (NormBlank == null)
            {
                NormBlank = new Texture.Texture2D("data/tex/normblank.png", Texture.LoadMethod.Single, false);
                DiffBlank = new Texture.Texture2D("data/tex/diffblank.png", Texture.LoadMethod.Single, false);
                SpecBlank = new Texture.Texture2D("data/tex/specblank.png", Texture.LoadMethod.Single, false);
            }

            AnimEntity3D root = new AnimEntity3D();
            string       file = path;

            AssimpContext e = new Assimp.AssimpContext();

            Assimp.Configs.NormalSmoothingAngleConfig c1 = new Assimp.Configs.NormalSmoothingAngleConfig(75);
            e.SetConfig(c1);

            Console.WriteLine("Impporting:" + file);
            Assimp.Scene s = null;
            try
            {
                s = e.ImportFile(file, PostProcessSteps.OptimizeMeshes | PostProcessSteps.OptimizeGraph | PostProcessSteps.FindInvalidData | PostProcessSteps.FindDegenerates | PostProcessSteps.Triangulate | PostProcessSteps.ValidateDataStructure | PostProcessSteps.CalculateTangentSpace);
            }
            catch (AssimpException ae)
            {
                Console.WriteLine(ae);
                Console.WriteLine("Failed to import");
                Environment.Exit(-1);
            }
            Console.WriteLine("Imported.");
            Dictionary <string, Mesh3D> ml = new Dictionary <string, Mesh3D>();
            List <Mesh3D> ml2 = new List <Mesh3D>();

            Console.WriteLine("animCount:" + s.AnimationCount);

            Matrix4x4 tf = s.RootNode.Transform;

            tf.Inverse();

            root.GlobalInverse = ToTK(tf);

            Dictionary <uint, List <VertexWeight> > boneToWeight = new Dictionary <uint, List <VertexWeight> >();

            root.Animator = new Animation.Animator();

            if (s.AnimationCount > 0)
            {
                Console.WriteLine("Processing animations.");
                root.Animator.InitAssImp(s, root);
                Console.WriteLine("Processed.");
                _ta = root.Animator;
            }
            Dictionary <uint, List <VertexWeight> > vertToBoneWeight = new Dictionary <uint, List <VertexWeight> >();

            //s.Animations[0].NodeAnimationChannels[0].
            //s.Animations[0].anim

            // root.Animator.InitAssImp(model);

            List <Vivid.Data.Vertex> _vertices = new List <Vertex>();
            List <Vivid.Data.Tri>    _tris     = new List <Tri>();

            List <Vertex> ExtractVertices(Mesh m, Dictionary <uint, List <VertexWeight> > vtb)
            {
                List <Vertex> rl = new List <Vertex>();

                for (int i = 0; i < m.VertexCount; i++)
                {
                    Vector3D pos  = m.HasVertices ? m.Vertices[i] : new Assimp.Vector3D();
                    Vector3D norm = m.HasNormals ? m.Normals[i] : new Assimp.Vector3D();
                    Vector3D tan  = m.HasTangentBasis ? m.Tangents[i] : new Assimp.Vector3D();
                    Vector3D bi   = m.HasTangentBasis ? m.BiTangents[i] : new Assimp.Vector3D();

                    Vertex nv = new Vertex
                    {
                        Pos    = new OpenTK.Vector3(pos.X, pos.Y, pos.Z),
                        Norm   = new OpenTK.Vector3(norm.X, norm.Y, norm.Z),
                        Tan    = new OpenTK.Vector3(tan.X, tan.Y, tan.Z),
                        BiNorm = new OpenTK.Vector3(bi.X, bi.Y, bi.Z)
                    };

                    if (m.HasTextureCoords(0))
                    {
                        Vector3D coord = m.TextureCoordinateChannels[0][i];
                        nv.UV = new OpenTK.Vector2(coord.X, 1 - coord.Y);
                    }

                    float[] weights     = vtb[(uint)i].Select(w => w.Weight).ToArray();
                    byte[]  boneIndices = vtb[(uint)i].Select(w => (byte)w.VertexID).ToArray();

                    nv.Weight         = weights.First();
                    nv.BoneIndices    = new int[4];
                    nv.BoneIndices[0] = boneIndices[0];
                    if (boneIndices.Length > 1)
                    {
                        nv.BoneIndices[1] = boneIndices[1];
                    }
                    if (boneIndices.Length > 2)
                    {
                        nv.BoneIndices[2] = boneIndices[2];
                    }
                    if (boneIndices.Length > 3)
                    {
                        nv.BoneIndices[3] = boneIndices[3];
                    }
                    rl.Add(nv);
                }

                return(rl);
            }

            root.Mesh = new Mesh3D();

            foreach (Mesh m in s.Meshes)
            {
                ExtractBoneWeightsFromMesh(m, vertToBoneWeight);
                Mesh3D.Subset sub = new Vivid.Data.Mesh3D.Subset
                {
                    VertexCount = m.VertexCount,
                    VertexStart = _vertices.Count,
                    FaceStart   = _tris.Count,
                    FaceCount   = m.FaceCount
                };

                root.Mesh.Subs.Add(sub);

                List <Vertex> verts = ExtractVertices(m, vertToBoneWeight);

                _vertices.AddRange(verts);

                List <short> indices = m.GetIndices().Select(i => (short)(i + (uint)sub.VertexStart)).ToList();

                for (int i = 0; i < indices.Count; i += 3)
                {
                    Tri t = new Tri
                    {
                        V0 = indices[i],
                        V1 = indices[i + 2],
                        v2 = indices[i + 1]
                    };
                    _tris.Add(t);
                }
            }

            root.Mesh.VertexData = _vertices.ToArray();
            root.Mesh.TriData    = _tris.ToArray();

            root.Mesh.FinalAnim();
            root.Renderer = new Visuals.VRMultiPassAnim();

            root.Meshes.Add(root.Mesh.Clone());
            root.Meshes[0].FinalAnim();

            Material.Material3D m1 = new Material.Material3D
            {
                ColorMap    = DiffBlank,
                NormalMap   = NormBlank,
                SpecularMap = SpecBlank
            };
            root.Mesh.Material      = m1;
            root.Meshes[0].Material = root.Mesh.Material;

            Assimp.Material mat = s.Materials[0];
            TextureSlot     t1;

            int sc = mat.GetMaterialTextureCount(TextureType.Unknown);

            Console.WriteLine("SC:" + sc);
            if (mat.HasColorDiffuse)
            {
                m1.Diff = CTV(mat.ColorDiffuse);
            }
            if (mat.HasColorSpecular)
            {
                m1.Spec = CTV(mat.ColorSpecular);
                // Console.WriteLine("Spec:" + vm.Spec);
            }

            if (mat.HasShininess)
            {
                //vm.Shine = 0.3f+ mat.Shininess;
                // Console.WriteLine("Shine:" + vm.Shine);
            }

            //Console.WriteLine("Spec:" + vm.Spec);
            //for(int ic = 0; ic < sc; ic++)
            ///{
            if (sc > 0)
            {
                TextureSlot tex2 = mat.GetMaterialTextures(TextureType.Unknown)[0];
                m1.SpecularMap = new Texture.Texture2D(IPath + "/" + tex2.FilePath, Texture.LoadMethod.Single, false);
            }

            if (mat.GetMaterialTextureCount(TextureType.Normals) > 0)
            {
                TextureSlot ntt = mat.GetMaterialTextures(TextureType.Normals)[0];
                Console.WriteLine("Norm:" + ntt.FilePath);
                m1.NormalMap = new Texture.Texture2D(IPath + "/" + ntt.FilePath, Vivid.Texture.LoadMethod.Single, false);
            }

            if (mat.GetMaterialTextureCount(TextureType.Diffuse) > 0)
            {
                t1 = mat.GetMaterialTextures(TextureType.Diffuse)[0];
                Console.WriteLine("DiffTex:" + t1.FilePath);

                if (t1.FilePath != null)
                {
                    try
                    {
                        // Console.Write("t1:" + t1.FilePath);
                        m1.ColorMap = new Texture.Texture2D(IPath + "/" + t1.FilePath.Replace(".dds", ".png"), Texture.LoadMethod.Single, false);
                        if (File.Exists(IPath + "norm" + t1.FilePath))
                        {
                            // vm.TNorm = new Texture.VTex2D(IPath + "norm" +
                            // t1.FilePath,Texture.LoadMethod.Single, false);

                            // Console.WriteLine("TexLoaded");
                        }
                    }
                    catch
                    {
                    }
                }
                if (true)
                {
                    if (new FileInfo(t1.FilePath).Exists == true)
                    {
                        //  var tex = App.AppSal.CreateTex2D();
                        //  tex.Path = t1.FilePath;
                        // tex.Load();
                        //m2.DiffuseMap = tex;
                    }
                }
            }

            //r1.LocalTurn = new OpenTK.Matrix4(s.Transform.A1, s.Transform.A2, s.Transform.A3, s.Transform.A4, s.Transform.B1, s.Transform.B2, s.Transform.B3, s.Transform.B4, s.Transform.C1, s.Transform.C2, s.Transform.C3, s.Transform.C4, s.Transform.D1, s.Transform.D2, s.Transform.D3, s.Transform.D4);
            root.LocalTurn = new OpenTK.Matrix4(s.RootNode.Transform.A1, s.RootNode.Transform.B1, s.RootNode.Transform.C1, s.RootNode.Transform.D1, s.RootNode.Transform.A2, s.RootNode.Transform.B2, s.RootNode.Transform.C2, s.RootNode.Transform.D2, s.RootNode.Transform.A3, s.RootNode.Transform.B3, s.RootNode.Transform.C3, s.RootNode.Transform.D3, s.RootNode.Transform.A4, s.RootNode.Transform.B4, s.RootNode.Transform.C4, s.RootNode.Transform.D4);

            root.LocalTurn = ToTK(s.RootNode.Children[0].Transform);
            OpenTK.Matrix4 lt = root.LocalTurn;

            root.LocalTurn = lt.ClearTranslation();
            root.LocalTurn = root.LocalTurn.ClearScale();
            root.LocalPos  = lt.ExtractTranslation();

            root.LocalScale = lt.ExtractScale();

            root.AnimName = "Run";

            return(root);

            /*
             * foreach (var m in s.Meshes)
             * {
             *  Console.WriteLine("M:" + m.Name + " Bones:" + m.BoneCount);
             *  Console.WriteLine("AA:" + m.HasMeshAnimationAttachments);
             *
             *  var vm = new Material.Material3D();
             *  vm.TCol = DiffBlank;
             *  vm.TNorm = NormBlank;
             *  vm.TSpec = SpecBlank;
             *  var m2 = new VMesh(m.GetIndices().Length, m.VertexCount);
             *  ml2.Add(m2);
             *  // ml.Add(m.Name, m2);
             *  for (int b = 0; b < m.BoneCount; b++)
             *  {
             *      uint index = 0;
             *      string name = m.Bones[b].Name;
             *  }
             *  m2.Mat = vm;
             *  // root.AddMesh(m2);
             *  m2.Name = m.Name;
             *  var mat = s.Materials[m.MaterialIndex];
             *  TextureSlot t1;
             *
             *  var sc = mat.GetMaterialTextureCount(TextureType.Unknown);
             *  Console.WriteLine("SC:" + sc);
             *  if (mat.HasColorDiffuse)
             *  {
             *      vm.Diff = CTV(mat.ColorDiffuse);
             *  }
             *  if (mat.HasColorSpecular)
             *  {
             *      vm.Spec = CTV(mat.ColorSpecular);
             *      Console.WriteLine("Spec:" + vm.Spec);
             *  }
             *  if (mat.HasShininess)
             *  {
             *      //vm.Shine = 0.3f+ mat.Shininess;
             *      Console.WriteLine("Shine:" + vm.Shine);
             *  }
             *
             *  Console.WriteLine("Spec:" + vm.Spec);
             *  //for(int ic = 0; ic < sc; ic++)
             *  ///{
             *  if (sc > 0)
             *  {
             *      var tex2 = mat.GetMaterialTextures(TextureType.Unknown)[0];
             *      vm.TSpec = new Texture.VTex2D(IPath + "/" + tex2.FilePath, Texture.LoadMethod.Single, false);
             *  }
             *
             *  if (mat.GetMaterialTextureCount(TextureType.Normals) > 0)
             *  {
             *      var ntt = mat.GetMaterialTextures(TextureType.Normals)[0];
             *      Console.WriteLine("Norm:" + ntt.FilePath);
             *      vm.TNorm = new Texture.VTex2D(IPath + "/" + ntt.FilePath, Fusion3D.Texture.LoadMethod.Single, false);
             *  }
             *
             *  if (mat.GetMaterialTextureCount(TextureType.Diffuse) > 0)
             *  {
             *      t1 = mat.GetMaterialTextures(TextureType.Diffuse)[0];
             *      Console.WriteLine("DiffTex:" + t1.FilePath);
             *
             *      if (t1.FilePath != null)
             *      {
             *          try
             *          {
             *              // Console.Write("t1:" + t1.FilePath);
             *              vm.TCol = new Texture.VTex2D(IPath + "/" + t1.FilePath.Replace(".dds", ".png"), Texture.LoadMethod.Single, false);
             *              if (File.Exists(IPath + "norm" + t1.FilePath))
             *              {
             *                  // vm.TNorm = new Texture.VTex2D(IPath + "norm" +
             *                  // t1.FilePath,Texture.LoadMethod.Single, false);
             *
             *                  // Console.WriteLine("TexLoaded");
             *              }
             *          }
             *          catch
             *          {
             *          }
             *      }
             *      if (true)
             *      {
             *          if (new FileInfo(t1.FilePath).Exists == true)
             *          {
             *              //  var tex = App.AppSal.CreateTex2D();
             *              //  tex.Path = t1.FilePath;
             *              // tex.Load();
             *              //m2.DiffuseMap = tex;
             *          }
             *      }
             *  }
             *
             *  ExtractBoneWeightsFromMesh(m, vertToBoneWeight);
             *
             *  for (int i = 0; i < m2.NumVertices; i++)
             *  {
             *      var v = m.Vertices[i];// * new Vector3D(15, 15, 15);
             *      var n = m.Normals[i];
             *      var t = m.TextureCoordinateChannels[0];
             *      Vector3D tan, bi;
             *      if (m.Tangents != null && m.Tangents.Count > 0)
             *      {
             *          tan = m.Tangents[i];
             *          bi = m.BiTangents[i];
             *      }
             *      else
             *      {
             *          tan = new Vector3D(0, 0, 0);
             *          bi = new Vector3D(0, 0, 0);
             *      }
             *      if (t.Count() == 0)
             *      {
             *          m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(new Vector3D(0, 0, 0)));
             *      }
             *      else
             *      {
             *          var tv = t[i];
             *          tv.Y = 1.0f - tv.Y;
             *          m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(tv));
             *      }
             *
             *      var weights = vertToBoneWeight[(uint)i].Select(w => w.Weight).ToArray();
             *      var boneIndices = vertToBoneWeight[(uint)i].Select(w => (byte)w.VertexID).ToArray();
             *
             *      m2.SetVertexBone(i, weights.First(), boneIndices);
             *
             *      //var v = new PosNormalTexTanSkinned(pos, norm.ToVector3(), texC.ToVector2(), tan.ToVector3(), weights.First(), boneIndices);
             *      //verts.Add(v);
             *  }
             *  int[] id = m.GetIndices();
             *  int fi = 0;
             *  uint[] nd = new uint[id.Length];
             *  for (int i = 0; i < id.Length; i += 3)
             *  {
             *      //Tri t = new Tri();
             *      //t.V0 = (int)nd[i];
             *      // t.V1 = (int)nd[i + 1];
             *      // t.v2 = (int)nd[i + 2];
             *
             *      // nd[i] = (uint)id[i];
             *      m2.SetTri(i / 3, (int)id[i], (int)id[i + 1], (int)id[i + 2]);
             *  }
             *
             *  m2.Indices = nd;
             *  //m2.Scale(AssImpImport.ScaleX, AssImpImport.ScaleY, AssImpImport.ScaleZ);
             *  m2.Final();
             * }
             *
             * ProcessNode(root, s.RootNode, ml2);
             *
             * foreach (var ac in root.Clips)
             * {
             *  Console.WriteLine("Anims:" + ac);
             * }
             * root.AnimName = "Run";
             * /*
             * while (true)
             * {
             * }
             */

            return(root as Node3D);
        }
Beispiel #13
0
        public override Node3D LoadNode(string path)
        {
            if (NormBlank == null)
            {
                NormBlank = new Texture.Texture2D("data/tex/normblank.png", Texture.LoadMethod.Single, false);
                DiffBlank = new Texture.Texture2D("data/tex/diffblank.png", Texture.LoadMethod.Single, false);
                SpecBlank = new Texture.Texture2D("data/tex/specblank.png", Texture.LoadMethod.Single, false);
            }
            string ip = path;
            int    ic = ip.LastIndexOf("/");

            if (ic < 1)
            {
                ic = ip.LastIndexOf("\\");
            }
            if (ic > 0)
            {
                IPath = ip.Substring(0, ic);
            }

            Entity3D root = new Entity3D();
            string   file = path;

            AssimpContext e = new Assimp.AssimpContext();

            Assimp.Configs.NormalSmoothingAngleConfig c1 = new Assimp.Configs.NormalSmoothingAngleConfig(75);
            e.SetConfig(c1);

            Console.WriteLine("Impporting:" + file);
            Assimp.Scene s = null;
            try
            {
                s = e.ImportFile(file, PostProcessSteps.OptimizeGraph | PostProcessSteps.FindInvalidData | PostProcessSteps.FindDegenerates | PostProcessSteps.Triangulate | PostProcessSteps.ValidateDataStructure | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.GenerateNormals | PostProcessSteps.FixInFacingNormals | PostProcessSteps.GenerateSmoothNormals);
                if (s.HasAnimations)
                {
                    return(LoadAnimNode(path));
                }
            }
            catch (AssimpException ae)
            {
                Console.WriteLine(ae);
                Console.WriteLine("Failed to import");
                Environment.Exit(-1);
            }
            Console.WriteLine("Imported.");
            Dictionary <string, Mesh3D> ml = new Dictionary <string, Mesh3D>();
            List <Mesh3D> ml2 = new List <Mesh3D>();

            Console.WriteLine("animCount:" + s.AnimationCount);

            Matrix4x4 tf = s.RootNode.Transform;

            tf.Inverse();

            root.GlobalInverse = ToTK(tf);

            Dictionary <uint, List <VertexWeight> > boneToWeight = new Dictionary <uint, List <VertexWeight> >();

            //root.Animator = new Animation.Animator();

            //s.Animations[0].NodeAnimationChannels[0].
            //s.Animations[0].anim

            // root.Animator.InitAssImp(model);

            foreach (Mesh m in s.Meshes)
            {
                Console.WriteLine("M:" + m.Name + " Bones:" + m.BoneCount);
                Console.WriteLine("AA:" + m.HasMeshAnimationAttachments);

                Material.Material3D vm = new Material.Material3D
                {
                    ColorMap    = DiffBlank,
                    NormalMap   = NormBlank,
                    SpecularMap = SpecBlank
                };
                Mesh3D m2 = new Mesh3D(m.GetIndices().Length, m.VertexCount);
                ml2.Add(m2);
                // ml.Add(m.Name, m2);
                for (int b = 0; b < m.BoneCount; b++)
                {
                    string name = m.Bones[b].Name;
                }
                m2.Material = vm;
                // root.AddMesh(m2);
                m2.Name = m.Name;
                Assimp.Material mat = s.Materials[m.MaterialIndex];
                TextureSlot     t1;

                int sc = mat.GetMaterialTextureCount(TextureType.Unknown);
                Console.WriteLine("SC:" + sc);
                if (mat.HasColorDiffuse)
                {
                    vm.Diff = CTV(mat.ColorDiffuse);
                    Console.WriteLine("Diff:" + vm.Diff);
                }
                if (mat.HasColorSpecular)
                {
                    // vm.Spec = CTV ( mat.ColorSpecular );
                    Console.WriteLine("Spec:" + vm.Spec);
                }
                if (mat.HasShininess)
                {
                    //vm.Shine = 0.3f+ mat.Shininess;
                    Console.WriteLine("Shine:" + vm.Shine);
                }

                Console.WriteLine("Spec:" + vm.Spec);
                //for(int ic = 0; ic < sc; ic++)
                ///{
                if (sc > 0)
                {
                    TextureSlot tex2 = mat.GetMaterialTextures(TextureType.Unknown)[0];
                    // vm.SpecularMap = new Texture.Texture2D ( IPath + "/" + tex2.FilePath, Texture.LoadMethod.Single, false );
                }

                if (mat.GetMaterialTextureCount(TextureType.Normals) > 0)
                {
                    TextureSlot ntt = mat.GetMaterialTextures(TextureType.Normals)[0];
                    Console.WriteLine("Norm:" + ntt.FilePath);
                    vm.NormalMap = new Texture.Texture2D(IPath + "/" + ntt.FilePath, Vivid.Texture.LoadMethod.Single, false);
                }

                if (mat.GetMaterialTextureCount(TextureType.Diffuse) > 0)
                {
                    t1 = mat.GetMaterialTextures(TextureType.Diffuse)[0];
                    Console.WriteLine("DiffTex:" + t1.FilePath);

                    if (t1.FilePath != null)
                    {
                        //Console.WriteLine ( "Tex:" + t1.FilePath );
                        // Console.Write("t1:" + t1.FilePath);
                        vm.ColorMap = new Texture.Texture2D(IPath + "/" + t1.FilePath.Replace(".dds", ".png"), Texture.LoadMethod.Single, false);
                        if (File.Exists(IPath + "/" + "norm_" + t1.FilePath))
                        {
                            vm.NormalMap = new Texture.Texture2D(IPath + "/" + "norm_" + t1.FilePath, Texture.LoadMethod.Single, false);
                        }
                    }
                }

                for (int i = 0; i < m2.NumVertices; i++)
                {
                    Vector3D v = m.Vertices[i];// * new Vector3D(15, 15, 15);

                    Vector3D n = new Vector3D(0, 1, 0);

                    if (m.Normals != null && m.Normals.Count > i)
                    {
                        n = m.Normals[i];
                    }

                    List <Vector3D> t = m.TextureCoordinateChannels[0];
                    Vector3D        tan, bi;
                    if (m.Tangents != null && m.Tangents.Count > 0)
                    {
                        tan = m.Tangents[i];
                        bi  = m.BiTangents[i];
                    }
                    else
                    {
                        tan = new Vector3D(0, 0, 0);
                        bi  = new Vector3D(0, 0, 0);
                    }
                    if (t.Count() == 0)
                    {
                        m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(new Vector3D(0, 0, 0)));
                    }
                    else
                    {
                        Vector3D tv = t[i];
                        tv.Y = 1.0f - tv.Y;
                        m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(tv));
                    }

                    //var v = new PosNormalTexTanSkinned(pos, norm.ToVector3(), texC.ToVector2(), tan.ToVector3(), weights.First(), boneIndices);
                    //verts.Add(v);
                }
                int[]  id = m.GetIndices();
                uint[] nd = new uint[id.Length];
                for (int i = 0; i < id.Length; i += 3)
                {
                    //Tri t = new Tri();
                    //t.V0 = (int)nd[i];
                    // t.V1 = (int)nd[i + 1];
                    // t.v2 = (int)nd[i + 2];

                    // nd[i] = (uint)id[i];
                    if (i + 2 < id.Length)
                    {
                        m2.SetTri(i / 3, id[i], id[i + 1], id[i + 2]);
                    }
                }

                m2.Indices = nd;
                //m2.Scale(AssImpImport.ScaleX, AssImpImport.ScaleY, AssImpImport.ScaleZ);
                //m2.GenerateTangents ( );

                m2.Final();
            }

            ProcessNode(root, s.RootNode, ml2);

            /*
             * while (true)
             * {
             * }
             */
            return(root as Node3D);
        }
Beispiel #14
0
 /// <summary>
 /// Loads the model using Assimp. (Throws on failure.)
 /// </summary>
 /// <param name="fileName">The absolute path and name of the model.</param>
 /// <returns>The Assimp scene.</returns>
 private static Assimp.Scene LoadAssimp(string fileName)
 {
     using (var importer = new AssimpContext())
     {
         importer.SetConfig(new Assimp.Configs.RemoveDegeneratePrimitivesConfig(true));
         return importer.ImportFile(fileName,
                                    PostProcessSteps.FindDegenerates |
                                    PostProcessSteps.FindInvalidData |
                                    PostProcessSteps.FlipUVs |               // Required for Direct3D
                                    PostProcessSteps.FlipWindingOrder |      // Required for Direct3D
                                    PostProcessSteps.JoinIdenticalVertices |
                                    PostProcessSteps.ImproveCacheLocality |
                                    PostProcessSteps.OptimizeMeshes |
                                    PostProcessSteps.Triangulate);
     }
 }
Beispiel #15
0
 static void Main(string[] args)
 {
     string[] strs = Directory.GetFiles(Environment.CurrentDirectory, "*.dae", SearchOption.TopDirectoryOnly);
     foreach (string path in strs)
     {
         try
         {
             using (AssimpContext ACont = new AssimpContext())
             {
                 ACont.SetConfig(new NormalSmoothingAngleConfig(66f));
                 Scene scene = ACont.ImportFile(path, PostProcessSteps.Triangulate);
                 if (!scene.HasAnimations)
                 {
                     Console.WriteLine("Skipping " + path);
                     continue;
                 }
                 Animation anim = scene.Animations[0];
                 if (!anim.HasNodeAnimations)
                 {
                     Console.WriteLine("Invalid animation in " + path);
                     continue;
                 }
                 StringBuilder sb = new StringBuilder();
                 sb.Append("// mcmonkey's animation details file format v0.2\n");
                 sb.Append("general\n");
                 sb.Append("{\n");
                 sb.Append("\tlength: ").Append((anim.DurationInTicks / anim.TicksPerSecond).ToString()).Append(";\n");
                 sb.Append("}\n");
                 for (int i = 0; i < anim.NodeAnimationChannelCount; i++)
                 {
                     NodeAnimationChannel node = anim.NodeAnimationChannels[i];
                     sb.Append(node.NodeName).Append('\n');
                     sb.Append("{\n");
                     Node found = LookForMatch(scene.RootNode, node.NodeName);
                     string pNode = "<none>";
                     if (found != null)
                     {
                         pNode = found.Parent.Name;
                     }
                     sb.Append("\tparent: " + pNode + ";\n");
                     /*Bone bfound = LookForBone(scene, node.NodeName);
                     Matrix4x4 mat = Matrix4x4.Identity;
                     if (bfound != null)
                     {
                         mat = bfound.OffsetMatrix;
                         //bpos = bfound.OffsetMatrix.C1 + "=" + bfound.OffsetMatrix.C2 + "=" + bfound.OffsetMatrix.C3;
                         //bpos = bfound.OffsetMatrix.A4 + "=" + bfound.OffsetMatrix.B4 + "=" + bfound.OffsetMatrix.C4;
                     }*/
                     /*sb.Append("\toffset: " + mat.A1 + "=" + mat.A2 + "=" + mat.A3 + "=" + mat.A4 + "=" +
                         mat.B1 + "=" + mat.B2 + "=" + mat.B3 + "=" + mat.B4 + "=" +
                         mat.C1 + "=" + mat.C2 + "=" + mat.C3 + "=" + mat.C4 + "=" +
                         mat.D1 + "=" + mat.D2 + "=" + mat.D3 + "=" + mat.D4 +";\n");*/
                     if (node.HasPositionKeys)
                     {
                         sb.Append("\tpositions: ");
                         for (int x = 0; x < node.PositionKeyCount; x++)
                         {
                             VectorKey key = node.PositionKeys[x];
                             sb.Append(key.Time.ToString() + "=" + key.Value.X.ToString() + "=" + key.Value.Y.ToString() + "=" + key.Value.Z.ToString() + " ");
                         }
                         sb.Append(";\n");
                     }
                     if (node.HasRotationKeys)
                     {
                         sb.Append("\trotations: ");
                         for (int x = 0; x < node.RotationKeyCount; x++)
                         {
                             QuaternionKey key = node.RotationKeys[x];
                             sb.Append(key.Time.ToString() + "=" + key.Value.X.ToString() + "=" + key.Value.Y.ToString() + "=" + key.Value.Z.ToString() + "=" + key.Value.W + " ");
                         }
                         sb.Append(";\n");
                     }
                     // TODO: Should scaling matter? Probably not.
                     sb.Append("}\n");
                 }
                 File.WriteAllText(path + ".anim", sb.ToString());
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("Processing " + path + ": " + ex.ToString());
         }
     }
 }
Beispiel #16
0
        /// <summary>
        /// Construct a scene given a file name, throw if loading fails
        /// </summary>
        /// <param name="file">File name to be loaded</param>
        public Scene(string file)
        {
            _file = file;
            _baseDir = Path.GetDirectoryName(file);

            _logStore = new LogStore();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                using (var imp = new AssimpContext())
                {
                    LogStream.IsVerboseLoggingEnabled = true;
                    using(var pipe = new LogPipe(_logStore))
                    {
                        // Assimp configuration:

                        //  - if no normals are present, generate them using a threshold
                        //    angle of 66 degrees.
                        imp.SetConfig(new NormalSmoothingAngleConfig(66.0f));

                        // start with TargetRealTimeMaximumQuality and add/remove flags
                        // according to the import configuration
                        var postprocess = GetPostProcessStepsFlags();

                        //  - request lots of post processing steps, the details of which
                        //    can be found in the TargetRealTimeMaximumQuality docs.
                        _raw = imp.ImportFile(file, postprocess);
                        if (_raw == null)
                        {
                            Dispose();
                            throw new Exception("failed to read file: " + file);
                        }

                        _incomplete = _raw.SceneFlags.HasFlag(SceneFlags.Incomplete);
                    }
                }
            }
            catch(AssimpException ex)
            {
                Dispose();
                throw new Exception("failed to read file: " + file + " (" + ex.Message + ")");
            }

            stopwatch.Stop();
            _loadingTime = stopwatch.ElapsedMilliseconds;

            _animator = new SceneAnimator(this);
            _textureSet = new TextureSet(BaseDir);
            LoadTextures();

            // compute a bounding box (AABB) for the scene we just loaded
            ComputeBoundingBox(out _sceneMin, out _sceneMax, out _sceneCenter);
            _pivot = _sceneCenter;

            CountVertsAndFaces(out _totalVertexCount, out _totalTriangleCount, out _totalLineCount, out _totalPointCount);

            CreateRenderingBackend();
        }
Beispiel #17
0
        public Mesh Import(string filename)
        {
            using (var importer = new AssimpContext())
            {
                //importer.AttachLogStream(new LogStream((msg, userData) =>
                //{
                //	Common.Log.WriteLine(msg);
                //}));

                var mesh = new Mesh();

                importer.SetConfig(new Assimp.Configs.VertexBoneWeightLimitConfig(4));
                //importer.ZAxisRotation = (float)(System.Math.PI / 2.0);

                var model = importer.ImportFile(filename, PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate
                    | PostProcessSteps.GenerateNormals | PostProcessSteps.LimitBoneWeights | PostProcessSteps.GenerateUVCoords);

                foreach (var meshToImport in model.Meshes)
                {
                    // Validate sub mesh data
                    if (meshToImport.PrimitiveType != PrimitiveType.Triangle)
                    {
                        Common.Log.WriteLine("{0}:{1} invalid primitive type {2} should be Triangle", filename, meshToImport.Name, meshToImport.PrimitiveType);
                        continue;
                    }

                    if (!meshToImport.HasNormals)
                    {
                        Common.Log.WriteLine("{0}:{1} does not have any normals", filename, meshToImport.Name);
                        continue;
                    }

                    if (!meshToImport.HasTangentBasis)
                    {
                        Common.Log.WriteLine("{0}:{1} does not have any tangents", filename, meshToImport.Name);
                        continue;
                    }

                    if (meshToImport.TextureCoordinateChannelCount == 0)
                    {
                        Common.Log.WriteLine("{0}:{1} does not have any texture channels", filename, meshToImport.Name);
                        continue;
                    }

                    var subMesh = new SubMesh();
                    subMesh.BoundingSphereRadius = 0;

                    // Create vertex format
                    if (meshToImport.HasBones)
                    {
                        subMesh.VertexFormat = new Renderer.VertexFormat(new Renderer.VertexFormatElement[]
                        {
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Position, Renderer.VertexPointerType.Float, 3, 0),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Normal, Renderer.VertexPointerType.Float, 3, sizeof(float) * 3),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Tangent, Renderer.VertexPointerType.Float, 3, sizeof(float) * 6),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.TexCoord, Renderer.VertexPointerType.Float, 2, sizeof(float) * 9),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.BoneIndex, Renderer.VertexPointerType.Float, 4, sizeof(float) * 11),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.BoneWeight, Renderer.VertexPointerType.Float, 4, sizeof(float) * 15),
                        });
                    }
                    else
                    {
                        subMesh.VertexFormat = new Renderer.VertexFormat(new Renderer.VertexFormatElement[]
                        {
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Position, Renderer.VertexPointerType.Float, 3, 0),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Normal, Renderer.VertexPointerType.Float, 3, sizeof(float) * 3),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.Tangent, Renderer.VertexPointerType.Float, 3, sizeof(float) * 6),
                            new Renderer.VertexFormatElement(Renderer.VertexFormatSemantic.TexCoord, Renderer.VertexPointerType.Float, 2, sizeof(float) * 9),
                        });
                    }

                    subMesh.TriangleCount = meshToImport.FaceCount;

                    Vertex[] vertices = new Vertex[meshToImport.VertexCount];

                    var positions = meshToImport.Vertices;
                    var normals = meshToImport.Normals;
                    var tangents = meshToImport.Tangents;
                    var texCoords = meshToImport.TextureCoordinateChannels[0];

                    // Setup vertex data
                    for (var i = 0; i < vertices.Length; i++)
                    {
                        vertices[i].Position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z);
                        vertices[i].Normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z);
                        vertices[i].Tangent = new Vector3(tangents[i].X, tangents[i].Y, tangents[i].Z);
                        vertices[i].TexCoord = new Vector2(texCoords[i].X, texCoords[i].Y);

                        var length = vertices[i].Position.Length;
                        if (subMesh.BoundingSphereRadius < length)
                            subMesh.BoundingSphereRadius = length;
                    }

                    // Map bone weights if they are available
                    if (meshToImport.HasBones)
                    {
                        var bones = meshToImport.Bones;

                        for (var i = 0; i < bones.Count; i++)
                        {
                            var bone = bones[i];

                            if (!bone.HasVertexWeights)
                                continue;

                            foreach (var weight in bone.VertexWeights)
                            {
                                var index = weight.VertexID;

                                var vertex = vertices[index];

                                if (vertex.BoneCount == 0)
                                {
                                    vertex.BoneIndex.X = i;
                                    vertex.BoneWeight.X = weight.Weight;
                                }
                                else if (vertex.BoneCount == 1)
                                {
                                    vertex.BoneIndex.Y = i;
                                    vertex.BoneWeight.Y = weight.Weight;
                                }
                                else if (vertex.BoneCount == 2)
                                {
                                    vertex.BoneIndex.Z = i;
                                    vertex.BoneWeight.Z = weight.Weight;
                                }
                                else if (vertex.BoneCount == 3)
                                {
                                    vertex.BoneIndex.W = i;
                                    vertex.BoneWeight.W = weight.Weight;
                                }

                                vertex.BoneCount++;
                                vertices[index] = vertex;
                            }
                        }
                    }

                    using (var memStream = new MemoryStream(meshToImport.VertexCount * subMesh.VertexFormat.Size))
                    {
                        using (var writer = new BinaryWriter(memStream))
                        {
                            for (int i = 0; i < meshToImport.VertexCount; i++)
                            {
                                writer.Write(vertices[i].Position);
                                writer.Write(vertices[i].Normal);
                                writer.Write(vertices[i].Tangent);
                                writer.Write(vertices[i].TexCoord);

                                if (meshToImport.HasBones)
                                {
                                    writer.Write(vertices[i].BoneIndex);
                                    writer.Write(vertices[i].BoneWeight);
                                }
                            }

                            subMesh.Vertices = memStream.GetBuffer();
                        }
                    }

                    using (var memStream = new MemoryStream(meshToImport.VertexCount * subMesh.VertexFormat.Size))
                    {
                        using (var writer = new BinaryWriter(memStream))
                        {
                            var indices = meshToImport.GetIndices();
                            foreach (var index in indices)
                            {
                                writer.Write(index);
                            }
                            subMesh.Indices = memStream.GetBuffer();
                        }
                    }

                    if (model.HasMaterials)
                    {
                        var material = model.Materials[meshToImport.MaterialIndex].Name;

                        if (!material.StartsWith("/materials/"))
                        {
                            material = "/materials/" + material;
                        }

                        subMesh.Material = material;
                    }
                    else
                    {
                        subMesh.Material = "no_material";
                    }

                    mesh.SubMeshes.Add(subMesh);
                }

                return mesh;
            }
        }
Beispiel #18
0
        public override GraphNode3D LoadNode(string path)
        {
            GraphEntity3D root = new GraphEntity3D();
            string        file = path;

            var e  = new Assimp.AssimpContext();
            var c1 = new Assimp.Configs.NormalSmoothingAngleConfig(45);

            e.SetConfig(c1);
            Console.WriteLine("Impporting:" + file);
            Assimp.Scene s = null;
            try
            {
                s = e.ImportFile(file, PostProcessSteps.CalculateTangentSpace | PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.Triangulate | PostProcessSteps.GenerateNormals);
            }
            catch (AssimpException ae)
            {
                Console.WriteLine(ae);
                Console.WriteLine("Failed to import");
            }
            Console.WriteLine("Imported.");
            Dictionary <string, VMesh> ml = new Dictionary <string, VMesh>();
            List <VMesh> ml2 = new List <VMesh>();

            foreach (var m in s.Meshes)
            {
                var vm = new Material.Material3D();

                var m2 = new VMesh(m.VertexCount, m.GetIndices().Length);
                ml2.Add(m2);
                // ml.Add(m.Name, m2);

                m2.Mat = vm;
                // root.AddMesh(m2);
                m2.Name = m.Name;
                var         mat = s.Materials[m.MaterialIndex];
                TextureSlot t1;

                if (mat.GetMaterialTextureCount(TextureType.Diffuse) > 0)
                {
                    t1 = mat.GetMaterialTextures(TextureType.Diffuse)[0];


                    if (t1.FilePath != null)
                    {
                        vm.TCol = new Tex.Tex2D(IPath + t1.FilePath, false);
                        Console.WriteLine("TexLoaded");
                    }
                    if (true)
                    {
                        if (new FileInfo(t1.FilePath).Exists == true)
                        {
                            //  var tex = App.AppSal.CreateTex2D();
                            //  tex.Path = t1.FilePath;
                            // tex.Load();
                            //m2.DiffuseMap = tex;
                        }
                    }
                }
                for (int i = 0; i < m2.NumVertices; i++)
                {
                    var      v = m.Vertices[i];
                    var      n = m.Normals[i];
                    var      t = m.TextureCoordinateChannels[0];
                    Vector3D tan, bi;
                    if (m.Tangents != null && m.Tangents.Count > 0)
                    {
                        tan = m.Tangents[i];
                        bi  = m.BiTangents[i];
                    }
                    else
                    {
                        tan = new Vector3D(0, 0, 0);
                        bi  = new Vector3D(0, 0, 0);
                    }
                    if (t.Count() == 0)
                    {
                        m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(t[i]));
                    }
                    else
                    {
                        m2.SetVertex(i, Cv(v), Cv(tan), Cv(bi), Cv(n), Cv2(t[i]));
                    }
                }
                int[]  id = m.GetIndices();
                int    fi = 0;
                uint[] nd = new uint[id.Length];
                for (int i = 0; i < id.Length; i++)
                {
                    nd[i] = (uint)id[i];
                }

                m2.Indices = nd;

                m2.Final();
            }

            ProcessNode(root, s.RootNode, ml2);


            return(root as GraphNode3D);
        }
Beispiel #19
0
 public ModelLoader(Device device)
 {
     m_device = device;
     m_importer = new AssimpContext();
     m_importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
 }
 public void LoadContent()
 {
     songs.Add("Melee Menu", new SoundPlayer(@"C:\Users\Lee\Documents\GitHub\SmackBrosClient\SmackBrosClient\files\menu.wav"));
     //OpenGL gl = openGLControl.OpenGL;
     String fileName = System.IO.Path.Combine(System.IO.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();
 }