Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        public static void ExportFile(Ai.Scene scene, string path)
        {
            var aiContext = new Ai.AssimpContext();

            aiContext.XAxisRotation = 90;
            aiContext.ExportFile(scene, path, "collada", Ai.PostProcessSteps.FlipUVs);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Import a mesh from a model file.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Mesh Load(string path)
        {
            Mesh mesh = new Mesh()
            {
                Path = path
            };

            a.AssimpContext context = new a.AssimpContext();
            a.Scene         scene   = context.ImportFile(path, a.PostProcessSteps.Triangulate);
            a.Mesh          aMesh   = scene.Meshes[0];

            mesh.vertices = new Vector4[aMesh.VertexCount];
            mesh.normals  = new Vector4[aMesh.VertexCount];
            mesh.uvs      = new Vector4[aMesh.VertexCount];

            for (int i = 0; i < aMesh.VertexCount; i++)
            {
                a.Vector3D aVertex = aMesh.Vertices[i];
                a.Vector3D aNormal = aMesh.Normals[i];
                a.Vector3D aUv     = aMesh.TextureCoordinateChannels[0][i];

                mesh.vertices[i] = new Vector4(aVertex.X, aVertex.Y, aVertex.Z, 1f);
                mesh.normals[i]  = new Vector4(aNormal.X, aNormal.Y, aNormal.Z, 0f);
                mesh.uvs[i]      = new Vector4(aUv.X, aUv.Y, 0f, 0f);
            }
            mesh.indices = aMesh.GetIndices();

            return(mesh);
        }
Exemplo n.º 5
0
        // Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
        private void loadModel(string path)
        {
            try
            {
                // Read file via ASSIMP
                Assimp.AssimpContext importer = new Assimp.AssimpContext();
                Scene scene = importer.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs);
                // Check for errors

                /*if (scene.SceneFlags == SceneFlags.Incomplete || Node.Equals(scene.RootNode, 0)) // if is Not Zero
                 * {
                 *  Console.WriteLine("ERROR::ASSIMP::");
                 *  return;
                 * }*/
                // Retrieve the directory path of the filepath
                this.directory = path.Substring(0, path.LastIndexOf('/'));

                // Process ASSIMP's root node recursively
                this.processNode(scene.RootNode, scene);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Program.bithack3D, "ERROR::ASSIMP::" + ex.ToString());
                Program.bithack3D.BeginInvoke(new MethodInvoker(Program.bithack3D.Close));
            }
        }
Exemplo n.º 6
0
        public void LoadFile(string path, string fileName, int texUnit)
        {
            RootPath = path;
            var assimpNetimporter = new Assimp.AssimpContext();

            assimpNetScene = assimpNetimporter.ImportFile(path + "\\" + fileName);
            Initialize(texUnit);
        }
Exemplo n.º 7
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     AssimpContext = new Assimp.AssimpContext();
     RebuildSurfaceList();
     UpdateSurfaceComboBox();
     //FillModelsGridView();
     HasInitialized = true;
 }
Exemplo n.º 8
0
        private void Window_Load(object sender, EventArgs e)
        {
            myObj  = new MyObj();
            camera = new Camera(window.Width, window.Height);
            cube   = new Cube(camera.shaderProgram);
            var importer = new Assimp.AssimpContext();

            scene = importer.ImportFile("samplescene.blend");
        }
Exemplo n.º 9
0
        public static void Export(Ai.Scene aiScene, string fileName, Ai.PostProcessSteps postProcessSteps = Ai.PostProcessSteps.None)
        {
            var aiContext = new Ai.AssimpContext();

            var formatExtension = Path.GetExtension(fileName).Substring(1);
            var formatId        = aiContext.GetSupportedExportFormats()
                                  .First(x => x.FileExtension.Equals(formatExtension, StringComparison.OrdinalIgnoreCase)).FormatId;

            aiContext.ExportFile(aiScene, fileName, formatId, postProcessSteps);
        }
Exemplo n.º 10
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;
    }
Exemplo n.º 11
0
 public void SetUp()
 {
     var assimpNetimporter = new Assimp.AssimpContext();
     Assimp.LogStream.IsVerboseLoggingEnabled = true;
     var logger = new Assimp.ConsoleLogStream();
     logger.Attach();
     assimpNetScene = assimpNetimporter.ImportFile(filename);
     logger.Detach();
     var assimpSharpImporter = new AssimpSharp.XFile.XFileImporter();
     assimpSharpScene = new AssimpSharp.Scene();
     assimpSharpImporter.InternReadFile(filename, assimpSharpScene);
 }
Exemplo n.º 12
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));
        }
Exemplo n.º 13
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));
        }
Exemplo n.º 14
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 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);
        }
Exemplo n.º 16
0
        private void loadCollisionModel(string path, MeshLoader loader)
        {
            var assimp = new ai.AssimpContext();

            ai.Scene scene = assimp.ImportFile(Util.AbsolutePath(path), ai.PostProcessSteps.DropNormals);

            if (scene == null || scene.RootNode == null || scene.SceneFlags.HasFlag(ai.SceneFlags.Incomplete))
            {
                Console.WriteLine($"Assimp error when importing file \'{path}\'");
                return;
            }

            directory = path.Substring(0, path.LastIndexOf("/") + 1);
            Meshes    = new List <Mesh <Vertex> >();

            proccessNode(scene.RootNode, scene, loader);
        }
        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));
        }
Exemplo n.º 18
0
        public ModelMesh GetMeshByFilePath(string filePath)
        {
            if (_meshCache.ContainsKey(filePath)) return _meshCache[filePath];

            var assimpContext = new Assimp.AssimpContext();
            var assimpScene = assimpContext.ImportFile(filePath, PostProcessSteps.GenerateNormals | PostProcessSteps.GenerateUVCoords | PostProcessSteps.Triangulate);

            if (assimpScene.MeshCount > 1) throw new NotSupportedException("Currently are just single meshs supported.");

            var assimpMesh = assimpScene.Meshes.First();

            var modelMesh = new ModelMesh
            {
                Mesh = new Mesh(_device, GenerateGeometryDataFromAssimpMesh(assimpMesh)),
                Material = GenerateMaterialFromMesh(assimpMesh.MaterialIndex, assimpScene)
            };
            _meshCache.Add(filePath, modelMesh);
            return modelMesh;
        }
Exemplo n.º 19
0
		public override void Import (Stream input, Stream output, string filename) {
			using (var importer = new AssimpContext()) {
				var scene = importer.ImportFileFromStream(input,
					PostProcessSteps.Triangulate | PostProcessSteps.SortByPrimitiveType | PostProcessSteps.GenerateNormals,
					Path.GetExtension(filename));
				using (var tw = new TarWriter(output)) {
					var textures = new Dictionary<string, string>();
					using (var ms = new MemoryStream()) {
						using (var bw = new BinaryWriter(ms)) {
							this.WriteModel(scene, bw, textures);
							bw.Flush();
							//this.PrintNode(scene, scene.RootNode, 0);
							ms.Position = 0;
							tw.Write(ms, ms.Length, "model.bin");
						}
					}
					this.WriteTextures(scene, tw, textures);
				}
			}
		}
Exemplo n.º 20
0
        public static Model LoadFromFile(string Path)
        {
            Model model = new Model();
            AssimpContext Context = new AssimpContext();
            Scene scene = Context.ImportFile(Path);
            foreach(Mesh mesh in scene.Meshes)
            {
                model.Components.Add(new ModelComponent(
                    mesh.Name,
                    mesh.Vertices,
                    mesh.GetIndices(),
                    mesh.TextureCoordinateChannels[0],
                    mesh.Normals,
                    mesh.Tangents,
                    mesh.BiTangents,
                    scene.Materials[mesh.MaterialIndex])
                    );
            }

            return model;
        }
