public ColladaGeometry(string file)
        {
            var collada = Grendgine_Collada.Grendgine_Load_File(file);

            foreach (var geometry in collada.Library_Geometries.Geometry)
            {
                var mesh     = geometry.Mesh;
                var sources  = mesh.Source;
                var vertices = mesh.Vertices;
                foreach (var input in vertices.Input)
                {
                    switch (input.Semantic)
                    {
                    }
                }

                foreach (var polygon in geometry.Mesh.Polygons)
                {
                    // input points to sources either directly
                    // or through sources defined in vertices
                    // (vertex semantics)
                    foreach (var input in polygon.Input)
                    {
                    }
                    foreach (int index in polygon.P.Value())
                    {
                    }
                }
            }
        }
Example #2
0
        private Grendgine_Collada_Node GetSkeletonFromVisualScene(Grendgine_Collada scene)
        {
            // We need to get the hierarchy of the bone structure.
            // DAE stores it in the visual scene, but sometimes it's hidden under layers of
            // other nodes. To get around that, we're going to check every node in the visual scene
            // for if A) it's a "JOINT" node and B) it has children, ie the node property isn't null.
            // The check will be recursive, working on every node in the hierarchy until we find what
            // *should* be the skeleton's root.

            Grendgine_Collada_Node root = null;

            foreach (Grendgine_Collada_Visual_Scene visScene in scene.Library_Visual_Scene.Visual_Scene)
            {
                foreach (Grendgine_Collada_Node node in visScene.Node)
                {
                    root = GetSkeletonFromNodeRecursive(node);

                    if (root != null)
                    {
                        break;
                    }
                }
            }

            return(root);
        }
Example #3
0
 public BMDManager(Grendgine_Collada scene)
 {
     Skeleton = new SkinningManager(scene);
     Geometry = new GeometryManager(scene, Skeleton.Drw1Data, Skeleton.SkelData.BindShapeMatrix);
     Geometry.VertexData.TransformPositions(Skeleton.Drw1Data, Skeleton.SkelData.FlatHierarchy);
     Skeleton.SkelData.AssignBoneBoundingBoxes(Geometry.VertexData.Positions, Skeleton.Drw1Data);
     Materials = new MaterialManager(scene, Geometry.BatchData.Batches);
 }
        public SkinningManager(Grendgine_Collada scene)
        {
            Grendgine_Collada_Skin skinning = GetSkinningInfo(scene);

            SkelData = new SkeletonData(scene, skinning);

            if (skinning != null)
            {
                Drw1Data = new DrawData(skinning, SkelData.FlatHierarchy, SkelData.BonesWithGeometry);
            }
        }
Example #5
0
        private Grendgine_Collada_Skin GetSkinningInfo(Grendgine_Collada scene)
        {
            Grendgine_Collada_Skin skinning = null;

            foreach (Grendgine_Collada_Controller con in scene.Library_Controllers.Controller)
            {
                if (con.Skin != null)
                {
                    skinning = con.Skin;
                }
            }

            return(skinning);
        }
Example #6
0
        static void Main(string[] args)
        {
            string inputFileName  = "";
            string outputFileName = "";

            #region Get input/output filenames

            // The user supplied at least an input file
            if (args.Length != 0)
            {
                // Just an input file
                if (args.Length == 1)
                {
                    inputFileName = args[0];
                }
                // Input file and a file name to output to
                else if (args.Length == 2)
                {
                    inputFileName  = args[0];
                    outputFileName = args[1];
                }
            }
            // User didn't give any files to convert, display help instead
            else
            {
                DisplayHelpMessage();
                return;
            }

            // Output file name wasn't set. So we'll just make it the input file name and replace its extension with .bmd
            if (outputFileName == "")
            {
                outputFileName = string.Format("{0}\\{1}.bmd", Path.GetDirectoryName(inputFileName),
                                               Path.GetFileNameWithoutExtension(inputFileName));
            }

            #endregion

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            Grendgine_Collada sourceModel = Grendgine_Collada.Grendgine_Load_File(inputFileName);
            BMDManager        manager     = new BMDManager(sourceModel);

            using (FileStream stream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write))
            {
                EndianBinaryWriter writer = new EndianBinaryWriter(stream, Endian.Big);
                manager.WriteBMD(writer);
            }
        }
Example #7
0
        /// <summary>
        /// Creates an instance of GeometryManager and loads the geometry data from it.
        /// </summary>
        /// <param name="scene">Source of geometry data</param>
        /// <param name="position">Datatype to use for position data</param>
        /// <param name="normal">Datatype to use for normal data</param>
        /// <param name="uv">Datatype to use for UV data</param>
        /// <param name="color">Datatype to use for color data</param>
        public GeometryManager(Grendgine_Collada scene, DrawData drw1, Matrix4 bindShape, DataTypes position = DataTypes.F32, DataTypes normal = DataTypes.F32,
                               DataTypes uv = DataTypes.F32, ColorDataTypes color = ColorDataTypes.RGBA8)
        {
            if (scene.Library_Geometries == null)
            {
                throw new FormatException("Mesh has no geometry!");
            }

            foreach (Grendgine_Collada_Geometry geom in scene.Library_Geometries.Geometry)
            {
                VertexData = new VertexData(geom.Mesh, bindShape, position, normal, uv, color);
                BatchData  = new BatchData(geom.Mesh, drw1);
                BatchData.SetBoundingBoxes(VertexData.Positions);
            }
        }