Exemplo n.º 21
0
        private static void ImportGenericModel(String path, out Scene scene)
        {
            try
            {
                using (LogStream logStream = new LogStream(delegate(String msg, String userData) { Console.WriteLine(msg); }))
                {

                    logStream.Attach();

                    using (AssimpContext importer = new AssimpContext())
                        scene = importer.ImportFile(path, PostProcessPreset.TargetRealTimeMaximumQuality);

                    logStream.Detach();
                }
            }
            catch (Exception exception)
            {
                scene = null;
                System.Windows.MessageBox.Show(exception.Message);
            }
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        public ExportDialog(MainWindow main)
        {
            _main = main;
            InitializeComponent();

            using (var v = new Assimp.AssimpContext())
            {
                _formats = v.GetSupportedExportFormats();
                foreach (var format in _formats)
                {
                    comboBoxExportFormats.Items.Add(format.Description + "  (" + format.FileExtension + ")");
                }
                comboBoxExportFormats.SelectedIndex         = ExportSettings.Default.ExportFormatIndex;
                comboBoxExportFormats.SelectedIndexChanged += (object s, EventArgs e) =>
                {
                    ExportSettings.Default.ExportFormatIndex = comboBoxExportFormats.SelectedIndex;
                    UpdateFileName(true);
                };
            }

            textBoxFileName.KeyPress += (object s, KeyPressEventArgs e) =>
            {
                _changedText = true;
            };

            // Respond to updates in the main window - the export dialog is non-modal and
            // always takes the currently selected file at the time the export button
            // is pressed.
            _main.SelectedTabChanged += (Tab tab) =>
            {
                UpdateFileName();
                UpdateCaption();
            };

            UpdateFileName();
            UpdateCaption();
        }
Exemplo n.º 24
0
        public ExportDialog(MainWindow main)
        {
            _main = main;
            InitializeComponent();

            using (var v = new AssimpContext())
            {
                _formats = v.GetSupportedExportFormats();
                foreach (var format in _formats)
                {
                    comboBoxExportFormats.Items.Add(format.Description + "  (" + format.FileExtension + ")");
                }
                comboBoxExportFormats.SelectedIndex = ExportSettings.Default.ExportFormatIndex;
                comboBoxExportFormats.SelectedIndexChanged += (object s, EventArgs e) =>
                {
                    ExportSettings.Default.ExportFormatIndex = comboBoxExportFormats.SelectedIndex;
                    UpdateFileName(true);
                };
            }

            textBoxFileName.KeyPress += (object s, KeyPressEventArgs e) =>
            {
                _changedText = true;
            };

            // Respond to updates in the main window - the export dialog is non-modal and
            // always takes the currently selected file at the time the export button
            // is pressed.
            _main.SelectedTabChanged += (Tab tab) =>
            {
                UpdateFileName();
                UpdateCaption();
            };

            UpdateFileName();
            UpdateCaption();
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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();
        }
        public override bool Execute(List<string> args)
        {
            if (args.Count != 1)
                return false;

            var builder = new RenderModelBuilder(_info.Version);

            // Add a root node
            var node = builder.AddNode(new RenderModel.Node
            {
                Name = _stringIds.GetStringId("street_cone"),
                ParentNode = -1,
                FirstChildNode = -1,
                NextSiblingNode = -1,
                DefaultRotation = new Vector4(0, 0, 0, -1),
                DefaultScale = 1,
                InverseForward = new Vector3(1, 0, 0),
                InverseLeft = new Vector3(0, 1, 0),
                InverseUp = new Vector3(0, 0, 1),
            });

            // Begin building the default region and permutation
            builder.BeginRegion(_stringIds.GetStringId("default"));
            builder.BeginPermutation(_stringIds.GetStringId("default"));

            using (var importer = new AssimpContext())
            {
                Scene model;
                using (var logStream = new LogStream((msg, userData) => Console.WriteLine(msg)))
                {
                    logStream.Attach();
                    model = importer.ImportFile(args[0],
                        PostProcessSteps.CalculateTangentSpace |
                        PostProcessSteps.GenerateNormals |
                        PostProcessSteps.JoinIdenticalVertices |
                        PostProcessSteps.SortByPrimitiveType |
                        PostProcessSteps.PreTransformVertices |
                        PostProcessSteps.Triangulate);
                    logStream.Detach();
                }

                Console.WriteLine("Assembling vertices...");

                // Build a multipart mesh from the model data,
                // with each model mesh mapping to a part of one large mesh and having its own material
                builder.BeginMesh();
                ushort partStartVertex = 0;
                ushort partStartIndex = 0;
                var vertices = new List<RigidVertex>();
                var indices = new List<ushort>();
                foreach (var mesh in model.Meshes)
                {
                    for (var i = 0; i < mesh.VertexCount; i++)
                    {
                        var position = mesh.Vertices[i];
                        var normal = mesh.Normals[i];
                        var uv = mesh.TextureCoordinateChannels[0][i];
                        var tangent = mesh.Tangents[i];
                        var bitangent = mesh.BiTangents[i];
                        vertices.Add(new RigidVertex
                        {
                            Position = new Vector4(position.X, position.Y, position.Z, 1),
                            Normal = new Vector3(normal.X, normal.Y, normal.Z),
                            Texcoord = new Vector2(uv.X, uv.Y),
                            Tangent = new Vector4(tangent.X, tangent.Y, tangent.Z, 1),
                            Binormal = new Vector3(bitangent.X, bitangent.Y, bitangent.Z),
                        });
                    }

                    // Build the index buffer
                    var meshIndices = mesh.GetIndices();
                    indices.AddRange(meshIndices.Select(i => (ushort)(i + partStartVertex)));

                    // Define a material and part for this mesh
                    var material = builder.AddMaterial(new RenderMaterial
                    {
                        RenderMethod = _cache.Tags[0x101F],
                    });
                    builder.DefinePart(material, partStartIndex, (ushort)meshIndices.Length, (ushort)mesh.VertexCount);

                    // Move to the next part
                    partStartVertex += (ushort)mesh.VertexCount;
                    partStartIndex += (ushort)meshIndices.Length;
                }

                // Bind the vertex and index buffers
                builder.BindRigidVertexBuffer(vertices, node);
                builder.BindIndexBuffer(indices, PrimitiveType.TriangleList);
                builder.EndMesh();
            }

            builder.EndPermutation();
            builder.EndRegion();

            Console.WriteLine("Building Blam mesh data...");

            var resourceStream = new MemoryStream();
            var renderModel = builder.Build(_info.Serializer, resourceStream);

            Console.WriteLine("Writing resource data...");

            // Add a new resource for the model data
            var resources = new ResourceDataManager();
            resources.LoadCachesFromDirectory(_fileInfo.DirectoryName);
            resourceStream.Position = 0;
            resources.Add(renderModel.Geometry.Resource, ResourceLocation.Resources, resourceStream);

            Console.WriteLine("Writing tag data...");

            using (var cacheStream = _fileInfo.Open(FileMode.Open, FileAccess.ReadWrite))
            {
                var tag = _cache.Tags[0x3317];
                var context = new TagSerializationContext(cacheStream, _cache, _stringIds, tag);
                _info.Serializer.Serialize(context, renderModel);
            }
            Console.WriteLine("Model imported successfully!");
            return true;
        }
Exemplo n.º 29
0
        private void MenuImportMesh_Click(object sender, RoutedEventArgs e)
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
            openDlg.FileName = ""; // Default file name
            openDlg.DefaultExt = ".*"; // Default file extension
            openDlg.Filter = "All files |*.*"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = openDlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = openDlg.FileName;

                //Create a new importer
                AssimpContext importer = new AssimpContext();

                //This is how we add a configuration (each config is its own class)
                //NormalSmoothingAngleConfig config = new NormalSmoothingAngleConfig(66.0f);
                //importer.SetConfig(config);

                var flags = PostProcessPreset.TargetRealTimeMaximumQuality | PostProcessSteps.Triangulate | PostProcessSteps.SortByPrimitiveType | PostProcessSteps.FlipUVs;

                //Import the model. All configs are set. The model
                //is imported, loaded into managed memory. Then the unmanaged memory is released, and everything is reset.
                Scene model = importer.ImportFile(filename, flags);

                var mesh = new Hatzap.Models.Mesh();

                Assimp.Mesh aMesh = null;

                foreach (var item in model.Meshes)
                {
                    if (item.PrimitiveType != Assimp.PrimitiveType.Triangle)
                        continue;

                    aMesh = item;
                    break;
                }

                if (aMesh != null)
                {
                    AssimpConvertor ac = new AssimpConvertor();

                    mesh = ac.FromAssimp(aMesh);
                }
                else
                {
                    Debug.WriteLine("ERROR: No triangle meshes found in imported model.");
                }

                importer.Dispose();

                if (mesh == null)
                    return;

                filename = System.IO.Path.GetFileNameWithoutExtension(filename);

                filename += ".mesh";

                // Configure save file dialog box
                Microsoft.Win32.SaveFileDialog saveDlg = new Microsoft.Win32.SaveFileDialog();
                saveDlg.FileName = filename; // Default file name
                saveDlg.DefaultExt = ".mesh"; // Default file extension
                saveDlg.Filter = "Mesh files (.mesh)|*.mesh"; // Filter files by extension

                // Show save file dialog box
                result = saveDlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    // Save document
                    filename = saveDlg.FileName;

                    MeshManager meshManager = new MeshManager();

                    using (var fs = File.OpenWrite(filename))
                    {
                        meshManager.TemporarySaveAsset(mesh, fs);
                    }
                }
            }
        }
Exemplo n.º 30
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());
         }
     }
 }
Exemplo n.º 31
0
        public static MeshModel Load(Stream stream, string formatHint)
        {
            using (AssimpContext importer = new AssimpContext())
            {
                var scene = importer.ImportFileFromStream(
                    stream,
                    PostProcessSteps.Triangulate |
                    // PostProcessSteps.PreTransformVertices |
                    PostProcessSteps.GenerateUVCoords |
                    PostProcessSteps.GenerateNormals,
                    formatHint);

                List<Mesh> meshes = new List<Mesh>();
                for (int i = 0; i < scene.MeshCount; i++)
                {
                    var mesh = scene.Meshes[i];
                    var indices = mesh.GetIndices();

                    int texture = 6;

                    BlockVertex[] vertices = new BlockVertex[mesh.VertexCount];
                    var src = mesh.Vertices;
                    var normals = mesh.HasNormals ? mesh.Normals : null;
                    var uvs = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0] : null;
                    for (int v = 0; v < vertices.Length; v++)
                    {
                        vertices[v].position = src[v].TK();
                        vertices[v].color = Vector3.One;
                        if (normals != null)
                            vertices[v].normal = normals[v].TK();
                        if (uvs != null)
                            vertices[v].uv = uvs[v].TK();
                        else
                            vertices[v].uv = 0.5f * Vector3.One;

                        // Set texture ID of the model
                        vertices[v].uv.Z = texture;
                    }

                    meshes.Add(new Mesh(indices, vertices, texture));
                }

                return new MeshModel(meshes);
            }
        }
        private bool ImportGenericModel()
        {
            LogStream logStream = new LogStream(delegate (String msg, String userData) { Console.WriteLine(msg); });

            try
            {
                logStream.Attach();
                using (AssimpContext importer = new AssimpContext())
                    Scene = importer.ImportFile(ModelPath, PostProcessPreset.TargetRealTimeMaximumQuality);

                logStream.Detach();    
                logStream.Dispose();

                if (Scene == null)
                    return false;
                return true;
            }
            catch (Exception exception)
            {
                logStream.Detach();
                logStream.Dispose();
                System.Windows.MessageBox.Show("An error appear : " + exception.Message);
                return false;
            }
        }
Exemplo n.º 33
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;
		}