Example #8
0
        // Keeping this for posterity until Load(string fileName) is proven to work
        public DAE(string fileName)
        {
            categoryCollection = new ObservableCollection <Category>();

            Grendgine_Collada file = Grendgine_Collada.Grendgine_Load_File(fileName);

            for (int i = 0; i < file.Library_Geometries.Geometry.Length; i++)
            {
                Category cat = new Category();

                cat.Name = file.Library_Geometries.Geometry[i].Name + "_parent";

                List <Vector3> verts = GetVerts(file.Library_Geometries.Geometry[i]);

                int skipValue = CalcSkipValue(file.Library_Geometries.Geometry[i]);

                Group grp = new Group();

                grp.Name = file.Library_Geometries.Geometry[i].Name;

                int[] pList = file.Library_Geometries.Geometry[i].Mesh.Polylist[0].P.Value();

                List <int> vertIndexes = GetVertIndexes(pList, skipValue);

                for (int j = 0; j < vertIndexes.Count; j += 3)
                {
                    Triangle face = new Triangle();

                    face.Vertex1 = verts[vertIndexes[j]];

                    face.Vertex2 = verts[vertIndexes[j + 1]];

                    face.Vertex3 = verts[vertIndexes[j + 2]];

                    face.ParentGroup = grp;

                    grp.Triangles.Add(face);
                }

                grp.CreateBufferObjects();

                grp.GroupCategory = cat;

                cat.Groups.Add(grp);

                categoryCollection.Add(cat);
            }
        }
Example #9
0
        public MaterialManager(Grendgine_Collada scene, List <Batch> batches, string modelPath)
        {
            #region List initialization
            m_indirectTexBlock    = new List <IndirectTexturing>();
            m_cullModeBlock       = new List <GXCullMode>();
            m_materialColorBlock  = new List <Color?>();
            m_channelControlBlock = new List <ChannelControl>();
            m_ambientColorBlock   = new List <Color?>();
            m_lightingColorBlock  = new List <Color?>();
            m_texCoord1GenBlock   = new List <TexCoordGen>();
            m_texCoord2GenBlock   = new List <TexCoordGen>();
            m_texMatrix1Block     = new List <TexMatrix>();
            m_texMatrix2Block     = new List <TexMatrix>();
            TextureList           = new List <BinaryTextureImage>();
            m_tevOrderBlock       = new List <TevOrder>();
            m_tevColorBlock       = new List <Color?>();
            m_tevKonstColorBlock  = new List <Color?>();
            m_tevStageBlock       = new List <TevStage>();
            m_swapModeBlock       = new List <TevSwapMode>();
            m_swapTableBlock      = new List <TevSwapModeTable>();
            m_fogBlock            = new List <Fog>();
            m_alphaCompBlock      = new List <AlphaCompare>();
            m_blendModeBlock      = new List <BlendMode>();
            m_zModeBlock          = new List <ZMode>();
            m_zCompLocBlock       = new List <bool>();
            m_ditherBlock         = new List <bool>();
            NumColorChannelsBlock = new List <byte>();
            NumTexGensBlock       = new List <byte>();
            NumTevSTagesBlock     = new List <byte>();

            Materials = new List <Material>();
            #endregion

            Grendgine_Collada_Material[] GrendgineMaterials = scene.Library_Materials.Material;
            Grendgine_Collada_Effect[]   Effects            = scene.Library_Effects.Effect;
            Grendgine_Collada_Image[]    Images             = scene.Library_Images.Image;

            foreach (Batch bat in batches)
            {
                Grendgine_Collada_Material batMat    = GrendgineMaterials.First(x => x.Name == bat.MaterialName || x.ID == bat.MaterialName);
                Grendgine_Collada_Effect   batEffect = Effects.First(x => x.ID == batMat.Instance_Effect.URL.Remove(0, 1));
                Grendgine_Collada_Phong    phong     = batEffect.Profile_COMMON[0].Technique.Phong;

                Material mat = new Material(phong, bat, modelPath, Images);
                Materials.Add(mat);
            }
        }
Example #10
0
        public MeshData Load(string filename)
        {
            if (!IsFileValid(filename))
            {
                return(new MeshData());
            }

            meshData         = Grendgine_Collada.Grendgine_Load_File(filename).Library_Geometries.Geometry[0].Mesh;
            indicesPerVertex = CalcIndexesPerVertex();
            numOfVertices    = CalcNumberOfVerticesInMesh();

            BuildIndicesArray();
            BuildVertexArray();

            SwitchUpAxisFromZtoY();

            return(new MeshData(vertices, indices));
        }
Example #11
0
        public static void ColladaTest()
        {
            string fileName = @"A:\Archiv\3D\_Jeannie\Models\2017.01.28\MilaPartyBlack_blender.dae";


            Grendgine_Collada.ReduceMesh(fileName, 0.1f);

            Grendgine_Collada col  = Grendgine_Collada.Load_File(fileName);
            string            path = OpenTKExtension.IOUtils.ExtractDirectory(fileName);


            Grendgine_Collada.Save(path + "new.dae", col);



            //OpenTKExtension.Collada.ColladaPointCloud cm = OpenTKExtension.Collada.ColladaLoader.LoadFile(path);
            TestForm tf = new TestForm();

            //tf.ShowPointClouds(cm.PointClouds);
            Application.Run((Form)tf);
        }
Example #12
0
        public SkeletonData(Grendgine_Collada scene, Grendgine_Collada_Skin skin)
        {
            FlatHierarchy     = new List <Bone>();
            BonesWithGeometry = new List <Bone>();

            boneNameList        = new List <string>();
            inverseBindMatrices = new List <Matrix4>();

            // Get the skeleton's root from the visual scene
            Grendgine_Collada_Node rootNode = GetSkeletonFromVisualScene(scene);

            // If a proper root was found, we create a new bone hierarchy from it
            if (rootNode != null)
            {
                SkeletonRoot = new Bone(rootNode);
                MakeDAESkeleton(skin);
            }
            // Otherwise, we create a root bone ourselves
            else
            {
                SkeletonRoot = new Bone();
                FlatHierarchy.Add(SkeletonRoot);
            }
        }
Example #13
0
        public static void load(string filename, MaterialManager material_manager, out Dictionary <string, UniqueMesh> unique_mesh_collection, out Dictionary <string, LightLoader.LightLoaderExtras> light_extras)
        {
            if (!File.Exists(filename))
            {
                throw new Exception("World File Not Found\n" + filename);
            }


            Debug.DebugHelper.logInfo(1, "Loading Collada File", Path.GetFileName(filename));
            Grendgine_Collada dae_file = Grendgine_Collada.Grendgine_Load_File(filename);


            //------------------------------------------------------
            // Create Image Dictionary
            //------------------------------------------------------
            Dictionary <string, string> image_collection = new Dictionary <string, string>();

            try
            {
                if (dae_file.Library_Images.Image != null)
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Image Dictionary", dae_file.Library_Images.Image.Count() + " images found");
                    foreach (Grendgine_Collada_Image i in dae_file.Library_Images.Image)
                    {
                        string id   = i.ID;
                        string path = i.Init_From;
                        path = path.Substring(1, path.Length - 1);
                        path = EngineHelper.getPath_MaterialTextures(path);

                        image_collection.Add(id, path);
                    }
                }
                else
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Image Dictionary", "0 images found :<");
                }
            }
            catch (Exception e)
            {
                Debug.DebugHelper.logError("\tCreating Image Dictionary", e.Message);
            }


            //------------------------------------------------------
            // Create Material Dictionary
            //------------------------------------------------------
            Dictionary <string, DAE_Material> material_collection = new Dictionary <string, DAE_Material>();

            try
            {
                if (dae_file.Library_Effects != null)
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Material Dictionary", dae_file.Library_Effects.Effect.Count() + " effects found");
                    foreach (Grendgine_Collada_Effect e in dae_file.Library_Effects.Effect)
                    {
                        string id = e.ID;

                        DAE_Material temp_material = new DAE_Material(id);
                        temp_material.load(e, image_collection, material_manager);

                        material_collection.Add(temp_material.id, temp_material);
                    }
                }
                else
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Material Dictionary", "0 effects found :<");
                }
            }
            catch (Exception e)
            {
                Debug.DebugHelper.logError("\tCreating Material Dictionary", e.Message);
            }


            //------------------------------------------------------
            // Create Animation Dictionary
            //------------------------------------------------------
            Dictionary <string, ObjectAnimator>   object_animator_collection   = new Dictionary <string, ObjectAnimator>();
            Dictionary <string, SkeletonAnimator> skeleton_animator_collection = new Dictionary <string, SkeletonAnimator>();

            try
            {
                if (dae_file.Library_Animations != null)
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Animation Dictionary", dae_file.Library_Animations.Animation.Count() + " animations found");
                    foreach (Grendgine_Collada_Animation a in dae_file.Library_Animations.Animation)
                    {
                        //------------------------------------------------------
                        // Get match strings to decide what kind of Animation this is
                        //------------------------------------------------------
                        // Get the ID of the object or bone we are animating
                        Match  object_match = Regex.Match(a.Channel[0].Target, "(.+)/.+");
                        string object_id    = object_match.Groups[1].ToString();

                        // Match if this is an object animation
                        Match object_animation_match = Regex.Match(a.ID, object_id + "_(location|rotation_euler|scale)_(X|Y|Z)");

                        // Match if this is a skeletal animation
                        Match skeleton_animation_match = Regex.Match(a.ID, "(.+)_" + object_id + "_pose_matrix");


                        //------------------------------------------------------
                        // Create Source and Sampler Dictionaries
                        //------------------------------------------------------
                        // Create source dictionary
                        Dictionary <string, Grendgine_Collada_Source> source_dictionary = a.Source.ToDictionary(s => s.ID, s => s);

                        // Create sampler dictionary
                        Dictionary <string, string> sampler_dictionary = a.Sampler[0].Input.ToDictionary(i => i.Semantic.ToString(), i => i.source);


                        //------------------------------------------------------
                        // Get Common Animation Data
                        //------------------------------------------------------
                        // Get Key interpolation method
                        string   source_interpolation_id  = sampler_dictionary["INTERPOLATION"].Replace("#", "");
                        string[] key_frame_interpolations = source_dictionary[source_interpolation_id].Name_Array.Value();

                        // Get Key Frame times
                        string  source_input_id = sampler_dictionary["INPUT"].Replace("#", "");
                        float[] key_frame_times = source_dictionary[source_input_id].Float_Array.Value();

                        // Get Key Frame data
                        string  source_output_id      = sampler_dictionary["OUTPUT"].Replace("#", "");
                        float[] key_frame_data        = source_dictionary[source_output_id].Float_Array.Value();
                        int     key_frame_data_stride = (int)source_dictionary[source_output_id].Technique_Common.Accessor.Stride;


                        //------------------------------------------------------
                        // Object Animation
                        //------------------------------------------------------
                        if (object_animation_match.Success && !skeleton_animation_match.Success)
                        {
                            string id      = object_id;
                            string action  = object_animation_match.Groups[1].ToString();
                            string channel = object_animation_match.Groups[2].ToString();

                            switch (action)
                            {
                            case "location":
                                action = AnimationHelper.translate;
                                break;

                            case "rotation_euler":
                                action = AnimationHelper.rotation_euler;
                                break;

                            case "scale":
                                action = AnimationHelper.scale;
                                break;
                            }

                            // Create new or use existing Animator
                            ObjectAnimator temp_animator;
                            if (object_animator_collection.TryGetValue(id, out temp_animator))
                            {
                                object_animator_collection.Remove(id);
                            }
                            else
                            {
                                temp_animator = new ObjectAnimator(id);
                            }


                            // Get Key Frame in tangent data
                            string  source_t1_id      = sampler_dictionary["IN_TANGENT"].Replace("#", "");
                            float[] key_frame_data_b1 = source_dictionary[source_t1_id].Float_Array.Value();

                            // Get Key Frame out tangent data
                            string  source_t2_id      = sampler_dictionary["OUT_TANGENT"].Replace("#", "");
                            float[] key_frame_data_b2 = source_dictionary[source_t2_id].Float_Array.Value();


                            // Loop through key frames and add to animator
                            for (int i = 0; i < key_frame_times.Length; i++)
                            {
                                float   current_frame_time = key_frame_times[i];
                                float   current_frame_data = key_frame_data[i];
                                int     j = i * 2;
                                Vector4 current_frame_data_bezier = new Vector4(
                                    key_frame_data_b1[j],
                                    key_frame_data_b1[j + 1],
                                    key_frame_data_b2[j],
                                    key_frame_data_b2[j + 1]
                                    );

                                temp_animator.addKeyFrame(current_frame_time, action, channel, current_frame_data, current_frame_data_bezier);
                            }

                            object_animator_collection.Add(id, temp_animator);
                        }


                        //------------------------------------------------------
                        // Skeletal Animation
                        //------------------------------------------------------
                        if (skeleton_animation_match.Success && !object_animation_match.Success)
                        {
                            string id        = skeleton_animation_match.Groups[1].ToString();
                            string bone_name = object_id;



                            // Create new or use existing Animator
                            SkeletonAnimator temp_animator;
                            if (skeleton_animator_collection.TryGetValue(id, out temp_animator))
                            {
                                skeleton_animator_collection.Remove(id);
                            }
                            else
                            {
                                temp_animator = new SkeletonAnimator(id);
                            }

                            // Loop through key frames and add to animator
                            for (int i = 0; i < key_frame_times.Length; i++)
                            {
                                int current_frame_data_index = i * key_frame_data_stride;

                                float   current_frame_time = key_frame_times[i];
                                float[] current_frame_data = new float[16];

                                // Create Matrix from each 16 strided float
                                Array.Copy(key_frame_data, current_frame_data_index, current_frame_data, 0, key_frame_data_stride);
                                Matrix4 current_frame_data_matrix = EngineHelper.createMatrix(current_frame_data);

                                temp_animator.addKeyFrame(bone_name, current_frame_time, current_frame_data_matrix);
                            }

                            skeleton_animator_collection.Add(id, temp_animator);
                        }

                        source_dictionary.Clear();
                        sampler_dictionary.Clear();
                    }


                    // Get last key frame for each animator
                    foreach (ObjectAnimator a in object_animator_collection.Values)
                    {
                        a.calcLastFrame();
                    }
                    foreach (SkeletonAnimator a in skeleton_animator_collection.Values)
                    {
                        a.calcLastFrame();
                    }
                }
                else
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Animation Dictionary", "0 animations found :<");
                }
            }
            catch (Exception e)
            {
                Debug.DebugHelper.logError("\tCreating Animation Dictionary", e.Message);
            }


            //------------------------------------------------------
            // Create Visual Scene + Skeleton Dictionary
            //------------------------------------------------------
            Debug.DebugHelper.logInfo(2, "\tCreating Visuals Dictionary", dae_file.Library_Visual_Scene.Visual_Scene[0].Node.Count() + " visuals found");
            List <Grendgine_Collada_Node>     mesh_visual_collection       = new List <Grendgine_Collada_Node>();
            List <Grendgine_Collada_Node>     controlled_visual_collection = new List <Grendgine_Collada_Node>();
            List <Grendgine_Collada_Node>     light_visual_collection      = new List <Grendgine_Collada_Node>();
            Dictionary <string, DAE_Skeleton> skeleton_dictionary          = new Dictionary <string, DAE_Skeleton>();

            light_extras = new Dictionary <string, LightLoader.LightLoaderExtras>();
            foreach (Grendgine_Collada_Node node in dae_file.Library_Visual_Scene.Visual_Scene[0].Node)
            {
                string id = node.ID;

                // Convert Blender transformation to Kailash
                Matrix4 temp_matrix = EngineHelper.createMatrix(
                    new Vector3(node.Translate[0].Value()[0], node.Translate[0].Value()[1], node.Translate[0].Value()[2]),
                    new Vector3(node.Rotate[2].Value()[3], node.Rotate[1].Value()[3], node.Rotate[0].Value()[3]),
                    new Vector3(node.Scale[0].Value()[0], node.Scale[0].Value()[1], node.Scale[0].Value()[2])
                    );
                Matrix4 temp_corrected_matrix = EngineHelper.blender2Kailash(temp_matrix);

                // Skeletons
                if (node.node != null && node.node[0].Instance_Geometry == null && node.node[0].Instance_Geometry == null)
                {
                    DAE_Skeleton     temp_skeleton = new DAE_Skeleton(id, temp_matrix, node.node);
                    SkeletonAnimator temp_animator;
                    if (skeleton_animator_collection.TryGetValue(temp_skeleton.id, out temp_animator))
                    {
                        temp_skeleton.animator = temp_animator;
                    }
                    skeleton_dictionary.Add(id, temp_skeleton);
                    continue;
                }

                // Lights
                if (node.Instance_Light != null)
                {
                    string         light_id      = node.Instance_Light[0].URL.Replace("#", "");
                    ObjectAnimator temp_animator = null;
                    object_animator_collection.TryGetValue(light_id.Replace("-light", ""), out temp_animator);
                    LightLoader.LightLoaderExtras temp_light_extras = new LightLoader.LightLoaderExtras(temp_corrected_matrix, temp_animator);
                    // Add to light matrix collection
                    light_extras.Add(light_id, temp_light_extras);
                    continue;
                }

                // Meshes
                if (node.Instance_Geometry != null)
                {
                    string mesh_id = node.Instance_Geometry[0].URL.Replace("#", "");
                    // Add to scene collection
                    mesh_visual_collection.Add(node);
                    continue;
                }

                // Controlled Objects
                if (node.Instance_Controller != null)
                {
                    string controller_id = node.Instance_Controller[0].URL.Replace("#", "");
                    // Add to scene collection
                    controlled_visual_collection.Add(node);
                    continue;
                }
            }


            //------------------------------------------------------
            // Load Skinning Data
            //------------------------------------------------------
            Dictionary <string, string> mesh_2_skeleton = new Dictionary <string, string>();
            Dictionary <string, string> skin_2_mesh     = new Dictionary <string, string>();

            try
            {
                if (dae_file.Library_Controllers.Controller != null)
                {
                    Debug.DebugHelper.logInfo(2, "\tLoading Skinning Data", dae_file.Library_Controllers.Controller.Count() + " skins found");
                    foreach (Grendgine_Collada_Controller c in dae_file.Library_Controllers.Controller)
                    {
                        string skin_id     = c.ID;
                        string skeleton_id = c.Name.Replace(".", "_");
                        ;

                        DAE_Skeleton temp_skeleton;
                        if (skeleton_dictionary.TryGetValue(skeleton_id, out temp_skeleton))
                        {
                            Grendgine_Collada_Skin temp_skin = c.Skin;
                            string mesh_id = temp_skin.source.Replace("#", "");

                            //------------------------------------------------------
                            // Load BSM into skeleton
                            //------------------------------------------------------
                            Matrix4 BSM = EngineHelper.createMatrix(temp_skin.Bind_Shape_Matrix.Value());
                            temp_skeleton.BSM = BSM;

                            //------------------------------------------------------
                            // Load Sources
                            //------------------------------------------------------
                            Dictionary <string, Grendgine_Collada_Source> source_dictionary = temp_skin.Source.ToDictionary(s => s.ID, s => s);

                            string joint_source_id   = "";
                            string IBM_source_id     = "";
                            string weights_source_id = "";

                            foreach (Grendgine_Collada_Input_Unshared i in temp_skin.Joints.Input)
                            {
                                switch (i.Semantic.ToString())
                                {
                                case "JOINT":
                                    joint_source_id = i.source.Replace("#", "");
                                    break;

                                case "INV_BIND_MATRIX":
                                    IBM_source_id = i.source.Replace("#", "");
                                    break;
                                }
                            }
                            foreach (Grendgine_Collada_Input_Shared i in temp_skin.Vertex_Weights.Input)
                            {
                                switch (i.Semantic.ToString())
                                {
                                case "WEIGHT":
                                    weights_source_id = i.source.Replace("#", "");
                                    break;
                                }
                            }

                            Grendgine_Collada_Source IBM_source     = source_dictionary[IBM_source_id];
                            Grendgine_Collada_Source weights_source = source_dictionary[weights_source_id];

                            //------------------------------------------------------
                            // Load Bone IDs
                            //------------------------------------------------------
                            string[] bone_names = source_dictionary[joint_source_id].Name_Array.Value();
                            int[]    bone_ids   = new int[bone_names.Length];
                            for (int i = 0; i < bone_names.Length; i++)
                            {
                                bone_ids[i] = temp_skeleton.bone_ids[bone_names[i]];
                            }

                            //------------------------------------------------------
                            // Load IBMs
                            //------------------------------------------------------
                            int IBM_stride = 16;
                            for (int i = 0; i < bone_names.Length; i++)
                            {
                                float[] temp_IBM = new float[IBM_stride];
                                Array.Copy(IBM_source.Float_Array.Value(), i * IBM_stride, temp_IBM, 0, IBM_stride);

                                string current_bone_name = bone_names[i];
                                int    current_bone_id   = temp_skeleton.bone_ids[current_bone_name];

                                temp_skeleton.bones[current_bone_id].IBM = EngineHelper.createMatrix(temp_IBM);
                            }

                            //------------------------------------------------------
                            // Load Vertex Weights
                            //------------------------------------------------------
                            float[] vertex_weights    = weights_source.Float_Array.Value();
                            int[]   bones_and_weights = temp_skin.Vertex_Weights.V.Value();
                            string  vcount_string     = temp_skin.Vertex_Weights.VCount.Value_As_String;
                            int[]   vcount            = Grendgine_Collada_Parse_Utils.String_To_Int(vcount_string.Remove(vcount_string.Length - 1, 1));

                            int current_weight_index = 0;
                            for (int i = 0; i < vcount.Length; i++)
                            {
                                int num_bones = vcount[i];
                                List <DAE_Skeleton.VertexWeight> temp_weights = new List <DAE_Skeleton.VertexWeight>();

                                for (int j = 0; j < num_bones * 2; j += 2)
                                {
                                    int bone_index   = bones_and_weights[current_weight_index + j];
                                    int weight_index = bones_and_weights[current_weight_index + j + 1];

                                    temp_weights.Add(new DAE_Skeleton.VertexWeight(bone_ids[bone_index], i, vertex_weights[weight_index]));
                                }
                                current_weight_index += num_bones * 2;

                                temp_skeleton.vertex_weights.Add(i, temp_weights.ToArray());
                            }


                            //------------------------------------------------------
                            // Map mesh_id to the Mesh's skeleton_id
                            //------------------------------------------------------
                            mesh_2_skeleton.Add(mesh_id, skeleton_id);
                            skin_2_mesh.Add(skin_id, mesh_id);
                        }
                    }
                }
                else
                {
                    Debug.DebugHelper.logInfo(2, "\tLoading Skinning Data", "0 skins found :<");
                }
            }
            catch (Exception e)
            {
                Debug.DebugHelper.logError("\tLoading Skinning Data", e.Message);
            }



            //------------------------------------------------------
            // Create Mesh Dictionary
            //------------------------------------------------------
            Dictionary <string, DAE_Mesh> mesh_collection = new Dictionary <string, DAE_Mesh>();

            try
            {
                if (dae_file.Library_Geometries != null)
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Mesh Dictionary", dae_file.Library_Geometries.Geometry.Count() + " meshes found");
                    foreach (Grendgine_Collada_Geometry g in dae_file.Library_Geometries.Geometry)
                    {
                        // Load Mesh
                        string mesh_id = g.Name.Replace('.', '_') + "-mesh";

                        DAE_Mesh temp_mesh = new DAE_Mesh(mesh_id, g);
                        try
                        {
                            string skeleton_id;
                            if (mesh_2_skeleton.TryGetValue(mesh_id, out skeleton_id))
                            {
                                temp_mesh.load(material_collection, skeleton_dictionary[skeleton_id]);
                            }
                            else
                            {
                                temp_mesh.load(material_collection);
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.DebugHelper.logError("[ FAILED ] Loading Mesh: " + mesh_id, e.Message);
                            continue;
                        }

                        // Load mesh's VAO
                        foreach (Mesh mesh in temp_mesh.submeshes)
                        {
                            mesh.setBufferIDs(loadVAO(mesh));
                        }

                        // Add to Mesh Collection
                        mesh_collection.Add(temp_mesh.id, temp_mesh);
                    }
                }
                else
                {
                    Debug.DebugHelper.logInfo(2, "\tCreating Mesh Dictionary", "0 meshes found :<");
                }
            }
            catch (Exception e)
            {
                Debug.DebugHelper.logError("\tCreating Mesh Dictionary", e.Message);
            }



            //------------------------------------------------------
            // Create Mesh Visuals
            //------------------------------------------------------
            Debug.DebugHelper.logInfo(2, "\tLoading Mesh Visuals", "");
            unique_mesh_collection = new Dictionary <string, UniqueMesh>();
            foreach (Grendgine_Collada_Node node in mesh_visual_collection)
            {
                string visual_id = node.ID;
                string mesh_id   = node.Instance_Geometry[0].URL.Replace("#", "");

                Debug.DebugHelper.logInfo(3, "\t\tLoading Visual Scene", visual_id);

                // Convert Blender transformation to Kailash
                Matrix4 temp_matrix = EngineHelper.blender2Kailash(EngineHelper.createMatrix(
                                                                       new Vector3(node.Translate[0].Value()[0], node.Translate[0].Value()[1], node.Translate[0].Value()[2]),
                                                                       new Vector3(node.Rotate[2].Value()[3], node.Rotate[1].Value()[3], node.Rotate[0].Value()[3]),
                                                                       new Vector3(node.Scale[0].Value()[0], node.Scale[0].Value()[1], node.Scale[0].Value()[2])
                                                                       ));

                // Load unique Mesh and its transformation
                DAE_Mesh m;
                if (mesh_collection.TryGetValue(mesh_id, out m))
                {
                    UniqueMesh temp_unique_mesh = new UniqueMesh(visual_id, m, temp_matrix);

                    // Add animator to unique mesh if one exists
                    ObjectAnimator temp_animator;
                    if (object_animator_collection.TryGetValue(visual_id, out temp_animator))
                    {
                        temp_unique_mesh.animator = temp_animator;
                    }

                    // Add to mesh collection
                    unique_mesh_collection.Add(visual_id, temp_unique_mesh);
                }
            }

            //------------------------------------------------------
            // Create Skin Visuals
            //------------------------------------------------------
            Debug.DebugHelper.logInfo(2, "\tLoading Controlled Visuals", "");
            foreach (Grendgine_Collada_Node node in controlled_visual_collection)
            {
                string visual_id     = node.ID;
                string controller_id = node.Instance_Controller[0].URL.Replace("#", "");
                string mesh_id;

                if (skin_2_mesh.TryGetValue(controller_id, out mesh_id))
                {
                    Debug.DebugHelper.logInfo(3, "\t\tLoading Visual Scene", visual_id + " (" + controller_id + " )");

                    // Convert Blender transformation to Kailash
                    Matrix4 temp_matrix = EngineHelper.blender2Kailash(EngineHelper.createMatrix(
                                                                           new Vector3(node.Translate[0].Value()[0], node.Translate[0].Value()[1], node.Translate[0].Value()[2]),
                                                                           new Vector3(node.Rotate[2].Value()[3], node.Rotate[1].Value()[3], node.Rotate[0].Value()[3]),
                                                                           new Vector3(node.Scale[0].Value()[0], node.Scale[0].Value()[1], node.Scale[0].Value()[2])
                                                                           ));

                    // Load unique Mesh and its transformation
                    DAE_Mesh m;
                    if (mesh_collection.TryGetValue(mesh_id, out m))
                    {
                        UniqueMesh temp_unique_mesh_test = new UniqueMesh(visual_id, m, temp_matrix);
                        unique_mesh_collection.Add(visual_id, temp_unique_mesh_test);
                    }
                }
            }



            // Clear dictionaries. dat mesh is loooaded
            image_collection.Clear();
            material_collection.Clear();
            mesh_collection.Clear();
            object_animator_collection.Clear();
            skeleton_animator_collection.Clear();
            mesh_visual_collection.Clear();
            controlled_visual_collection.Clear();
            light_visual_collection.Clear();
            skeleton_dictionary.Clear();
            mesh_2_skeleton.Clear();
        }