Exemplo n.º 34
0
        protected override void OnLoad(EventArgs e)
        {
            Debug.WriteLine("OnLoad()");

            /*thread = new Thread(new ThreadStart(() =>
            {
                view = WebCore.CreateWebView(Width, Height, WebViewType.Offscreen);

                //WebCore.AutoUpdatePeriod = 30;

                view.IsTransparent = true;

                finishedLoading = false;

                var path = Path.Combine(new String[] {
                    Directory.GetCurrentDirectory(),
                    "TestWebPages\\index.html"
                });

                path = "http://lasoft.fi/";

                // Load some content.
                view.Source = new Uri(path);

                // Handle the LoadingFrameComplete event.
                // For this example, we use a lambda expression.
                view.LoadingFrameComplete += (s, eargs) =>
                {
                    if (!eargs.IsMainFrame)
                        return;

                    UploadWebpageToGPU((WebView)s);
                    finishedLoading = true;
                };

                if (WebCore.UpdateState == WebCoreUpdateState.NotUpdating)
                    WebCore.Run();

            }));

            thread.Start();*/

            GPUCapabilities.Initialize();

            Debug.WriteLine("GPUCapabilities.Version=" + GPUCapabilities.Version);
            Debug.WriteLine("GPUCapabilities.GLSL=" + GPUCapabilities.GLSL);
            Debug.WriteLine("GPUCapabilities.Instancing=" + GPUCapabilities.Instancing);
            Debug.WriteLine("GPUCapabilities.MaxVaryingFloats=" + GPUCapabilities.MaxVaryingFloats);
            Debug.WriteLine("GPUCapabilities.MaxVaryingVectors=" + GPUCapabilities.MaxVaryingVectors);
            Debug.WriteLine("GPUCapabilities.SeamlessCubemaps=" + GPUCapabilities.SeamlessCubemaps);
            Debug.WriteLine("GPUCapabilities.TextureCompression=" + GPUCapabilities.TextureCompression);
            Debug.WriteLine("GPUCapabilities.AnisotrophicFiltering=" + GPUCapabilities.AnisotrophicFiltering);
            Debug.WriteLine("GPUCapabilities.MaxAnisotrophyLevel=" + GPUCapabilities.MaxAnisotrophyLevel);

            if (GPUCapabilities.SeamlessCubemaps)
                GL.Enable(EnableCap.TextureCubeMapSeamless);

            GLState.DepthTest = true;
            GLState.AlphaBleding = true;
            GLState.CullFace = true;

            SceneManager.Initialize(500, 5, 20, Vector3.Zero);
            SceneManager.CullByObject = false;

            renderQueue = new RenderQueue();
            renderQueue.AllowInstancing = true;

            viewPort = new Vector2(Width, Height);

            camera = new Hatzap.Camera(this);

            camera.SetAsCurrent();

            camera.Position = new Vector3(0, 1, 1);
            camera.Target = new Vector3(-1, 0, 0);

            camera.Update(0);
            camera.DirectionLock = true;

            camera.Rotate(new Vector2(-(float)Math.PI / 2.5f, 0));

            // Now camera.Position changes whenever Target changes, and the camera angle stays locked.
            // Camera's distance from it's target can be controlled from camera.Distance property now.

            FontCollection fonts = new FontCollection();

            fonts.Fonts.Add(new FontInfo()
            {
                FontFamily = "OpenSans-Regular",
                FontDataFile = "Assets/Fonts/OpenSans-Regular.ttf_sdf.txt",
                FontTextureFile = "Assets/Fonts/OpenSans-Regular.ttf_sdf.png"
            });

            XML.Write.ToFile(fonts, "Assets/Fonts/collection.xml");

            //Console.WriteLine("Test test ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ");

            FontManager.LoadCollection(fonts);

            ShaderCollection collection = new ShaderCollection();

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/Model.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/Model.frag",
                    Type = ShaderType.FragmentShader
                }}),
                Name = "Model"
            });

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/Text.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/Text.frag",
                    Type = ShaderType.FragmentShader
                }}),
                Name = "Text"
            });

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/Gui.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/Gui.frag",
                    Type = ShaderType.FragmentShader
                }}),
                Name = "Gui"
            });

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/GuiImage.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/GuiImage.frag",
                    Type = ShaderType.FragmentShader
                }}),
                Name = "Gui.Image"
            });

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel2.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel2.frag",
                    Type = ShaderType.FragmentShader
                },/*new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel.geom",
                    Type = ShaderType.GeometryShader
                }*/}),
                Name = "SimpleModel"
            });

            collection.ShaderPrograms.Add(new ShaderProgramInfo()
            {
                Shaders = new List<ShaderInfo>(new[]{ new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel2.vert",
                    Type = ShaderType.VertexShader
                },new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel1.frag",
                    Type = ShaderType.FragmentShader
                },/*new ShaderInfo() {
                    Path = "Assets/Shaders/SimpleModel.geom",
                    Type = ShaderType.GeometryShader
                }*/}),
                Name = "Textureless"
            });

            //XML.Write.ToFile(collection, "Assets/Shaders/collection.xml");

            ShaderManager.LoadCollection(collection);

            Time.Initialize();
            UserInput.Initialize(this, typeof(AccurateMouse), typeof(Hatzap.Input.Keyboard));
            UserInput.Mouse.ClickInterval = 0.5f;
            GuiRoot.Initialize(this);

            GuiRoot.Root.Texture = new TextureArray();

            TextureMeta guiTextureMeta = new TextureMeta()
            {
                FileName = "Assets/Textures/greySheet.png",
                Width = 512,
                Height = 512,
                PixelInternalFormat = PixelInternalFormat.Rgba,
                PixelFormat = PixelFormat.Bgra,
                PixelType = PixelType.UnsignedByte,
                Precompressed = false,
                Quality = new TextureQuality()
                {
                    Anisotrophy = 0,
                    Filtering = TextureFiltering.Nearest,
                    TextureWrapMode_S = OpenTK.Graphics.OpenGL.TextureWrapMode.Clamp,
                    TextureWrapMode_T = OpenTK.Graphics.OpenGL.TextureWrapMode.Clamp,
                },
            };

            GuiRoot.Root.Texture.Load(guiTextureMeta);

            ElementCollection guiElements = new ElementCollection()
            {
                Elements = new List<WidgetInfo> {
                    new WidgetInfo(){
                        WidgetType = typeof(Button).ToString(),
                        Slices = new List<GuiTextureRegion> {
                            new GuiTextureRegion() { // Top left
                                Offset = new Vector2(49,433),
                                Size = new Vector2(6,4),
                                Page = 0
                            }, new GuiTextureRegion() { // Top center
                                Offset = new Vector2(55,433),
                                Size = new Vector2(37,4),
                                Page = 0
                            }, new GuiTextureRegion() { // Top Right
                                Offset = new Vector2(92,433),
                                Size = new Vector2(6,4),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle left
                                Offset = new Vector2(49,437),
                                Size = new Vector2(6,36),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle center
                                Offset = new Vector2(55,437),
                                Size = new Vector2(37,36),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle right
                                Offset = new Vector2(92,437),
                                Size = new Vector2(6,36),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom left
                                Offset = new Vector2(49,473),
                                Size = new Vector2(6,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom center
                                Offset = new Vector2(55,473),
                                Size = new Vector2(37,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom right
                                Offset = new Vector2(92,473),
                                Size = new Vector2(6,5),
                                Page = 0
                            },
                        },
                    },
                    new WidgetInfo(){
                        WidgetType = typeof(Window).ToString(),
                        Slices = new List<GuiTextureRegion> {
                             new GuiTextureRegion() { // Top left
                                Offset = new Vector2(190,98),
                                Size = new Vector2(7,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Top center
                                Offset = new Vector2(195,98),
                                Size = new Vector2(86,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Top Right
                                Offset = new Vector2(283,98),
                                Size = new Vector2(7,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle left
                                Offset = new Vector2(190,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle center
                                Offset = new Vector2(197,103),
                                Size = new Vector2(86,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle right
                                Offset = new Vector2(283,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle left
                                Offset = new Vector2(190,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle center
                                Offset = new Vector2(197,103),
                                Size = new Vector2(86,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle right
                                Offset = new Vector2(283,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom left
                                Offset = new Vector2(190,192),
                                Size = new Vector2(7,6),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom center
                                Offset = new Vector2(197,192),
                                Size = new Vector2(86,6),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom right
                                Offset = new Vector2(283,192),
                                Size = new Vector2(7,6),
                                Page = 0
                            }
                        },
                    },
                    new WidgetInfo(){
                        WidgetType = typeof(Panel).ToString(),
                        Slices = new List<GuiTextureRegion> {
                            new GuiTextureRegion() { // Top left
                                Offset = new Vector2(190,98),
                                Size = new Vector2(7,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Top center
                                Offset = new Vector2(195,98),
                                Size = new Vector2(86,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Top Right
                                Offset = new Vector2(283,98),
                                Size = new Vector2(7,5),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle left
                                Offset = new Vector2(190,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle center
                                Offset = new Vector2(197,103),
                                Size = new Vector2(86,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Middle right
                                Offset = new Vector2(283,103),
                                Size = new Vector2(7,89),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom left
                                Offset = new Vector2(190,192),
                                Size = new Vector2(7,6),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom center
                                Offset = new Vector2(197,192),
                                Size = new Vector2(86,6),
                                Page = 0
                            }, new GuiTextureRegion() { // Bottom right
                                Offset = new Vector2(283,192),
                                Size = new Vector2(7,6),
                                Page = 0
                            }
                        },
                    },
                }
            };

            XML.Write.ToFile(guiElements, "Assets/Gui/elements.xml");

            GridContainer mainGuiGrid = new GridContainer();
            mainGuiGrid.Columns = 1;
            mainGuiGrid.Rows = 3;
            mainGuiGrid.CellWidths.Add(1280);
            mainGuiGrid.RowHeights.Add(30);
            mainGuiGrid.RowHeights.Add(0);
            mainGuiGrid.RowHeights.Add(30);
            mainGuiGrid.Anchor = new Anchor();
            mainGuiGrid.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
            mainGuiGrid.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
            mainGuiGrid.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
            mainGuiGrid.Anchor.Directions[AnchorDirection.Bottom] = AnchorType.Snap;
            mainGuiGrid.Position = new Vector2(0, 0);
            mainGuiGrid.Size = new Vector2(400, 200);

            Panel leftPanel = new Panel();
            leftPanel.Anchor = new Anchor();
            leftPanel.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
            leftPanel.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
            leftPanel.Anchor.Directions[AnchorDirection.Bottom] = AnchorType.Snap;

            leftPanel.Position = new Vector2(100, 100);
            leftPanel.Size = new Vector2(300, 10);
            leftPanel.Color = new Vector4(0.1f, 0.1f, 0.1f, 1f);
            leftPanel.RightAnchorOffset = -10.0f;

            leftPanel.TextureRegion = guiElements.GetInfo(leftPanel).Slices.ToArray();

            Panel menuBar = new Panel();
            menuBar.Anchor = new Anchor();
            menuBar.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
            menuBar.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
            menuBar.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;

            menuBar.Position = new Vector2(100, 100);
            menuBar.Size = new Vector2(300, 30);
            menuBar.Color = new Vector4(0.1f, 0.1f, 0.1f, 1f);

            menuBar.TextureRegion = guiElements.GetInfo(leftPanel).Slices.ToArray();

            Panel bottomBar = new Panel();
            bottomBar.Anchor = new Anchor();
            bottomBar.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
            bottomBar.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
            bottomBar.Anchor.Directions[AnchorDirection.Bottom] = AnchorType.Snap;

            bottomBar.Position = new Vector2(0, 690);
            bottomBar.Size = new Vector2(0, 30);
            bottomBar.Color = new Vector4(0.1f, 0.1f, 0.1f, 1f);

            bottomBar.TextureRegion = guiElements.GetInfo(leftPanel).Slices.ToArray();

            #region StackContainer test
            StackContainer stack = new StackContainer();
            {
                Button btn = new Button();
                Button btn2 = new Button();
                Button btn3 = new Button();
                Button btn4 = new Button();

                stack.AddChildWidget(btn);
                stack.AddChildWidget(btn2);
                stack.AddChildWidget(btn3);
                stack.AddChildWidget(btn4);

                btn.Color = new Vector4(1.5f, 1.5f, 1.5f, 1);
                btn.Text = "Button 1";
                btn.TextColor = new Vector4(0, 0, 0, 1);
                btn.OnClick += (m) =>
                {
                    //btn.Text = "Clicked " + m.ToString();
                };
                btn.Anchor = new Anchor();
                btn.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
                btn.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
                btn.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
                btn.Position = new Vector2(100, 100);
                btn.Size = new Vector2(150, 50);
                btn.TextureRegion = guiElements.Elements[0].Slices.ToArray();

                btn2.Color = new Vector4(0.2f, 0.2f, 0.2f, 1);
                btn2.Text = "Button 2";
                btn2.OnClick += (m) =>
                {
                    btn2.Text = "Clicked " + m.ToString();
                };
                btn2.Anchor = new Anchor();
                btn2.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
                btn2.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
                btn2.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
                btn2.Position = new Vector2(300, 100);
                btn2.Size = new Vector2(150, 50);
                btn2.TextureRegion = guiElements.Elements[0].Slices.ToArray();

                btn3.Text = "Button 3";
                btn3.OnClick += (m) =>
                {
                    var r = new Hatzap.Utilities.Random();
                    btn3.Color = new Vector4((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), 1);
                    //btn3.Z = btn4.Z + 1;
                };
                btn3.Anchor = new Anchor();
                btn3.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
                btn3.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
                btn3.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
                btn3.Position = new Vector2(100, 200);
                btn3.Size = new Vector2(150, 50);
                btn3.TextureRegion = guiElements.Elements[0].Slices.ToArray();

                btn4.Color = new Vector4(1, 1, 1, 0.5f);
                btn4.Text = "Button 4";
                btn4.OnClick += (m) =>
                {
                    //btn4.Text = "Clicked " + m.ToString();
                    //btn4.Z = btn3.Z + 1;
                };
                btn4.Anchor = new Anchor();
                btn4.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
                btn4.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
                btn4.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
                btn4.Position = new Vector2(150, 200);
                btn4.Size = new Vector2(150, 50);
                btn4.TextureRegion = guiElements.GetInfo(btn4).Slices.ToArray();
            }

            stack.Anchor = new Anchor();
            stack.Anchor.Directions[AnchorDirection.Left] = AnchorType.Snap;
            stack.Anchor.Directions[AnchorDirection.Top] = AnchorType.Snap;
            stack.Anchor.Directions[AnchorDirection.Right] = AnchorType.Snap;
            stack.Anchor.Directions[AnchorDirection.Bottom] = AnchorType.Snap;

            stack.RightAnchorOffset = 5;
            stack.LeftAnchorOffset = 5;
            stack.TopAnchorOffset = 5;
            #endregion

            var image = new Hatzap.Gui.Widgets.Image();
            var lblText = new Label();

            Window window = new Window();
            window.TextureRegion = guiElements.GetInfo(window).Slices.ToArray();
            window.Position = new Vector2(1200, 600);
            window.Size = new Vector2(300, 200);
            window.TitleHeight = 20;
            window.TitleColor = new Vector4(79f / 255f / 0.5f, 193f / 255f / 0.5f, 233f / 255f / 0.5f, 1f);
            window.Color = new Vector4(1f / (210f / 255f), 1f / (210f / 255f), 1f / (210f / 255f), 1f);

            leftPanel.AddChildWidget(stack);

            mainGuiGrid.AddChildWidget(menuBar);
            mainGuiGrid.AddChildWidget(leftPanel);
            mainGuiGrid.AddChildWidget(bottomBar);

            GuiRoot.Root.AddWidget(mainGuiGrid);

            UserInput.Keyboard.CaptureText = true;

            modelShader = ShaderManager.Get("Model");
            textShader = ShaderManager.Get("Text");

            //Create a new importer
            AssimpContext importer = new AssimpContext();

            //This is how we add a configuration (each config is its own class)
            //NormalSmoothingAngleConfig config = new NormalSmoothingAngleConfig(66.0f);
            //importer.SetConfig(config);

            var flags = PostProcessPreset.TargetRealTimeMaximumQuality | PostProcessSteps.Triangulate | PostProcessSteps.SortByPrimitiveType | PostProcessSteps.FlipUVs;

            //Import the model. All configs are set. The model
            //is imported, loaded into managed memory. Then the unmanaged memory is released, and everything is reset.
            Scene model = importer.ImportFile("Assets/Models/cube.fbx", flags);

            mesh = new Hatzap.Models.Mesh();

            Assimp.Mesh aMesh = null;

            foreach (var item in model.Meshes)
            {
                if (item.PrimitiveType != Assimp.PrimitiveType.Triangle)
                    continue;

                aMesh = item;
                break;
            }

            if (aMesh != null)
            {
                //mesh.AssimpMesh = aMesh;
            }
            else
            {
                Debug.WriteLine("ERROR: No triangle meshes found in imported model.");
            }

            //End of example
            importer.Dispose();

            TextureMeta shipTextureMeta = new TextureMeta()
            {
                FileName = "Assets/Textures/sh3.jpg,Assets/Textures/sh3_n.png,Assets/Textures/sh3_s.jpg",
                PixelInternalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt1Ext,
                PixelFormat = PixelFormat.Bgra,
                PixelType = PixelType.UnsignedByte,
                Width = 1024,
                Height = 1024,
                Quality = new TextureQuality()
                {
                    Filtering = TextureFiltering.Trilinear,
                    Anisotrophy = 32,
                    Mipmaps = true,
                    TextureWrapMode_S = OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat,
                    TextureWrapMode_T = OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat
                }
            };

            shipTexture = new TextureArray();
            shipTexture.Load(shipTextureMeta);

            font = FontManager.Get("OpenSans-Regular");

            fpsText = new GuiText();
            fpsText.Font = font;
            fpsText.FontSize = 8f;
            fpsText.Weight = 1.2f;
            fpsText.Smooth = 2.5f;
            fpsText.LineHeight = 50.0f;
            fpsText.Color = new Vector4(1, 1, 1, 1);
            fpsText.Text = "FPS: Calculating..";

            int n = 5;
            int sizeScale = 7;

            var rand = new Hatzap.Utilities.Random();

            for (int x = -n; x <= n; x++)
            {
                for (int y = -n; y <= n; y++)
                {
                    Hatzap.Models.Material spaceShipMaterial = new Hatzap.Models.Material();

                    bool transparent = rand.NextDouble() < 0.5;

                    float transparency = (float)rand.NextDouble();

                    transparency += 0.05f;

                    if (!(transparency < 1.0f))
                    {
                        transparency = 1.0f;
                        transparent = false;
                    }

                    spaceShipMaterial.Transparent = transparent;

                    spaceShipMaterial.UniformData = new List<IUniformData> {
                        new UniformDataVector4()
                        {
                            Name = "Color",
                            Data = new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), transparency)
                        }
                    };

                    for (int z = -n; z <= n; z++)
                    {
                        var spaceShip = new Model();
                        spaceShip.Texture = shipTexture;
                        //spaceShip.Shader = ShaderManager.Get("Textureless");
                        spaceShip.Shader = ShaderManager.Get("Model");
                        spaceShip.Mesh = mesh;
                        spaceShip.Transform.Static = true;
                        spaceShip.Transform.Position = new Vector3((x + (float)(rand.NextDouble() - 0.5)) * sizeScale, (y + (float)(rand.NextDouble() - 0.5)) * sizeScale, (z + (float)(rand.NextDouble() - 0.5)) * sizeScale);
                        spaceShip.Transform.Rotation = Quaternion.FromEulerAngles(x * 360.0f / n / (float)Math.PI, y * 360.0f / n / (float)Math.PI, z * 360.0f / n / (float)Math.PI);
                        spaceShip.Material = spaceShipMaterial;

                        SceneManager.Insert(spaceShip);
                    }
                }
            }

            Debug.WriteLine("OnLoad() ends");

            base.OnLoad(e);
        }
Exemplo n.º 35
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;
            }
        }
Exemplo n.º 36
0
        public void loadMeshFromFile(String filename)
        {
            //Filepath to our model
            String fileName = FileManager.getMediaFile(filename);

            //Create a new importer
            AssimpContext importer = new AssimpContext();

            ////This is how we add a logging callback
            //LogStream logstream = new LogStream(delegate (String msg, String userData)
            //{
            //    Console.WriteLine(msg);
            //});
            //logstream.Attach();

            //Import the model. The model is imported, loaded into managed memory.
            // Then the unmanaged memory is released, and everything is reset.
            Scene model = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality);

            // Load the model data into our own structures
            for (var i = 0; i < model.MeshCount; i++)
            {
                // Vertices
                for (var currentVertex = 0; currentVertex < model.Meshes[i].VertexCount; currentVertex++)
                {
                    Vector3D vector = model.Meshes[i].Vertices[currentVertex];
                    vertices.Add(new Vector3(vector.X, vector.Y, vector.Z));
                    colorData.Add(new Vector3(0.5f, 0.5f, 0.5f));
                }

                // Normals
                for (var currentNormal = 0; currentNormal < model.Meshes[i].Normals.Count; currentNormal++)
                {
                    Vector3D normal = model.Meshes[i].Normals[currentNormal];
                    normals.Add(new Vector3(normal.X, normal.Y, normal.Z));
                }

                // Material
                if (model.Materials[0].HasTextureDiffuse == true)
                {
                    isTextured = true;

                    textureCoordinates.Capacity = model.Meshes[0].TextureCoordinateChannels[0].Count;
                    foreach (Assimp.Vector3D element in model.Meshes[0].TextureCoordinateChannels[0])
                    {
                        textureCoordinates.Add(new Vector2(element.X, element.Y));
                    }

                    textureID = GL.GenTexture();
                    GL.BindTexture(TextureTarget.Texture2D, textureID);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

                    // Use anisotropic Filtering if available
                    var extensions = GL.GetString(StringName.Extensions).Split(' ');
                    if (extensions.Contains("GL_EXT_texture_filter_anisotropic"))
                    {
                        int max_aniso = GL.GetInteger((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt);
                        GL.TexParameter(TextureTarget.Texture2D, (TextureParameterName)ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, max_aniso);
                    }

                    Bitmap bmp = new Bitmap(FileManager.getMediaFile("textures/" + model.Materials[0].TextureDiffuse.FilePath));
                    BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);

                    bmp.UnlockBits(bmp_data);

                    // Generate MipMaps (especially to get rid of texture flickering)
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                }
                GL.BindTexture(TextureTarget.Texture2D, -1);

                // Indices
                indices.AddRange(model.Meshes[i].GetIndices());
            }

            //End of example
            importer.Dispose();

            // Generate the buffers
            generateBuffers();
        }
Exemplo n.º 37
0
        private void LoadMesh(CpuDescriptorHandle heapStart)
        {
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MinimumLod = float.MinValue,
                MaximumLod = float.MaxValue,
                MipLodBias = 0,
                MaximumAnisotropy = 0,
                ComparisonFunction = Comparison.Never

            };
            var heapPosition = heapStart;

            // Load model from obj.
            var importer = new Assimp.AssimpContext();
            var scene = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices);

            Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)];
            int[] indices = new int[scene.Meshes.Sum(m => m.FaceCount * 3)];
            faceCounts = new List<int>();

            int vertexOffSet = 0;
            int indexOffSet = 0;
            foreach (var mesh in scene.Meshes)
            {
                var positions = mesh.Vertices;
                var normals = mesh.Normals;
                var texs = mesh.TextureCoordinateChannels[0];
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    vertices[vertexOffSet + i] = new Vertex()
                    {
                        position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z),
                        normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z),
                        textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z)
                    };
                }

                var faces = mesh.Faces;
                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    indices[i * 3 + indexOffSet] = (int)faces[i].Indices[0] + vertexOffSet;
                    indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet;
                    indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet;
                }

                faceCounts.Add(mesh.FaceCount * 3);
                vertexOffSet += mesh.VertexCount;
                indexOffSet += mesh.FaceCount * 3;

                string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath);
                var texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName);
                textures.Add(texResource);

                int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768;
                ShaderResourceViewDescription desc = new ShaderResourceViewDescription
                {
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Format = texResource.Description.Format,
                    Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
                };
                desc.Texture2D.MipLevels = 1;
                desc.Texture2D.MostDetailedMip = 0;
                desc.Texture2D.ResourceMinLODClamp = 0;

                device.CreateShaderResourceView(texResource, desc, heapStart);
                heapStart += constantBufferDescriptorSize;
            }

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            int indexBufferSize = Utilities.SizeOf(indices);
            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;
        }