Example #14
0
 public BMDManager(Grendgine_Collada scene)
 {
     Skeleton = new Skeleton(scene);
     Geometry = new GeometryManager(scene);
     Skeleton.AssignBoneBoundingBoxes(Geometry.VertexData.Positions);
 }
Example #15
0
        public IEnumerable <Category> Load(string fileName)
        {
            categoryCollection = new ObservableCollection <Category>();

            Grendgine_Collada file = Grendgine_Collada.Grendgine_Load_File(fileName);

            for (int i = 0; i < file.Library_Geometries.Geometry.Length; i++)
            {
                Category cat = new Category();

                cat.Name = file.Library_Geometries.Geometry[i].Name + "_parent";

                List <Vector3> verts = GetVerts(file.Library_Geometries.Geometry[i]);

                int skipValue = CalcSkipValue(file.Library_Geometries.Geometry[i]);

                Group grp = new Group();

                grp.Name = file.Library_Geometries.Geometry[i].Name;

                int[] pList = null;

                if (file.Library_Geometries.Geometry[i].Mesh.Polylist == null)
                {
                    // Horrible sanitization of 3dsmax's collada data
                    string plist = file.Library_Geometries.Geometry[i].Mesh.Triangles[0].P.Value_As_String;
                    plist = plist.Replace('\n', ' ').Trim();
                    file.Library_Geometries.Geometry[i].Mesh.Triangles[0].P.Value_As_String = plist;

                    pList = file.Library_Geometries.Geometry[i].Mesh.Triangles[0].P.Value();
                }

                else
                {
                    pList = file.Library_Geometries.Geometry[i].Mesh.Polylist[0].P.Value();
                }

                List <int> vertIndexes = GetVertIndexes(pList, skipValue);

                for (int j = 0; j < vertIndexes.Count; j += 3)
                {
                    Triangle face = new Triangle();

                    face.Vertex1 = verts[vertIndexes[j]];

                    face.Vertex2 = verts[vertIndexes[j + 1]];

                    face.Vertex3 = verts[vertIndexes[j + 2]];

                    face.ParentGroup = grp;

                    grp.Triangles.Add(face);
                }

                grp.CreateBufferObjects();

                grp.GroupCategory = cat;

                cat.Groups.Add(grp);

                categoryCollection.Add(cat);
            }

            return(categoryCollection);
        }