Exemplo n.º 38
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);
     }
 }
Exemplo n.º 39
0
        /// <summary>
        /// Initialize our basic model
        /// </summary>
        /// <param name="device">Direct3D device for use</param>
        /// <param name="texMgr">Texture manager from which to load texture data</param>
        /// <param name="filename">Filename of the ASSIMP resource we would like to load (see ASSIMP documentation for supported formats)</param>
        /// <param name="texturePath">Texture path - base path for textures used by the ASSIMP model</param>
        public BasicModel(Device device, TextureManager texMgr, string filename, string texturePath)
        {
            _subsets = new List<MeshGeometry.Subset>();
            _vertices = new List<BasicEffectVertex>();
            _indices = new List<ushort>();
            DiffuseMapSRV = new List<ShaderResourceView>();
            NormalMapSRV = new List<ShaderResourceView>();
            Materials = new List<Lighting.Material>();
            _modelMesh = new MeshGeometry();

            var importer = new AssimpContext();
            if (!importer.IsImportFormatSupported(Path.GetExtension(filename)))
            {
                throw new ArgumentException($"Model format {Path.GetExtension(filename)} is not supported! Cannot load {filename}", "Outside Engine");
            }
            var model = importer.ImportFile(filename, PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace);
            #if DEBUG
            var logStream = new ConsoleLogStream();
            logStream.Attach();
            #endif

            foreach (var mesh in model.Meshes)
            {
                //
                // Vertex processing
                //
                var verts = new List<BasicEffectVertex>();
                var subset = new MeshGeometry.Subset
                {
                    VertexCount = mesh.VertexCount,
                    VertexStart = _vertices.Count,
                    FaceStart = _indices.Count / 3,
                    FaceCount = mesh.FaceCount
                };
                _subsets.Add(subset);

                // TODO KAM: Process bounding box corners

                for (var i = 0; i < mesh.VertexCount; ++i)
                {
                    Vector3 pos = mesh.HasVertices ? mesh.Vertices[i].ToVector3() : new Vector3();

                    var norml = mesh.HasNormals ? mesh.Normals[i].ToVector3() : new Vector3();
                    var texC = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i].ToVector3() : new Vector3();
                    var tan = mesh.HasTangentBasis ? mesh.Tangents[i].ToVector3() : new Vector3();
                    var v = new BasicEffectVertex(pos, norml, new Vector2(texC.X, texC.Y));
                    verts.Add(v);
                }

                _vertices.AddRange(verts);

                var indices = mesh.GetIndices().Select(i => (ushort)(i + (uint)subset.VertexStart)).ToList();
                _indices.AddRange(indices);

                //
                // Material processing
                //
                var mat = model.Materials[mesh.MaterialIndex];
                var material = mat.ToMaterial();

                Materials.Add(material);
                TextureSlot diffuseSlot;
                mat.GetMaterialTexture(TextureType.Diffuse, 0, out diffuseSlot);
                var diffusePath = diffuseSlot.FilePath;
                if (Path.GetExtension(diffusePath) == ".tga")
                {
                    throw new InvalidDataException("Cannot use TGA files for textures with DirectX. Sorry about that.");
                }

                if (!string.IsNullOrEmpty(diffusePath))
                {
                    DiffuseMapSRV.Add(texMgr.GetTexture(Path.Combine(texturePath, diffusePath)));
                }

                TextureSlot normalSlot;
                mat.GetMaterialTexture(TextureType.Normals, 0, out normalSlot);
                var normalPath = normalSlot.FilePath;
                if (!string.IsNullOrEmpty(normalPath))
                {
                    NormalMapSRV.Add(texMgr.GetTexture(Path.Combine(texturePath, normalPath)));
                }
                else
                {
                    var normalExt = Path.GetExtension(diffusePath);
                    normalPath = Path.GetFileNameWithoutExtension(diffusePath) + "_nmap" + normalExt;
                    NormalMapSRV.Add(texMgr.GetTexture(Path.Combine(texturePath, normalPath)));
                }
            }

            _modelMesh.SetSubsetTable(_subsets);
            _modelMesh.SetVertices(device, _vertices);
            _modelMesh.SetIndices(device, _indices);
        }
Exemplo n.º 40
0
        public static List <MeshGroup> FromFbx(string filePath)
        {
            List <MeshGroup> group = new List <MeshGroup>();

            const float Scale        = 1.0f;
            var         assimp       = new Assimp.AssimpContext();
            var         scene        = assimp.ImportFile(filePath, Assimp.PostProcessSteps.PreTransformVertices);
            var         baseFilePath = Path.GetDirectoryName(filePath);

            TexList     = new List <string>();
            TextureData = new List <Tm2>();

            foreach (Assimp.Material mat in scene.Materials)
            {
                TexList.Add(Path.GetFileName(mat.TextureDiffuse.FilePath));
                Stream str = File.OpenRead(TexList[TexList.Count - 1]);

                PngImage png     = new PngImage(str);
                Tm2      tmImage = Tm2.Create(png);
                TextureData.Add(tmImage);
            }

            for (int i = 0; i < scene.RootNode.ChildCount; i++)
            {
                Node      child            = scene.RootNode.Children[i];
                MeshGroup currentMeshGroup = new MeshGroup();
                currentMeshGroup.MeshDescriptors = new List <MeshDescriptor>();

                // Get meshes by ID.
                foreach (int j in child.MeshIndices)
                {
                    MeshDescriptor meshDescriptor = new MeshDescriptor();
                    Mesh           x = scene.Meshes[j];

                    var vertices = new PositionColoredTextured[x.Vertices.Count];
                    for (var k = 0; k < vertices.Length; k++)
                    {
                        vertices[k].X  = x.Vertices[k].X * Scale;
                        vertices[k].Y  = x.Vertices[k].Y * Scale;
                        vertices[k].Z  = x.Vertices[k].Z * Scale;
                        vertices[k].Tu = x.TextureCoordinateChannels[0][k].X;
                        vertices[k].Tv = 1.0f - x.TextureCoordinateChannels[0][k].Y;
                        vertices[k].R  = x.VertexColorChannels[0][i].R;
                        vertices[k].G  = x.VertexColorChannels[0][i].G;
                        vertices[k].B  = x.VertexColorChannels[0][i].B;
                        vertices[k].A  = x.VertexColorChannels[0][i].A;
                    }

                    meshDescriptor.Vertices     = vertices;
                    meshDescriptor.Indices      = x.GetIndices();
                    meshDescriptor.IsOpaque     = false;
                    meshDescriptor.TextureIndex = x.MaterialIndex;


                    currentMeshGroup.MeshDescriptors.Add(meshDescriptor);
                }

                group.Add(currentMeshGroup);
            }

            return(group);
        }
Exemplo n.º 41
0
 public ModelLoader(Device device)
 {
     m_device = device;
     m_importer = new AssimpContext();
     m_importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
 }
Exemplo n.º 42
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);
        }