Example #16
0
        public void Import(string fileName)
        {
            // Only need to Update the HEADER, and Animation.Duration, ASETHEADER is auto handled
            this.File = new BrgFile();
            BrgFile           model  = this.File; // just ref here so I don't have to rename model to this.File
            Grendgine_Collada cModel = Grendgine_Collada.Grendgine_Load_File(fileName);

            //Materials
            BrgMaterial mat = new BrgMaterial(model);

            model.Materials.Add(mat);
            mat.AmbientColor     = new Color3D();
            mat.DiffuseColor     = new Color3D();
            mat.SpecularColor    = new Color3D(0.5f);
            mat.SpecularExponent = 5;
            mat.Id      = 100;
            mat.Opacity = 1f;
            mat.Flags  |= BrgMatFlag.HasTexture | BrgMatFlag.SpecularExponent;

            model.Header.NumMaterials = model.Materials.Count();

            //Meshes
            foreach (Grendgine_Collada_Geometry geo in cModel.Library_Geometries.Geometry)
            {
                BrgMesh mesh = new BrgMesh(model);
                model.Meshes.Add(mesh);

                mesh.Header.Flags                     |= BrgMeshFlag.MATERIAL;
                mesh.Header.Flags                     |= model.Meshes.Count == 1 ? 0 : BrgMeshFlag.SECONDARYMESH;
                mesh.Header.AnimationType             |= BrgMeshAnimType.KeyFrame;
                mesh.Header.Format                    |= 0;
                mesh.ExtendedHeader.NumMaterials       = (byte)model.Header.NumMaterials;
                mesh.ExtendedHeader.AnimationLength    = 30;
                mesh.ExtendedHeader.NumUniqueMaterials = 0;

                string polyVertSourceID;
                string polyNormalsSourceID;
                string materialID;
                int[]  vertCountPerPoly;
                int[]  vertLinkPerPoly;
                int[]  vertNormalBindings;

                //Locate the vertices and convert them
                string vertexPosSourceID = geo.Mesh.Vertices.Input.First <Grendgine_Collada_Input_Unshared>(x => x.Semantic == Grendgine_Collada_Input_Semantic.POSITION).source;
                Grendgine_Collada_Float_Array vertsArray = FindSourceByID(geo.Mesh, vertexPosSourceID).Float_Array;

                mesh.Vertices           = FloatToVectorArray(vertsArray);
                mesh.Header.NumVertices = (short)mesh.Vertices.Count;

                //Check for polygons otherwise skip mesh
                if (geo.Mesh.Polylist != null || geo.Mesh.Polylist.Length > 0)
                {
                    mesh.Header.NumFaces = (short)geo.Mesh.Polylist[0].Count;
                    polyVertSourceID     = geo.Mesh.Polylist[0].Input.First <Grendgine_Collada_Input_Unshared>(x => x.Semantic == Grendgine_Collada_Input_Semantic.VERTEX).source;
                    polyNormalsSourceID  = geo.Mesh.Polylist[0].Input.First <Grendgine_Collada_Input_Unshared>(x => x.Semantic == Grendgine_Collada_Input_Semantic.NORMAL).source;
                    vertCountPerPoly     = geo.Mesh.Polylist[0].VCount.Value();
                    materialID           = geo.Mesh.Polylist[0].Material;
                    vertLinkPerPoly      = geo.Mesh.Polylist[0].P.Value();

                    mesh.Faces = new List <Face>(mesh.Header.NumFaces);

                    vertNormalBindings = new int[mesh.Header.NumVertices];

                    int  polyindex = 0;
                    Face ff;
                    foreach (int count in vertCountPerPoly)
                    {
                        if (count == 3) //If triangle
                        {
                            ff         = new Face();
                            ff.Indices = new List <short>(3);
                            ff.Indices.Add((short)vertLinkPerPoly[polyindex]);
                            ff.Indices.Add((short)vertLinkPerPoly[polyindex + 4]);
                            ff.Indices.Add((short)vertLinkPerPoly[polyindex + 2]);
                            //List correct normal bindings
                            vertNormalBindings[ff.Indices[0]] = vertLinkPerPoly[polyindex + 1];
                            vertNormalBindings[ff.Indices[1]] = vertLinkPerPoly[polyindex + 5];
                            vertNormalBindings[ff.Indices[2]] = vertLinkPerPoly[polyindex + 3];
                            //Bind materials
                            if (mesh.Header.Flags.HasFlag(BrgMeshFlag.MATERIAL))
                            {
                                ff.MaterialIndex = (short)mat.Id;
                            }
                            mesh.Faces.Add(ff);
                        }
                        polyindex += count * 2; //Including face normal bindings
                    }
                }
                else
                {
                    break;
                }

                //Locate the vertex normals
                Grendgine_Collada_Float_Array normalsArray = FindSourceByID(geo.Mesh, polyNormalsSourceID).Float_Array;
                if (normalsArray.Count != vertsArray.Count)
                {
                    System.Windows.Forms.MessageBox.Show("The mesh hash only face normals instead of vertex normals. Be sure to export only smooth shaded models.", "Model Import Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                }
                List <Vector3D> unsortedNormals = FloatToVectorArray(normalsArray);
                mesh.Normals = new List <Vector3D>(mesh.Header.NumVertices);
                for (int i = 0; i < mesh.Header.NumVertices; i++)
                {
                    mesh.Normals.Add(unsortedNormals[vertNormalBindings[i]]);
                }

                mesh.VertexMaterials = new List <short>(mesh.Header.NumVertices);
                for (int i = 0; i < mesh.Header.NumVertices; i++)
                {
                    mesh.VertexMaterials.Add((short)mat.Id);
                }
            }

            model.Header.NumMeshes = model.Meshes.Count();
        }
Example #17
0
        public Skeleton(Grendgine_Collada scene)
        {
            boneNameList         = new List <string>();
            inverseBindMatrices  = new List <Matrix4>();
            weights              = new List <float>();
            vertexBoneIndexPairs = new List <int>();
            vertexWeightCounts   = new List <int>();
            FlatHierarchy        = new List <Bone>();
            BonesWithGeometry    = new List <Bone>();
            VertexWeights        = new List <Weight>();
            MultiBoneWeights     = new List <Weight>();

            SkeletonRoot = new Bone(GetSkeletonFromVisualScene(scene));

            Grendgine_Collada_Skin skin = GetSkinningInfo(scene);

            // Get bone names and inverse bind matrices
            if (skin.Joints != null)
            {
                foreach (Grendgine_Collada_Input_Unshared input in skin.Joints.Input)
                {
                    if (input.Semantic == Grendgine_Collada_Input_Semantic.JOINT)
                    {
                        GetJointNamesFromSkin(input.source.Remove(0, 1), skin);
                    }
                    else if (input.Semantic == Grendgine_Collada_Input_Semantic.INV_BIND_MATRIX)
                    {
                        GetInvBindMatricesFromSkin(input.source.Remove(0, 1), skin);
                    }
                }
            }

            // Get vertex weights, vertex/bone pairs, and vertex weight counts
            if (skin.Vertex_Weights != null)
            {
                foreach (Grendgine_Collada_Input_Unshared input in skin.Vertex_Weights.Input)
                {
                    if (input.Semantic == Grendgine_Collada_Input_Semantic.WEIGHT)
                    {
                        GetWeightsFromSkin(input.source.Remove(0, 1), skin);
                    }
                }
            }

            Dictionary <string, Matrix4> matrixDict = new Dictionary <string, Matrix4>();

            for (int i = 0; i < boneNameList.Count; i++)
            {
                matrixDict.Add(boneNameList[i], inverseBindMatrices[i]);
            }

            //Assign inverse bind matrices to the bones that need one
            SkeletonRoot.GetInverseBindMatrixRecursive(matrixDict);

            // Flatten hierarchy for easy access later
            SkeletonRoot.FlattenHierarchy(FlatHierarchy);

            // We'll make another list that contains just the bones with geometry from boneNameList, in order,
            // so that the vertex weights and bone assignments can be used correctly.
            MakeBoneGeometryList();
            List <Bone> testList = new List <Bone>();

            int offset = 0;

            for (int i = 0; i < vertexWeightCounts.Count; i++)
            {
                int    numWeights = vertexWeightCounts[i];
                Weight weight     = new Weight();

                while (numWeights != 0)
                {
                    Bone  bone      = BonesWithGeometry[vertexBoneIndexPairs[offset++]];
                    float weightVal = weights[vertexBoneIndexPairs[offset++]];

                    weight.AddBoneWeight((short)FlatHierarchy.IndexOf(bone), weightVal);

                    numWeights--;
                }

                if ((weight.BoneIndexes.Count) > 1)
                {
                    MultiBoneWeights.Add(weight);
                }
                if ((weight.BoneWeights.Count == 1) && (!testList.Contains(FlatHierarchy[weight.BoneIndexes[0]])))
                {
                    testList.Add(FlatHierarchy[weight.BoneIndexes[0]]);
                }

                VertexWeights.Add(weight);
            }

            drw1Data = new DrawData(VertexWeights, FlatHierarchy, BonesWithGeometry);
        }
        public ColladaGeometry(string file)
        {
            var collada = Grendgine_Collada.Grendgine_Load_File(file);

            if (collada == null)
            {
                return;
            }

            foreach (var geometry in collada.Library_Geometries.Geometry)
            {
                var mesh = geometry.Mesh;

                Dictionary <string, Collada_Source> sources = new Dictionary <string, Collada_Source>();
                foreach (var source in mesh.Source)
                {
                    sources[source.ID] = source;
                }

                foreach (var polylist in mesh.Polylist)
                {
                    // input
                    int[]         vcount = polylist.VCount.Value();
                    int[]         p      = polylist.P.Value();
                    StringBuilder vSb    = new StringBuilder();
                    StringBuilder pSb    = new StringBuilder();

                    foreach (int i in vcount)
                    {
                        vSb.Append(i.ToString());
                        vSb.Append(" ");
                    }
                    foreach (int pi in p)
                    {
                        pSb.Append(pi.ToString());
                        pSb.Append(" ");
                    }
                    System.Diagnostics.Trace.TraceInformation(
                        "Polylist.VCount : " + vSb.ToString()
                        );
                    System.Diagnostics.Trace.TraceInformation(
                        "Polylist.P : " + pSb.ToString()
                        );
                    foreach (var input in polylist.Input)
                    {
                        System.Diagnostics.Trace.TraceInformation(
                            "input.Semantic : " + input.Semantic.ToString() + "\n" +
                            "input.Source   : " + input.source + "\n" +
                            "input.Offset   : " + input.Offset + "\n" +
                            "input.Set      : " + input.Set + "\n"
                            );
                        Collada_Source source = sources[input.source];
                        if (source.Technique_Common != null)
                        {
                        }
                    }
                    System.Diagnostics.Debugger.Break();
                }

                /*var sources = mesh.Source;
                 * var vertices = mesh.Vertices;
                 * foreach(var input in vertices.Input)
                 * {
                 * }*/

                foreach (var polygon in geometry.Mesh.Polygons)
                {
                    // input points to sources either directly
                    // or through sources defined in vertices
                    // (vertex semantics)
                    foreach (var input in polygon.Input)
                    {
                    }
                    foreach (int index in polygon.P.Value())
                    {
                    }
                }
            }
        }