Exemplo n.º 43
0
        public override bool Execute(List<string> args)
        {
            if (args.Count < 1 || args.Count > 3)
                return false;

            ResourceLocation location = ResourceLocation.Resources;
            TagInstance destination = Info.Cache.Tags[0x3317];

            if (args.Count == 3)
            {
                var value = args[0];

                switch (value)
                {
                    case "resources":
                        location = ResourceLocation.Resources;
                        break;

                    case "textures":
                        location = ResourceLocation.Textures;
                        break;

                    case "textures_b":
                        location = ResourceLocation.TexturesB;
                        break;

                    case "audio":
                        location = ResourceLocation.Audio;
                        break;

                    case "video":
                        location = ResourceLocation.Video;
                        break;

                    case "render_models":
                        location = ResourceLocation.RenderModels;
                        break;

                    case "lightmaps":
                        location = ResourceLocation.Lightmaps;
                        break;

                    default:
                        Console.WriteLine("Invalid resource location: " + value);
                        return false;
                }

                args.RemoveAt(0);
            }

            if (args.Count == 2)
            {
                destination = ArgumentParser.ParseTagIndex(Info, args[0]);

                if (!destination.IsInGroup("mode"))
                {
                    Console.WriteLine("Specified tag is not a render_model: " + args[0]);
                    return false;
                }

                args.RemoveAt(0);
            }

            var builder = new RenderModelBuilder(Info.Version);

            // Add a root node
            var node = builder.AddNode(new RenderModel.Node
            {
                Name = Info.StringIDs.GetStringID("street_cone"),
                ParentNode = -1,
                FirstChildNode = -1,
                NextSiblingNode = -1,
                DefaultRotation = new Vector4(0, 0, 0, -1),
                DefaultScale = 1,
                InverseForward = new Vector3(1, 0, 0),
                InverseLeft = new Vector3(0, 1, 0),
                InverseUp = new Vector3(0, 0, 1),
            });

            // Begin building the default region and permutation
            builder.BeginRegion(Info.StringIDs.GetStringID("default"));
            builder.BeginPermutation(Info.StringIDs.GetStringID("default"));

            using (var importer = new AssimpContext())
            {
                Scene model;
                using (var logStream = new LogStream((msg, userData) => Console.WriteLine(msg)))
                {
                    logStream.Attach();
                    model = importer.ImportFile(args[0],
                        PostProcessSteps.CalculateTangentSpace |
                        PostProcessSteps.GenerateNormals |
                        PostProcessSteps.JoinIdenticalVertices |
                        PostProcessSteps.SortByPrimitiveType |
                        PostProcessSteps.PreTransformVertices |
                        PostProcessSteps.Triangulate);
                    logStream.Detach();
                }

                Console.WriteLine("Assembling vertices...");

                // Build a multipart mesh from the model data,
                // with each model mesh mapping to a part of one large mesh and having its own material
                builder.BeginMesh();
                ushort partStartVertex = 0;
                ushort partStartIndex = 0;
                var vertices = new List<RigidVertex>();
                var indices = new List<ushort>();
                foreach (var mesh in model.Meshes)
                {
                    for (var i = 0; i < mesh.VertexCount; i++)
                    {
                        var position = mesh.Vertices[i];
                        var normal = mesh.Normals[i];
                        var uv = mesh.TextureCoordinateChannels[0][i];
                        var tangent = mesh.Tangents[i];
                        var bitangent = mesh.BiTangents[i];
                        vertices.Add(new RigidVertex
                        {
                            Position = new Vector4(position.X, position.Y, position.Z, 1),
                            Normal = new Vector3(normal.X, normal.Y, normal.Z),
                            Texcoord = new Vector2(uv.X, uv.Y),
                            Tangent = new Vector4(tangent.X, tangent.Y, tangent.Z, 1),
                            Binormal = new Vector3(bitangent.X, bitangent.Y, bitangent.Z),
                        });
                    }

                    // Build the index buffer
                    var meshIndices = mesh.GetIndices();
                    indices.AddRange(meshIndices.Select(i => (ushort)(i + partStartVertex)));

                    // Define a material and part for this mesh
                    var material = builder.AddMaterial(new RenderMaterial
                    {
                        RenderMethod = Info.Cache.Tags[0x101F],
                    });

                    builder.BeginPart(material, partStartIndex, (ushort)meshIndices.Length, (ushort)mesh.VertexCount);
                    builder.DefineSubPart(partStartIndex, (ushort)meshIndices.Length, (ushort)mesh.VertexCount);
                    builder.EndPart();

                    // Move to the next part
                    partStartVertex += (ushort)mesh.VertexCount;
                    partStartIndex += (ushort)meshIndices.Length;
                }

                // Bind the vertex and index buffers
                builder.BindRigidVertexBuffer(vertices, node);
                builder.BindIndexBuffer(indices, PrimitiveType.TriangleList);
                builder.EndMesh();
            }

            builder.EndPermutation();
            builder.EndRegion();

            Console.WriteLine("Building Blam mesh data...");

            var resourceStream = new MemoryStream();
            var renderModel = builder.Build(Info.Serializer, resourceStream);

            Console.WriteLine("Writing resource data...");

            // Add a new resource for the model data
            var resources = new ResourceDataManager();
            resources.LoadCachesFromDirectory(Info.CacheFile.DirectoryName);
            resourceStream.Position = 0;
            resources.Add(renderModel.Geometry.Resource, location, resourceStream);

            Console.WriteLine("Writing tag data...");

            using (var cacheStream = Info.OpenCacheReadWrite())
            {
                var tag = destination;
                var context = new TagSerializationContext(cacheStream, Info.Cache, Info.StringIDs, tag);
                Info.Serializer.Serialize(context, renderModel);
            }

            Console.WriteLine("Model imported successfully!");

            return true;
        }
Exemplo n.º 44
0
        private void DoExport(Scene scene, string id) 
        {          
            var overwriteWithoutConfirmation = checkBoxNoOverwriteConfirm.Checked;

            var path = textBoxPath.Text.Trim();
            path = (path.Length > 0 ? path : scene.BaseDir);
            var name = textBoxFileName.Text.Trim();
            var fullPath = Path.Combine(path, name);
            if (!overwriteWithoutConfirmation && Path.GetFullPath(fullPath) == Path.GetFullPath(scene.File))
            {
                if (MessageBox.Show("This will overwrite the current scene's source file. Continue?", "Warning", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    PushLog("Canceled");
                    return;
                }
            }

            var copyTextures = checkBoxCopyTexturesToSubfolder.Checked;
            var relativeTexturePaths = checkBoxUseRelativeTexturePaths.Checked;
            var includeAnimations = checkBoxIncludeAnimations.Checked;
            var includeSceneHierarchy = checkBoxIncludeSceneHierarchy.Checked;

            var textureCopyJobs = new Dictionary<string, string>();
            var textureDestinationFolder = textBoxCopyTexturesToFolder.Text;

            PushLog("*** Export: " + scene.File);

            if(copyTextures)
            {
                try
                {
                    Directory.CreateDirectory(Path.Combine(path, textureDestinationFolder));
                }
                catch (Exception)
                {
                    PushLog("Failed to create texture destination directory " + Path.Combine(path, textureDestinationFolder));
                    return;
                }
            }

            progressBarExport.Style = ProgressBarStyle.Marquee;
            progressBarExport.MarqueeAnimationSpeed = 5;

            // Create a shallow copy of the original scene that replaces all the texture paths with their
            // corresponding output paths, and omits animations if requested.
            var sourceScene = new Assimp.Scene
                              {
                                  Textures = scene.Raw.Textures,
                                  SceneFlags = scene.Raw.SceneFlags,
                                  RootNode = scene.Raw.RootNode,
                                  Meshes = scene.Raw.Meshes,
                                  Lights = scene.Raw.Lights,
                                  Cameras = scene.Raw.Cameras
                              };

            if (includeAnimations)
            {
                sourceScene.Animations = scene.Raw.Animations;
            }

            var uniques = new HashSet<string>();
            var textureMapping = new Dictionary<string, string>();

            PushLog("Locating all textures");
            foreach (var texId in scene.TextureSet.GetTextureIds())
            {
                // TODO(acgessler): Verify if this handles texture replacements and GUID-IDs correctly.
                var destName = texId;

                // Broadly skip over embedded (in-memory) textures
                if (destName.StartsWith("*"))
                {
                    PushLog("Ignoring embedded texture: " + destName);
                    continue;
                }

                // Locate the texture on-disk
                string diskLocation;
                try
                {
                    TextureLoader.ObtainStream(texId, scene.BaseDir, out diskLocation).Close();
                } catch(IOException)
                {
                    PushLog("Failed to locate texture " + texId);
                    continue;
                }
             
                if (copyTextures)
                {
                    destName = GeUniqueTextureExportPath(path, textureDestinationFolder, diskLocation, uniques);
                }

                if (relativeTexturePaths)
                {
                    textureMapping[texId] = GetRelativePath(path + "\\", destName);
                }
                else
                {
                    textureMapping[texId] = destName;
                }
                textureCopyJobs[diskLocation] = destName;

                PushLog("Texture " + texId + " maps to " + textureMapping[texId]);              
            }

            foreach (var mat in scene.Raw.Materials)
            {
                sourceScene.Materials.Add(CloneMaterial(mat, textureMapping));
            }

            var t = new Thread(() =>
            {
                using (var v = new AssimpContext())
                {
                    PushLog("Exporting using Assimp to " + fullPath + ", using format id: " + id);
                    var result = v.ExportFile(sourceScene, fullPath, id, includeSceneHierarchy 
                        ? PostProcessSteps.None 
                        : PostProcessSteps.PreTransformVertices);
                    _main.BeginInvoke(new MethodInvoker(() =>
                    {
                        progressBarExport.Style = ProgressBarStyle.Continuous;
                        progressBarExport.MarqueeAnimationSpeed = 0;

                        if (!result)
                        {
                            // TODO: get native error message
                            PushLog("Export failure");
                            MessageBox.Show("Failed to export to " + fullPath, "Export error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            if (copyTextures)
                            {
                                PushLog("Copying textures");
                                foreach (var kv in textureCopyJobs)
                                {
                                    PushLog(" ... " + kv.Key + " -> " + kv.Value);
                                    try
                                    {
                                        File.Copy(kv.Key, kv.Value, false);
                                    }                               
                                    catch (IOException)
                                    {
                                        if (!File.Exists(kv.Value))
                                        {
                                            throw;
                                        }
                                        if (!overwriteWithoutConfirmation && MessageBox.Show("Texture " + kv.Value +
                                                " already exists. Overwrite?", "Overwrite Warning",
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                                        {
                                            PushLog("Exists already, skipping");
                                            continue;
                                        }
                                        PushLog("Exists already, overwriting");
                                        File.Copy(kv.Key, kv.Value, true);
                                    }
                                    catch (Exception ex)
                                    {
                                        PushLog(ex.Message);
                                    }
                                }
                            }
                            if (checkBoxOpenExportedFile.Checked)
                            {
                                _main.AddTab(fullPath, true, false);
                            }
                            PushLog("Export completed");
                        }
                    }));
                }
            });

            t.Start();
        }
Exemplo n.º 45
0
 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();
 }
Exemplo n.º 46
0
        public RendererContext(MessageProvider messageProvider) : base(messageProvider)
        {
            m_AssimpContext = new AssimpContext();

            PrivateCompositor = null;
        }
Exemplo n.º 47
0
        private void LoadMesh(CpuDescriptorHandle heapStart)
        {
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.ComparisonMinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MinimumLod         = float.MinValue,
                MaximumLod         = float.MaxValue,
                MipLodBias         = 0,
                MaximumAnisotropy  = 0,
                ComparisonFunction = Comparison.Never
            };
            var heapPosition = heapStart;

            // Load model from obj.
            var importer = new Assimp.AssimpContext();
            var scene    = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices);


            Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)];
            int[]    indices  = new int[scene.Meshes.Sum(m => m.FaceCount * 3)];
            faceCounts = new List <int>();

            int vertexOffSet = 0;
            int indexOffSet  = 0;

            foreach (var mesh in scene.Meshes)
            {
                var positions = mesh.Vertices;
                var normals   = mesh.Normals;
                var texs      = mesh.TextureCoordinateChannels[0];
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    vertices[vertexOffSet + i] = new Vertex()
                    {
                        position          = new Vector3(positions[i].X, positions[i].Y, positions[i].Z),
                        normal            = new Vector3(normals[i].X, normals[i].Y, normals[i].Z),
                        textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z)
                    };
                }

                var faces = mesh.Faces;
                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    indices[i * 3 + indexOffSet]     = (int)faces[i].Indices[0] + vertexOffSet;
                    indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet;
                    indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet;
                }

                faceCounts.Add(mesh.FaceCount * 3);
                vertexOffSet += mesh.VertexCount;
                indexOffSet  += mesh.FaceCount * 3;

                string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath);
                var    texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName);
                textures.Add(texResource);

                int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768;
                ShaderResourceViewDescription desc           = new ShaderResourceViewDescription
                {
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Format    = texResource.Description.Format,
                    Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
                };
                desc.Texture2D.MipLevels           = 1;
                desc.Texture2D.MostDetailedMip     = 0;
                desc.Texture2D.ResourceMinLODClamp = 0;

                device.CreateShaderResourceView(texResource, desc, heapStart);
                heapStart += constantBufferDescriptorSize;
            }

            int vertexBufferSize = Utilities.SizeOf(vertices);


            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);

            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes  = Utilities.SizeOf <Vertex>();
            vertexBufferView.SizeInBytes    = vertexBufferSize;


            //Create Index Buffer
            int indexBufferSize = Utilities.SizeOf(indices);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);

            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format         = Format.R32_UInt;
            indexBufferView.SizeInBytes    = indexBufferSize;
        }
Exemplo n.º 48
0
        private void Export(object parameter)
        {
            FileExtension = FileExtension.ToString();
            string exportedFile = FilePath + "\\" + FileName + '.' + FileExtension;

            if (FileExtension == "")
            {
                System.Windows.MessageBox.Show("Select a file extension");
                return;
            }
            if (FileName == "")
            {
                System.Windows.MessageBox.Show("Choose a name for your file");
                return;
            }
            if (!Directory.Exists(FilePath))
            {
                System.Windows.MessageBox.Show("Path is invalid");
                return;
            }
            if (File.Exists(exportedFile))
            {
                System.Windows.MessageBox.Show("File already exists at " + FilePath);
                return;
            }
            else
            {
                bool result = false;

                if (Session.CurrentSession.HasCurrentProject() && Session.CurrentSession.CurrentProject.CurrentModel3D != null)
                    scene = Session.CurrentSession.CurrentProject.CurrentModel3D.GetScene();
                
                if (Scene == null)
                {
                    System.Windows.MessageBox.Show("You must open a scene in order to export it");
                    return;
                }

                using (AssimpContext exporter = new AssimpContext())
                {
                    ExportFormatDescription[] exportFormat = exporter.GetSupportedExportFormats();

                    foreach (ExportFormatDescription format in exportFormat)
                    {
                        if (format.FileExtension == FileExtension)
                        {
                            result = exporter.ExportFile(scene, exportedFile, format.FormatId);
                            break;
                        }
                    }
                    if (result == false)
                    {
                        System.Windows.MessageBox.Show("Bad export file extension");
                        return;
                    }
                }
                    
                if (result == false)
                {
                    System.Windows.MessageBox.Show("Export failed");
                    return;
                }
                Window currentWindow = parameter as Window;
                McWindow.CloseWindow(currentWindow);
            }
        }
Exemplo n.º 49
0
 private AssimpContext GetImporter()
 {
     AssimpContext importer = new AssimpContext();
     importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
     return importer;
 }
Exemplo n.º 50
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>
        /// <param name="options">Additional options for the import.</param>
        /// <returns>
        /// The loaded <see cref="IModel"/>.
        /// </returns>
        public IModel Load(string filename, string name, Dictionary<string, string> additionalAnimationFiles, string[] options)
        {
            this.LoadAssimpLibrary();

            // Import the scene via AssImp.
            var importer = new AssimpContext();
            PostProcessSteps ProcessFlags = 0;
            if (options == null)
            {
                ProcessFlags |= PostProcessSteps.FlipUVs | PostProcessSteps.Triangulate |
                                PostProcessSteps.FlipWindingOrder;
            }
            else
            {
                foreach (var v in options)
                {
                    PostProcessSteps flag;
                    if (Enum.TryParse(v, true, out flag))
                    {
                        ProcessFlags |= flag;
                        Console.Write("(on: " + flag + ") ");
                    }
                }
            }
            
            var scene = importer.ImportFile(filename, ProcessFlags);

            ModelVertex[] vertexes;
            int[] indices;
            IModelBone boneHierarchy;
            Material material = null;

            if (scene.MeshCount >= 1)
            {
                var boneWeightingMap = this.BuildBoneWeightingMap(scene);
                var staticTransformMap = this.BuildStaticTransformMap(scene);
                
                if (options?.Contains("!NoBoneHierarchy") ?? false)
                {
                    boneHierarchy = null;
                }
                else
                {
                    boneHierarchy = this.ImportBoneHierarchy(scene.RootNode, scene.Meshes[0]);
                }

                vertexes = this.ImportVertexes(scene, boneWeightingMap, staticTransformMap);
                indices = this.ImportIndices(scene);
            }
            else
            {
                boneHierarchy = this.ImportBoneHierarchy(scene.RootNode, null);
                vertexes = new ModelVertex[0];
                indices = new int[0];
            }
            
            // If the scene has materials associated with it, and the mesh has
            // a material associated with it, read in the material information.
            if (scene.MeshCount >= 1 && scene.MaterialCount > scene.Meshes[0].MaterialIndex)
            {
                var assimpMaterial = scene.Materials[scene.Meshes[0].MaterialIndex];

                material = ConvertMaterial(assimpMaterial);
            }

            // 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(
                _modelRenderConfigurations,
                _renderBatcher,
                name,
                new AnimationCollection(animations),
                material,
                boneHierarchy, 
                vertexes,
                indices);
        }
Exemplo n.º 51
-1
        public static ModelMesh[] LoadFromFile(GameMode gameMode, string filePath)
        {
            if (".pmesh".Equals(Path.GetExtension(filePath), StringComparison.OrdinalIgnoreCase))
            {
                return new[] { LoadPMesh(gameMode, filePath) };
            }
            else
            {
                var modelDirectory = Path.GetDirectoryName(filePath);

                var context = new AssimpContext();
                const PostProcessSteps flags = PostProcessSteps.GenerateNormals | PostProcessSteps.GenerateUVCoords
                                               | PostProcessSteps.FlipWindingOrder
                                               | PostProcessSteps.FlipUVs;
                var scene = context.ImportFile(filePath, flags);

                var meshs = new List<ModelMesh>();
                foreach (var assimpMesh in scene.Meshes)
                {
                    var modelMesh = new ModelMesh(gameMode, scene, assimpMesh, modelDirectory);
                    meshs.Add(modelMesh);
                }

                return meshs.ToArray();
            } 
        }