static void exportBone(BinaryWriter dest, MeshNode target,  Assimp.Scene scene, int boneID)
        {
            Assimp.Node node = target.node;

            exportString(dest, node.Name);
            if (node.Parent!=null)
                exportString(dest, node.Parent.Name);
            else
                exportString(dest, "");

            Matrix4x4 mat = new Matrix4x4(node.Transform.A1, node.Transform.A2, node.Transform.A3, node.Transform.A4, node.Transform.B1, node.Transform.B2, node.Transform.B3, node.Transform.B4, node.Transform.C1, node.Transform.C2, node.Transform.C3, node.Transform.C4, node.Transform.D1, node.Transform.D2, node.Transform.D3, node.Transform.D4);
            mat.Transpose();

            exportMatrix(dest, mat);

            Bone bone = target.bone;
            if (bone != null)
            {
                mat = new Matrix4x4(bone.OffsetMatrix.A1, bone.OffsetMatrix.A2, bone.OffsetMatrix.A3, bone.OffsetMatrix.A4, bone.OffsetMatrix.B1, bone.OffsetMatrix.B2, bone.OffsetMatrix.B3, bone.OffsetMatrix.B4, bone.OffsetMatrix.C1, bone.OffsetMatrix.C2, bone.OffsetMatrix.C3, bone.OffsetMatrix.C4, bone.OffsetMatrix.D1, bone.OffsetMatrix.D2, bone.OffsetMatrix.D3, bone.OffsetMatrix.D4);
                mat.Transpose();
            }
            else
                mat = Matrix4x4.Identity;

            exportMatrix(dest, mat);
        }
Beispiel #2
0
        private static GeometryData GenerateGeometryDataFromAssimpMesh(Assimp.Mesh mesh)
        {
            var geometryData = new GeometryData
            {
                Vertices = new VertexPositionNormalTexture[mesh.VertexCount],
                Indices = new ushort[mesh.FaceCount * 3]
            };

            geometryData.Vertices = new VertexPositionNormalTexture[mesh.VertexCount];

            for (var i = 0; i < mesh.VertexCount; i++)
            {
                var vertex = mesh.Vertices[i];
                geometryData.Vertices[i].Position = new Vector3(vertex.X, vertex.Y, vertex.Z);

                var normal = mesh.Normals[i];
                geometryData.Vertices[i].Normal = new Vector3(normal.X, normal.Y, normal.Z);

                var texcoord = mesh.TextureCoordinateChannels[0][i];
                geometryData.Vertices[i].TextureCoordinate = new Vector2(texcoord.X, texcoord.Y);
            }

            for (var i = 0; i < mesh.FaceCount; i++)
            {
                geometryData.Indices[i * 3 + 0] = (ushort)mesh.Faces[i].Indices[0];
                geometryData.Indices[i * 3 + 1] = (ushort)mesh.Faces[i].Indices[1];
                geometryData.Indices[i * 3 + 2] = (ushort)mesh.Faces[i].Indices[2];
            }

            return geometryData;
        }
Beispiel #3
0
 public static void AreEqual(Assimp.Matrix4x4 a, SharpDX.Matrix b)
 {
     Vector3D transA;
     Vector3 transB;
     Vector3D scaleA;
     Vector3 scaleB;
     Assimp.Quaternion rotA;
     SharpDX.Quaternion rotB;
     a.Decompose(out scaleA, out rotA, out transA);
     b.Decompose(out scaleB, out rotB, out transB);
     AreEqual(transA, transB);
     AreEqual(rotA, rotB);
     AreEqual(scaleA, scaleB);
     //AreNearEqual(a.A1, b.M11);
     //AreNearEqual(a.A2, b.M12);
     //AreNearEqual(a.A3, b.M13);
     //AreNearEqual(a.A4, b.M14);
     //AreNearEqual(a.B1, b.M21);
     //AreNearEqual(a.B2, b.M22);
     //AreNearEqual(a.B3, b.M23);
     //AreNearEqual(a.B4, b.M24);
     //AreNearEqual(a.C1, b.M31);
     //AreNearEqual(a.C2, b.M32);
     //AreNearEqual(a.C3, b.M33);
     //AreNearEqual(a.C4, b.M34);
     //AreNearEqual(a.D1, b.M41);
     //AreNearEqual(a.D2, b.M42);
     //AreNearEqual(a.D3, b.M43);
     //AreNearEqual(a.D4, b.M44);
 }
Beispiel #4
0
 public static void AreEqual(Assimp.Color4D a, SharpDX.Color4 b)
 {
     Assert.AreEqual(a.A, b.Alpha);
     Assert.AreEqual(a.R, b.Red);
     Assert.AreEqual(a.G, b.Green);
     Assert.AreEqual(a.B, b.Blue);
 }
Beispiel #5
0
 public static void AreEqual(Assimp.Vector3D[] a, SharpDX.Vector3[] b)
 {
     Assert.AreEqual(a.Length, b.Length);
     for (int i = 0; i < a.Length; i++)
     {
         AreEqual(a[i], b[i]);
     }
 }
 /// <summary>
 /// Creates an Assimp.Animation by copying the given source Assimp.Animation content.<br />
 /// </summary>
 /// <param name="rootNode"></param>
 /// <param name="sourceAnimation">The source Assimp.Animation to copy.</param>
 /// <returns></returns>
 private static Assimp.Animation CreateAssimpAnimation(Node rootNode, Assimp.Animation sourceAnimation)
 {
     Assimp.Animation animation = new Assimp.Animation();
     animation.DurationInTicks = sourceAnimation.DurationInTicks;
     animation.Name = sourceAnimation.Name;
     animation.TicksPerSecond = sourceAnimation.TicksPerSecond;
     CreateNodeAnimationChannels(animation, sourceAnimation.NodeAnimationChannels, rootNode);
     return animation;
 }
Beispiel #7
0
    private static void processNodes(IntPtr scene, IntPtr node, ref List <AssimpJoint> listJoints)
    {
        AssimpJoint joint = new AssimpJoint();

        string name = Assimp.aiNode_GetName(node);

        if (name == "")
        {
            name = "REMOVE-ME";
        }
        joint.Name       = name;
        joint.parentName = "NONE";
        joint.Position   = Assimp.aiNode_GetPosition(node);
        //assimp quaternion is w,x,y,z and unity x,y,z,w bu int this lib i fix this for unity
        Quaternion quad = Assimp.aiNode_GetRotation(node);

        joint.Orientation = quad;



        if (Assimp.aiNode_GetParent(node) != null)
        {
            string parentName = Assimp.aiNode_GetName(Assimp.aiNode_GetParent(node));
            joint.parentName = parentName;
        }


        listJoints.Add(joint);

        for (int i = 0; i < listJoints.Count; i++)
        {
            AssimpJoint parent = listJoints[i];
            if (joint.parentName == parent.Name)
            {
                joint.parent = parent;
                joint.Path  += parent.Path + "/";
                break;
            }
        }

        joint.Path += name;

        if (joint.parent != null)
        {
            //   Debug.Log(string.Format(" Joint  name: {0}  ; parent:{1} ;  animation path:{2} ", joint.Name, joint.parent.Name,"Skeleton/" +  joint.Path));
        }
        else
        {
            //   Debug.Log(string.Format(" Joint  name: {0}  ; animation path:{1} ", joint.Name,"Skeleton/" + joint.Path));
        }

        for (int n = 0; n < Assimp.aiNode_GetNumChildren(node); n++)
        {
            processNodes(scene, Assimp.aiNode_GetChild(node, n), ref listJoints);
        }
    }
        /// <summary>
        /// Creates an Assimp.NodeAnimationChannel from the given NodeAnimationChannel list and Assimp.Node.<br />
        /// Adds the Assimp.NodeAnimationChannel to the given Assimp.Animation
        /// </summary>
        /// <param name="node"></param>
        /// <param name="channel"></param>
        private static void CreateNodeAnimationChannels(Assimp.Animation animation, List<NodeAnimationChannel> sourceNodeAnimationChannels, Node node)
        {
            NodeAnimationChannel nodeAnimationChannel = new NodeAnimationChannel();
            nodeAnimationChannel = sourceNodeAnimationChannels[animation.NodeAnimationChannelCount];
            nodeAnimationChannel.NodeName = node.Name;
            animation.NodeAnimationChannels.Add(nodeAnimationChannel);

            for (int i = 0; i < node.ChildCount; i++)
                CreateNodeAnimationChannels(animation, sourceNodeAnimationChannels, node.Children[i]);
        }
        public TexturedMaterial(Assimp.Material m, string materialDirectory)
            : this()
        {
            Diffuse = m.ColorDiffuse.ToNETColor();
            Specular = m.ColorSpecular.ToNETColor();
            //Ambient = m.ColorAmbient.ToNETColor();
            Emissive = m.ColorEmissive.ToNETColor();

            textureSlots = new List<Assimp.TextureSlot>(m.GetAllTextures());
            LoadTextures(materialDirectory);
        }
        /// <summary>
        /// Applies a 4x4 Assimp matrix to all of the vertices
        /// </summary>
        /// <param name="vertices">The vertices to apply the matrix to</param>
        /// <param name="mat">The matrix</param>
        private static void ApplyMatrixLocal(List<ObjVertex> vertices, Assimp.Matrix4x4 mat)
        {
            //Console.WriteLine("Applying: {0}", mat);
            foreach (var v in vertices) {
                var pos = v.Position;
                Vector4 newPos = new Vector4(mat.A1 * pos.X + mat.B1 * pos.Y + mat.C1 * pos.Z + mat.D1 * pos.W,
                                             mat.A2 * pos.X + mat.B2 * pos.Y + mat.C2 * pos.Z + mat.D2 * pos.W,
                                             mat.A3 * pos.X + mat.B3 * pos.Y + mat.C3 * pos.Z + mat.D3 * pos.W,
                                             mat.A4 * pos.X + mat.B4 * pos.Y + mat.C4 * pos.Z + mat.D4 * pos.W);
                v.Position = newPos;

            }
        }
Beispiel #11
0
        /// <summary>
        /// Sets the contents of the info pop-up given an assimp node.
        /// 
        /// At the time this method is called, the node info popup's
        /// location has already been adjusted by the caller.
        /// </summary>
        public void Populate(Assimp.Scene scene, Node node, NodePurpose purpose)
        {
            Debug.Assert(scene != null);
            Debug.Assert(node != null);
            Debug.Assert(_owner != null);
            switch (purpose)
            {
                case NodePurpose.Joint:
                    labelCaption.Text = "Joint";
                    break;
                case NodePurpose.ImporterGenerated:
                    labelCaption.Text = "Root";
                    break;
                case NodePurpose.GenericMeshHolder:
                    labelCaption.Text = "Node";
                    break;
                case NodePurpose.Camera:
                    labelCaption.Text = "Camera";
                    break;
                case NodePurpose.Light:
                    labelCaption.Text = "Light";
                    break;
                default:
                    Debug.Assert(false);
                    break;
            }

            // count children recursively
            var children = 0;
            CountChildren(node, ref children);

            var animated = false;

            // check whether there are any animation channels for this node
            for (var i = 0; i < scene.AnimationCount && !animated; ++i )
            {
                var anim = scene.Animations[i];
                for(var j = 0; j < anim.NodeAnimationChannelCount; ++j)
                {
                    if(anim.NodeAnimationChannels[j].NodeName == node.Name)
                    {
                        animated = true;
                        break;
                    }
                }
            }

            labelInfo.Text = string.Format("{0} Children\n{1}", children, (animated ? "Animated" : "Not animated"));
        }
Beispiel #12
0
        static void addNodes(List<MeshNode> nodes, Assimp.Node node, Mesh mesh)
        {
            Bone bone =null;
            for (int i = 0; i < mesh.BoneCount; i++ )
            if (mesh.Bones[i].Name.Equals(node.Name))
            {
                bone = mesh.Bones[i];
                break;
            }

            nodes.Add(new MeshNode(node, bone));

            for (int i = 0; i < node.ChildCount; i++)
            {
                addNodes(nodes, node.Children[i], mesh);
            }
        }
 public int Initialize(string rootPath, string modelName, int viewStep, Assimp.Material meterial)
 {
     Name = modelName + "." + meterial.Name;
     ViewStep = viewStep;
     Color.Opacity = meterial.Opacity;
     Color.Shininess = meterial.Shininess;
     for(int i = 0; i < 4; i++)
     {
         Color.Ambient[i] = meterial.ColorAmbient[i];
         Color.Diffuse[i] = meterial.ColorDiffuse[i];
         Color.Emissive[i] = meterial.ColorEmissive[i];
         Color.Reflective[i] = meterial.ColorReflective[i];
         Color.Specular[i] = meterial.ColorSpecular[i];
         Color.Transparent[i] = meterial.ColorTransparent[i];
     }
     SetTexture(rootPath, meterial);
     return viewStep + 5 * Engine.Instance.Core.Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
 }
        /// <summary>
        /// Writes mesh data to the .obj.
        /// </summary>
        /// <param name="reader">The mesh reader to use.</param>
        /// <param name="compressor">The vertex compressor to use.</param>
        /// <param name="resourceStream">A stream open on the resource data.</param>
        public void ExtractMesh(MeshReader reader, Assimp.Matrix4x4 matrix_local, VertexCompressor compressor, Stream resourceStream)
        {
            // Read the vertex buffer and decompress each vertex
            var vertices = ReadVertices(reader, resourceStream);
            DecompressVertices(vertices, compressor);

            ApplyMatrixLocal(vertices, matrix_local);

            // Write out the vertices
            WriteVertices(vertices);

            // Read and write out the triangles for each part
            foreach (var part in reader.Mesh.Parts)
            {
                var indexes = ReadIndexes(reader, part, resourceStream);
                WriteTriangles(indexes);
            }
            _baseIndex += (uint)vertices.Count;
        }
Beispiel #15
0
 void TestAnimationChannel(Assimp.NodeAnimationChannel netChannel, AssimpSharp.NodeAnim sharpChannel)
 {
     Assert.AreEqual(netChannel.NodeName, sharpChannel.NodeName);
     Assert.AreEqual(netChannel.PositionKeyCount, sharpChannel.PositionKeys.Length);
     for (int i = 0; i < netChannel.PositionKeyCount; i++)
     {
         Assert.AreEqual(netChannel.PositionKeys[i].Time, sharpChannel.PositionKeys[i].Time);
         MathAssert.AreEqual(netChannel.PositionKeys[i].Value, sharpChannel.PositionKeys[i].Value);
     }
     Assert.AreEqual(netChannel.RotationKeyCount, sharpChannel.RotationKeys.Length);
     for (int i = 0; i < netChannel.RotationKeyCount; i++)
     {
         Assert.AreEqual(netChannel.RotationKeys[i].Time, sharpChannel.RotationKeys[i].Time);
         MathAssert.AreEqual(netChannel.RotationKeys[i].Value, sharpChannel.RotationKeys[i].Value);
     }
     Assert.AreEqual(netChannel.ScalingKeyCount, sharpChannel.ScalingKeys.Length);
     for (int i = 0; i < netChannel.ScalingKeyCount; i++)
     {
         Assert.AreEqual(netChannel.ScalingKeys[i].Time, sharpChannel.ScalingKeys[i].Time);
         MathAssert.AreEqual(netChannel.ScalingKeys[i].Value, sharpChannel.ScalingKeys[i].Value);
     }
 }
Beispiel #16
0
 public void TestEachNode(Assimp.Node netNode, AssimpSharp.Node sharpNode)
 {
     Assert.AreEqual(netNode.Name, sharpNode.Name);
     MathAssert.AreEqual(netNode.Transform, sharpNode.Transformation);
     Assert.AreEqual(netNode.HasMeshes, sharpNode.Meshes != null && sharpNode.Meshes.Count > 0);
     if (netNode.HasMeshes)
     {
         Assert.AreEqual(netNode.MeshCount, sharpNode.Meshes.Count);
         for (int i = 0; i < netNode.MeshCount; i++)
         {
             Assert.AreEqual(netNode.MeshIndices, sharpNode.Meshes);
         }
     }
     Assert.AreEqual(netNode.HasChildren, sharpNode.Children != null);
     if (netNode.HasChildren)
     {
         Assert.AreEqual(netNode.ChildCount, sharpNode.Children.Count);
         for (int nodeIndex = 0; nodeIndex < netNode.ChildCount; nodeIndex++)
         {
             TestEachNode(netNode.Children[nodeIndex], sharpNode.Children[nodeIndex]);
         }
     }
 }
Beispiel #17
0
 void TestAnimationAttachment(Assimp.MeshAnimationAttachment netAnimMesh, AssimpSharp.AnimMesh sharpAnimMesh)
 {
     Assert.AreEqual(netAnimMesh.HasVertices, sharpAnimMesh.HasPosition);
     if (netAnimMesh.HasVertices)
     {
         Assert.AreEqual(netAnimMesh.Vertices, sharpAnimMesh.Vertices);
     }
     Assert.AreEqual(netAnimMesh.HasNormals, sharpAnimMesh.HasNormals);
     if (netAnimMesh.HasNormals)
     {
         Assert.AreEqual(netAnimMesh.Normals, sharpAnimMesh.Normals);
     }
     Assert.AreEqual(netAnimMesh.HasTangentBasis, sharpAnimMesh.HasTangentsAndBitangets);
     if (netAnimMesh.HasTangentBasis)
     {
         Assert.AreEqual(netAnimMesh.Tangents, sharpAnimMesh.Tangents);
         Assert.AreEqual(netAnimMesh.BiTangents, sharpAnimMesh.Bitangents);
     }
     for (int i = 0; i < netAnimMesh.TextureCoordinateChannelCount; i++)
     {
         Assert.AreEqual(netAnimMesh.HasTextureCoords(i), sharpAnimMesh.HasTextureCoords(i));
         if (netAnimMesh.HasTextureCoords(i))
         {
             Assert.AreEqual(netAnimMesh.TextureCoordinateChannels[i], sharpAnimMesh.TextureCoords[i]);
         }
     }
     for (int i = 0; i < netAnimMesh.VertexColorChannelCount; i++)
     {
         Assert.AreEqual(netAnimMesh.HasVertexColors(i), sharpAnimMesh.HasVertexColors(i));
         if (netAnimMesh.HasVertexColors(i))
         {
             Assert.AreEqual(netAnimMesh.VertexColorChannels[i], sharpAnimMesh.Colors[i]);
         }
     }
 }
Beispiel #18
0
    private static void readMesh(string path, string filename, string texturepath)
    {
        string importingAssetsDir;

        if (File.Exists(path + "/" + filename))
        {
            Assimp.PostProcessSteps flags = (
                //  Assimp.PostProcessSteps.MakeLeftHanded |
                Assimp.PostProcessSteps.Triangulate |
                Assimp.PostProcessSteps.CalculateTangentSpace |
                Assimp.PostProcessSteps.GenerateUVCoords |
                Assimp.PostProcessSteps.GenerateSmoothNormals |
                Assimp.PostProcessSteps.RemoveComponent |
                Assimp.PostProcessSteps.JoinIdenticalVertices);

            IntPtr config = Assimp.aiCreatePropertyStore();

            Assimp.aiSetImportPropertyFloat(config, Assimp.AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, 60.0f);
            Assimp.aiSetImportPropertyInteger(config, Assimp.AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
            // IntPtr scene = Assimp.aiImportFile(path + "/" + filename, (uint)flags);
            IntPtr scene = Assimp.aiImportFileWithProperties(path + "/" + filename, (uint)flags, config);
            Assimp.aiReleasePropertyStore(config);
            if (scene == null)
            {
                Debug.LogWarning("failed to read file: " + path + "/" + filename);
                return;
            }
            else
            {
                string nm = Path.GetFileNameWithoutExtension(filename);


                importingAssetsDir = "Assets/Prefabs/" + nm + "/";

                if (saveAssets)
                {
                    if (!Directory.Exists(importingAssetsDir))
                    {
                        Directory.CreateDirectory(importingAssetsDir);
                    }
                    AssetDatabase.Refresh();
                }


                GameObject ObjectRoot    = new GameObject(nm);
                GameObject meshContainer = new GameObject(nm + "_Mesh");
                meshContainer.transform.parent = ObjectRoot.transform;



                //  List<CombineInstance> combineInstances = new List<CombineInstance>();
                List <Material>   materials = new List <Material>();
                List <AssimpMesh> MeshList  = new List <AssimpMesh>();



                for (int i = 0; i < Assimp.aiScene_GetNumMaterials(scene); i++)
                {
                    string matName = Assimp.aiMaterial_GetName(scene, i);
                    matName = nm + "_mat" + i;

                    //  string fname = Path.GetFileNameWithoutExtension(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse));
                    string fname = Path.GetFileName(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse));
                    Debug.Log("texture " + fname + "Material :" + matName);

                    Color ambient  = Assimp.aiMaterial_GetAmbient(scene, i);
                    Color diffuse  = Assimp.aiMaterial_GetDiffuse(scene, i);
                    Color specular = Assimp.aiMaterial_GetSpecular(scene, i);
                    Color emissive = Assimp.aiMaterial_GetEmissive(scene, i);

                    Material mat = new Material(Shader.Find("Diffuse"));
                    mat.name = matName;

                    string texturename = path + "/" + fname;

                    Texture2D tex = null;
                    if (File.Exists(texturename))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename, typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".PNG"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".PNG", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".JPG"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".JPG", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".BMP"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".BMP", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".TGA"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".TGA", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".DDS"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".DDS", typeof(Texture2D));
                    }

                    if (tex != null)
                    {
                        string p = AssetDatabase.GetAssetPath(tex);
                        ConfigureForAtlas(p);


                        Debug.Log("LOAD (" + texturename + ") texture");
                        mat.SetTexture("_MainTex", tex);
                    }
                    else
                    {
                        Debug.LogError("Fail LOAD (" + texturename + ") error");
                    }


                    materials.Add(mat);
                }

                AssetDatabase.Refresh();

                if (Assimp.aiScene_GetRootNode(scene) != null)
                {
                    ObjectRoot.transform.position = Assimp.aiNode_GetPosition(Assimp.aiScene_GetRootNode(scene));

                    //assimp quaternion is w,x,y,z and unity x,y,z,w bu int this lib i fix this for unity
                    Quaternion assQuad = Assimp.aiNode_GetRotation(Assimp.aiScene_GetRootNode(scene));
                    ObjectRoot.transform.rotation = assQuad;


                    GameObject skeleton = new GameObject("Skeleton");
                    skeleton.transform.parent = ObjectRoot.transform;
                    processNodes(scene, Assimp.aiScene_GetRootNode(scene), ref listJoints);

                    for (int i = 0; i < listJoints.Count; i++)
                    {
                        AssimpJoint joint = listJoints[i];
                        //Transform bone = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
                        Transform bone = new GameObject(joint.Name).transform;
                        //   DebugBone debug = (DebugBone)bone.gameObject.AddComponent(typeof(DebugBone));



                        bone.name   = joint.Name;
                        bone.parent = skeleton.transform;

                        if (getBoneByName(joint.parentName) != null)
                        {
                            int index = findBoneByName(joint.parentName);
                            bone.parent = joint.parent.transform;
                        }
                        bone.localPosition = joint.Position;
                        bone.localRotation = joint.Orientation;

                        joint.transform = bone;
                    }
                }



                if (Assimp.aiScene_HasMeshes(scene))
                {
                    for (int i = 0; i < Assimp.aiScene_GetNumMeshes(scene); i++)
                    {
                        string name = "Mesh_";
                        name += i.ToString();


                        bool HasNormals  = Assimp.aiMesh_HasNormals(scene, i);
                        bool HasTexCoord = Assimp.aiMesh_HasTextureCoords(scene, i, 0);
                        bool HasFaces    = Assimp.aiMesh_HasFaces(scene, i);


                        AssimpMesh mesh = new AssimpMesh(meshContainer, ObjectRoot, name);
                        mesh.setmaterial(materials[Assimp.aiMesh_GetMaterialIndex(scene, i)]);
                        MeshList.Add(mesh);



                        for (int v = 0; v < Assimp.aiMesh_GetNumVertices(scene, i); v++)
                        {
                            Vector3 vertex = Assimp.aiMesh_Vertex(scene, i, v);
                            Vector3 n      = Assimp.aiMesh_Normal(scene, i, v);
                            float   x      = Assimp.aiMesh_TextureCoordX(scene, i, v, 0);
                            float   y      = Assimp.aiMesh_TextureCoordY(scene, i, v, 0);

                            Vector3 binormalf = Assimp.aiMesh_Bitangent(scene, i, v);
                            Vector3 tangentf  = Assimp.aiMesh_Tangent(scene, i, v);

                            Vector4 outputTangent = new Vector4(tangentf.x, tangentf.y, tangentf.z, 0.0F);

                            float dp = Vector3.Dot(Vector3.Cross(n, tangentf), binormalf);
                            if (dp > 0.0F)
                            {
                                outputTangent.w = 1.0F;
                            }
                            else
                            {
                                outputTangent.w = -1.0F;
                            }


                            mesh.addVertex(vertex, n, outputTangent, new Vector2(x, y));
                        }

                        for (int f = 0; f < Assimp.aiMesh_GetNumFaces(scene, i); f++)
                        {
                            int a = Assimp.aiMesh_Indice(scene, i, f, 0);
                            int b = Assimp.aiMesh_Indice(scene, i, f, 1);
                            int c = Assimp.aiMesh_Indice(scene, i, f, 2);
                            mesh.addFace(a, b, c);
                        }



                        //****
                        int numBone = Assimp.aiMesh_GetNumBones(scene, i);


                        for (int b = 0; b < numBone; b++)
                        {
                            string      bname  = Assimp.aiMesh_GetBoneName(scene, i, b);
                            AssimpJoint joint  = getBoneByName(bname);
                            int         boneID = findBoneByName(bname);


                            int numWeights = Assimp.aiMesh_GetNumBoneWeights(scene, i, b);
                            for (int w = 0; w < numWeights; w++)
                            {
                                float Weight   = Assimp.aiMesh_GetBoneWeight(scene, i, b, w);
                                int   VertexId = Assimp.aiMesh_GetBoneVertexId(scene, i, b, w);
                                mesh.addBone(VertexId, boneID, Weight);
                            }
                        }

                        for (int j = 0; j < listJoints.Count; j++)
                        {
                            AssimpJoint joint = listJoints[j];
                            mesh.addJoint(joint);
                        }

                        //**********


                        mesh.BuilSkin();
                        mesh.build();
                        mesh.dispose();
                    }
                }

                Mesh m = CombineInstance(ObjectRoot, meshContainer, importingAssetsDir);



                //create key frames
                if (Assimp.aiScene_HasAnimation(scene))
                {
                    Animation anim = (UnityEngine.Animation)ObjectRoot.AddComponent(typeof(Animation));

                    int numAnimation = Assimp.aiScene_GetNumAnimations(scene);

                    Debug.Log("count animation  :" + numAnimation);


                    for (int a = 0; a < numAnimation; a++)
                    {
                        AnimationClip clip  = new AnimationClip();
                        string        anima = Assimp.aiAnim_GetName(scene, a);
                        clip.name   = nm + "_" + anima + "_" + a;
                        clip.legacy = true;

                        clip.wrapMode = WrapMode.Loop;

                        float tinks = (float)Assimp.aiAnim_GetTicksPerSecond(scene, a);
                        if (tinks <= 1f)
                        {
                            tinks = 1f;
                        }
                        float fps = tinks;
                        clip.frameRate = tinks;


                        Debug.Log("animation fps :" + fps);



                        int numchannels = Assimp.aiAnim_GetNumChannels(scene, a);
                        for (int i = 0; i < numchannels; i++)
                        {
                            string      name  = Assimp.aiAnim_GetChannelName(scene, a, i);
                            AssimpJoint joint = getBoneByName(name);



                            //  Debug.Log(String.Format("anim channel {0} bone name {1}  poskeys {2}  rotkeys{2}", i, name, Assimp.aiAnim_GetNumPositionKeys(scene, 0, i), Assimp.aiAnim_GetNumRotationKeys(scene, 0, i)));

                            //public static bool ignoreRotations = true;
                            // public static bool ignorePositions = true;
                            // public static bool ignoreScalling = true;

                            if (!ignoreScalling)
                            {
                                if (Assimp.aiAnim_GetNumScalingKeys(scene, a, i) != 0)
                                {
                                    AnimationCurve scaleXcurve = new AnimationCurve();
                                    AnimationCurve scaleYcurve = new AnimationCurve();
                                    AnimationCurve scaleZcurve = new AnimationCurve();

                                    for (int j = 0; j < Assimp.aiAnim_GetNumScalingKeys(scene, a, i); j++)
                                    {
                                        float   time  = (float)Assimp.aiAnim_GetScalingFrame(scene, a, i, j);/// fps;
                                        Vector3 scale = Assimp.aiAnim_GetScalingKey(scene, a, i, j);
                                        //    time = (float)j;
                                        scaleXcurve.AddKey(time, scale.x);
                                        scaleYcurve.AddKey(time, scale.y);
                                        scaleZcurve.AddKey(time, scale.z);
                                    }
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.x", scaleXcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.y", scaleYcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.z", scaleZcurve);
                                }
                            }

                            if (!ignorePositions)
                            {
                                if (Assimp.aiAnim_GetNumPositionKeys(scene, a, i) != 0)
                                {
                                    AnimationCurve posXcurve = new AnimationCurve();
                                    AnimationCurve posYcurve = new AnimationCurve();
                                    AnimationCurve posZcurve = new AnimationCurve();


                                    for (int j = 0; j < Assimp.aiAnim_GetNumPositionKeys(scene, a, i); j++)
                                    {
                                        float   time = (float)Assimp.aiAnim_GetPositionFrame(scene, a, i, j);// / fps;
                                        Vector3 pos  = Assimp.aiAnim_GetPositionKey(scene, a, i, j);
                                        //    time = (float)j;
                                        posXcurve.AddKey(time, pos.x);
                                        posYcurve.AddKey(time, pos.y);
                                        posZcurve.AddKey(time, pos.z);
                                    }

                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.x", posXcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.y", posYcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.z", posZcurve);
                                }
                            }

                            if (!ignoreRotations)
                            {
                                if (Assimp.aiAnim_GetNumRotationKeys(scene, a, i) != 0)
                                {
                                    AnimationCurve rotXcurve = new AnimationCurve();
                                    AnimationCurve rotYcurve = new AnimationCurve();
                                    AnimationCurve rotZcurve = new AnimationCurve();
                                    AnimationCurve rotWcurve = new AnimationCurve();

                                    for (int j = 0; j < Assimp.aiAnim_GetNumRotationKeys(scene, a, i); j++)
                                    {
                                        float time = (float)Assimp.aiAnim_GetRotationFrame(scene, a, i, j);// / fps;

                                        Quaternion rotation = Assimp.aiAnim_GetRotationKey(scene, a, i, j);
                                        //    time = (float)j;
                                        rotXcurve.AddKey(time, rotation.x);
                                        rotYcurve.AddKey(time, rotation.y);
                                        rotZcurve.AddKey(time, rotation.z);
                                        rotWcurve.AddKey(time, rotation.w);
                                    }

                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.x", rotXcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.y", rotYcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.z", rotZcurve);
                                    clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.w", rotWcurve);
                                }
                            }
                        }



                        clip.EnsureQuaternionContinuity();
                        anim.AddClip(clip, clip.name);
                        anim.clip = clip;

                        string clipAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + clip.name + ".asset");
                        AssetDatabase.CreateAsset(clip, clipAssetPath);
                    }
                }


                if (saveAssets)
                {
                    string prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + filename + ".prefab");
                    var    prefab     = PrefabUtility.CreateEmptyPrefab(prefabPath);
                    PrefabUtility.ReplacePrefab(ObjectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
                    AssetDatabase.Refresh();
                }

                MeshList.Clear();
            }

            listJoints.Clear();

            Assimp.aiReleaseImport(scene);
            Debug.LogWarning(path + "/" + filename + " Imported ;) ");
        }
    }
    private static void readMesh(string path, string filename, string texturepath)
    {
        string importingAssetsDir;

        if (File.Exists(path + "/" + filename))
        {
            Assimp.PostProcessSteps flags = (

                Assimp.PostProcessSteps.RemoveComponent);

            IntPtr config = Assimp.aiCreatePropertyStore();

            Assimp.aiSetImportPropertyFloat(config, Assimp.AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, 60.0f);
            Assimp.aiSetImportPropertyInteger(config, Assimp.AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
            // IntPtr scene = Assimp.aiImportFile(path + "/" + filename, (uint)flags);
            IntPtr scene = Assimp.aiImportFileWithProperties(path + "/" + filename, (uint)flags, config);
            Assimp.aiReleasePropertyStore(config);
            if (scene == null)
            {
                Debug.LogWarning("failed to read file: " + path + "/" + filename);
                return;
            }
            else
            {
                string nm = Path.GetFileNameWithoutExtension(filename);


                importingAssetsDir = "Assets/Prefabs/" + nm + "/";

                if (saveAssets)
                {
                    if (!Directory.Exists(importingAssetsDir))
                    {
                        Directory.CreateDirectory(importingAssetsDir);
                    }
                    AssetDatabase.Refresh();
                }


                GameObject ObjectRoot = new GameObject(nm);

                AssetDatabase.Refresh();

                if (Assimp.aiScene_GetRootNode(scene) != null)
                {
                    ObjectRoot.transform.position = Assimp.aiNode_GetPosition(Assimp.aiScene_GetRootNode(scene));

                    //assimp quaternion is w,x,y,z and unity x,y,z,w bu int this lib i fix this for unity
                    Quaternion assQuad = Assimp.aiNode_GetRotation(Assimp.aiScene_GetRootNode(scene));
                    ObjectRoot.transform.rotation = assQuad;


                    GameObject skeleton = new GameObject("Skeleton");
                    skeleton.transform.parent = ObjectRoot.transform;
                    processNodes(scene, Assimp.aiScene_GetRootNode(scene), ref listJoints);

                    for (int i = 0; i < listJoints.Count; i++)
                    {
                        AssimpJoint joint = listJoints[i];
                        Transform   bone  = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
                        //  Transform bone = new GameObject(joint.Name).transform;
                        //   DebugBone debug = (DebugBone)bone.gameObject.AddComponent(typeof(DebugBone));



                        bone.name   = joint.Name;
                        bone.parent = skeleton.transform;

                        if (getBoneByName(joint.parentName) != null)
                        {
                            int index = findBoneByName(joint.parentName);
                            bone.parent = joint.parent.transform;
                        }
                        bone.localPosition = joint.Position;
                        bone.localRotation = joint.Orientation;

                        joint.transform = bone;
                    }
                }



                //create key frames
                if (Assimp.aiScene_HasAnimation(scene))
                {
                    Animation anim = (UnityEngine.Animation)ObjectRoot.AddComponent(typeof(Animation));

                    int numAnimation = Assimp.aiScene_GetNumAnimations(scene);

                    for (int a = 0; a < numAnimation; a++)
                    {
                        AnimationClip clip  = new AnimationClip();
                        string        anima = Assimp.aiAnim_GetName(scene, a);
                        clip.name = nm + "_" + anima + "_" + a;


                        clip.wrapMode = WrapMode.Loop;

                        float tinks = (float)Assimp.aiAnim_GetTicksPerSecond(scene, a);
                        if (tinks <= 1f)
                        {
                            tinks = 1f;
                        }
                        float fps = tinks;
                        clip.frameRate = tinks;


                        Debug.Log("animation fps :" + fps);



                        int numchannels = Assimp.aiAnim_GetNumChannels(scene, a);
                        for (int i = 0; i < numchannels; i++)
                        {
                            string      name  = Assimp.aiAnim_GetChannelName(scene, a, i);
                            AssimpJoint joint = getBoneByName(name);



                            //  Debug.Log(String.Format("anim channel {0} bone name {1}  poskeys {2}  rotkeys{2}", i, name, Assimp.aiAnim_GetNumPositionKeys(scene, 0, i), Assimp.aiAnim_GetNumRotationKeys(scene, 0, i)));



                            if (Assimp.aiAnim_GetNumScalingKeys(scene, a, i) != 0)
                            {
                                AnimationCurve scaleXcurve = new AnimationCurve();
                                AnimationCurve scaleYcurve = new AnimationCurve();
                                AnimationCurve scaleZcurve = new AnimationCurve();

                                for (int j = 0; j < Assimp.aiAnim_GetNumScalingKeys(scene, a, i); j++)
                                {
                                    float   time  = (float)Assimp.aiAnim_GetScalingFrame(scene, a, i, j);// *fps;
                                    Vector3 scale = Assimp.aiAnim_GetScalingKey(scene, a, i, j);
                                    //time = (float)j;
                                    scaleXcurve.AddKey(time, scale.x);
                                    scaleYcurve.AddKey(time, scale.y);
                                    scaleZcurve.AddKey(time, scale.z);
                                }
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.x", scaleXcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.y", scaleYcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "m_LocalScale.z", scaleZcurve);
                            }


                            if (Assimp.aiAnim_GetNumPositionKeys(scene, a, i) != 0)
                            {
                                AnimationCurve posXcurve = new AnimationCurve();
                                AnimationCurve posYcurve = new AnimationCurve();
                                AnimationCurve posZcurve = new AnimationCurve();


                                for (int j = 0; j < Assimp.aiAnim_GetNumPositionKeys(scene, a, i); j++)
                                {
                                    float   time = (float)Assimp.aiAnim_GetPositionFrame(scene, a, i, j);// *fps;
                                    Vector3 pos  = Assimp.aiAnim_GetPositionKey(scene, a, i, j);
                                    //  time = (float)j;
                                    posXcurve.AddKey(time, pos.x);
                                    posYcurve.AddKey(time, pos.y);
                                    posZcurve.AddKey(time, pos.z);
                                }

                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.x", posXcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.y", posYcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localPosition.z", posZcurve);
                            }
                            if (Assimp.aiAnim_GetNumRotationKeys(scene, a, i) != 0)
                            {
                                AnimationCurve rotXcurve = new AnimationCurve();
                                AnimationCurve rotYcurve = new AnimationCurve();
                                AnimationCurve rotZcurve = new AnimationCurve();
                                AnimationCurve rotWcurve = new AnimationCurve();

                                for (int j = 0; j < Assimp.aiAnim_GetNumRotationKeys(scene, a, i); j++)
                                {
                                    float time = (float)Assimp.aiAnim_GetRotationFrame(scene, a, i, j);// *fps;

                                    Quaternion rotation = Assimp.aiAnim_GetRotationKey(scene, a, i, j);
                                    //    time = (float)j;
                                    rotXcurve.AddKey(time, rotation.x);
                                    rotYcurve.AddKey(time, rotation.y);
                                    rotZcurve.AddKey(time, rotation.z);
                                    rotWcurve.AddKey(time, rotation.w);
                                }

                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.x", rotXcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.y", rotYcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.z", rotZcurve);
                                clip.SetCurve("Skeleton/" + joint.Path, typeof(Transform), "localRotation.w", rotWcurve);
                            }
                        }



                        clip.EnsureQuaternionContinuity();
                        anim.AddClip(clip, clip.name);
                        anim.clip = clip;


                        string clipAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + clip.name + ".asset");
                        AssetDatabase.CreateAsset(clip, clipAssetPath);

                        //  AssetDatabase.CreateAsset(clip, "Assets/Models/" + nm +"_"+a+ ".anim");
                        //  AssetDatabase.SaveAssets();
                    }
                }


                if (saveAssets)
                {
                    string prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + filename + ".prefab");
                    var    prefab     = PrefabUtility.CreateEmptyPrefab(prefabPath);
                    PrefabUtility.ReplacePrefab(ObjectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
                    AssetDatabase.Refresh();
                }
            }

            listJoints.Clear();

            Assimp.aiReleaseImport(scene);
            Debug.LogWarning(path + "/" + filename + " Imported ;) ");
        }
    }
Beispiel #20
0
 void TestTexture(Assimp.EmbeddedTexture netTexture, AssimpSharp.Texture sharpTexture)
 {
     throw (new NotImplementedException());
 }
        public EmbeddedTextureLoader(Assimp.EmbeddedTexture tex) 
        {
            if(tex.IsCompressed)
            {
                var compTex = tex;
                if(!compTex.HasCompressedData)
                {
                    return;
                }

                // note: have to keep the stream open for the lifetime of the image, so don't Dispose()
                SetFromStream(new MemoryStream(compTex.CompressedData));
                return;
            }

            var rawTex = tex;
            if (!rawTex.HasNonCompressedData || rawTex.Width < 1 || rawTex.Height < 1)
            {
                return;
            }
            var texels = rawTex.NonCompressedData;

            
            var image = new Bitmap(rawTex.Width, rawTex.Height, PixelFormat.Format32bppArgb);

            var bounds = new Rectangle(0, 0, rawTex.Width, rawTex.Height);
            BitmapData bmpData;

            try
            {
                bmpData = image.LockBits(bounds, ImageLockMode.WriteOnly, image.PixelFormat);
                // ignore exceptions thrown by LockBits - we just can't read the image in this case
            }
            catch
            {
                return;
            }

            var ptr = bmpData.Scan0;

            Debug.Assert(bmpData.Stride > 0);

            var countBytes = bmpData.Stride*image.Height;
            var tempBuffer = new byte[countBytes];

            var dataLineLength = image.Width*4;
            var padding = bmpData.Stride - dataLineLength;
            Debug.Assert(padding >= 0);

            var n = 0;
            foreach(var texel in texels)
            {
                tempBuffer[n++] = texel.B;
                tempBuffer[n++] = texel.G;
                tempBuffer[n++] = texel.R;
                tempBuffer[n++] = texel.A;

                if(n % dataLineLength == 0)
                {
                    n += padding;
                }
            }

            Marshal.Copy(tempBuffer, 0, ptr, countBytes);
            image.UnlockBits(bmpData);

            _image = image;
            _result = LoadResult.Good;
        }
Beispiel #22
0
        private static OutlineItem CreateOutlineItem(Assimp.Scene scene)
        {
            var item = new OutlineItem
            {
                Text = "Assimp scene",
                Icon = MultiColorGlyphs.SceneNode,
                Children = new OutlineItemCollection(),
                ToolTip = ToolTipAssimpNode,
                UserData = scene,
                IsExpanded = false,
            };

            item.Children.Add(CreateOutlineItem(scene.RootNode));

            return item;
        }
Beispiel #23
0
        private static OutlineItem CreateOutlineItem(Assimp.Node node)
        {
            var item = new OutlineItem
            {
                Text = node.Name,
                Icon = node.HasMeshes ? MultiColorGlyphs.Mesh : MultiColorGlyphs.SceneNode,
                Children = new OutlineItemCollection(),
                ToolTip = ToolTipAssimpNode,
                UserData = node,
            };

            if (node.HasChildren)
                foreach (var child in node.Children)
                    item.Children.Add(CreateOutlineItem(child));

            return item;
        }
Beispiel #24
0
 private Material GenerateMaterialFromMesh(int materialIndex, Assimp.Scene assimpScene)
 {
     var assimpMaterial = assimpScene.Materials[materialIndex];
     var texture = string.IsNullOrEmpty(assimpMaterial.TextureDiffuse.FilePath) ? null : GetTexture2D(assimpMaterial.TextureDiffuse.FilePath);
     return new Material(texture);
 }
Beispiel #25
0
        /// <summary>
        /// Build a transformation matrix from rotation, scaling and translation components.
        /// The transformation order is scaling, rotation, translation (left to right).
        /// </summary>
        /// <param name="presentRotation"></param>
        /// <param name="presentScaling"></param>
        /// <param name="presentPosition"></param>
        /// <param name="outMatrix"></param>
        private static void BuildTransform(ref Assimp.Quaternion presentRotation, ref Vector3D presentScaling, 
            ref Vector3D presentPosition, out Matrix4 outMatrix)
        {
            // build a transformation matrix from it
            var mat = new Matrix4x4(presentRotation.GetMatrix());
            mat.A1 *= presentScaling.X;
            mat.B1 *= presentScaling.X;
            mat.C1 *= presentScaling.X;
            mat.A2 *= presentScaling.Y;
            mat.B2 *= presentScaling.Y;
            mat.C2 *= presentScaling.Y;
            mat.A3 *= presentScaling.Z;
            mat.B3 *= presentScaling.Z;
            mat.C3 *= presentScaling.Z;
            mat.A4 = presentPosition.X;
            mat.B4 = presentPosition.Y;
            mat.C4 = presentPosition.Z;

            outMatrix = AssimpToOpenTk.FromMatrix(ref mat);
        }
Beispiel #26
0
        //determine the number of elements in the vertex
        private int GetNoofInputElements(Assimp.Mesh mesh)
        {

            bool hasTexCoords = mesh.HasTextureCoords(0);
            bool hasColors = mesh.HasVertexColors(0);
            bool hasNormals = mesh.HasNormals;
            bool hasTangents = mesh.Tangents != null;
            bool hasBitangents = mesh.BiTangents != null;

            int noofElements = 1;

            if (hasColors)
                noofElements++;

            if (hasNormals)
                noofElements++;

            if (hasTangents)
                noofElements++;

            if (hasBitangents)
                noofElements++;

            if (hasTexCoords)
                noofElements++;

            return noofElements;
        }
 public static void Run(Assimp.Scene scene)
 {
 }
        /// <summary>
        /// Update a 3D Joint in the joint Collection
        /// </summary>
        /// <param name="nodeName">The joint Name</param>
        /// <param name="absoluteMatrix">Destintation Matrix of the specified node</param>
        private void SetJoint(string nodeName, Matrix3D absoluteMatrix, Assimp.Vector3D delta)
        {
            Joint myJoint = joints.FindJointByName(nodeName);
            if (myJoint == null)
            {
                myJoint = new Joint();
                myJoint.Name = nodeName;
                myJoint.Matrix.Add(absoluteMatrix);
                myJoint.Delta.Add(delta);

                joints.Add(myJoint);
            }
            else
            {
                myJoint.Matrix.Add(absoluteMatrix);
                myJoint.Delta.Add(delta);
            }
        }
Beispiel #29
0
 void TestAnimationChannel(Assimp. MeshAnimationChannel netChannel, AssimpSharp.MeshAnim sharpChannel)
 {
     Assert.AreEqual(netChannel.MeshName, sharpChannel.Name);
     Assert.AreEqual(netChannel.MeshKeyCount, sharpChannel.Keys.Length);
     for (int i = 0; i < netChannel.MeshKeyCount; i++)
     {
         Assert.AreEqual(netChannel.MeshKeys[i].Time, sharpChannel.Keys[i].Time);
         Assert.AreEqual(netChannel.MeshKeys[i].Value, sharpChannel.Keys[i].Value);
     }
 }
        private void RecursiveRender(Assimp.Scene scene, Node node, ref OpenGL gl)
        {
            Matrix4 m = FromMatrix(node.Transform);
            m.Transpose();
            gl.PushMatrix();
            gl.MultMatrix(FloatFromMatrix(m));

            if (node.HasMeshes)
            {
                foreach (int index in node.MeshIndices)
                {
                    Mesh mesh = scene.Meshes[index];
                    ApplyMaterial(m_model.Materials[mesh.MaterialIndex], ref gl);

                    if (mesh.HasNormals)
                    {

                        gl.Enable(OpenGL.GL_LIGHTING);
                    }
                    else
                    {
                        gl.Disable(OpenGL.GL_LIGHTING);
                    }

                    bool hasColors = mesh.HasVertexColors(0);
                    if (hasColors)
                    {
                        gl.Enable(OpenGL.GL_COLOR_MATERIAL);
                    }
                    else
                    {
                        gl.Disable(OpenGL.GL_COLOR_MATERIAL);
                    }

                    bool hasTexCoords = mesh.HasTextureCoords(0);

                    foreach (Assimp.Face face in mesh.Faces)
                    {
                        BeginMode faceMode;
                        switch (face.IndexCount)
                        {
                            case 1:
                                faceMode = BeginMode.Points;
                                break;
                            case 2:
                                faceMode = BeginMode.Lines;
                                break;
                            case 3:
                                faceMode = BeginMode.Triangles;
                                break;
                            default:
                                faceMode = BeginMode.Polygon;
                                break;
                        }

                        gl.Begin(faceMode);
                        for (int i = 0; i < face.IndexCount; i++)
                        {
                            int indice = face.Indices[i];
                            if (hasColors)
                            {
                                Color4 vertColor = FromColor(mesh.VertexColorChannels[0][indice]);
                                if (mesh.HasNormals)
                                {
                                    Vector3 normal = FromVector(mesh.Normals[indice]);
                                    gl.Normal(normal.X, normal.Y, normal.Z);
                                }
                                if (hasTexCoords)
                                {
                                    Vector3 uvw = FromVector(mesh.TextureCoordinateChannels[0][indice]);
                                    gl.TexCoord(uvw.X, 1 - uvw.Y);
                                }
                                Vector3 pos = FromVector(mesh.Vertices[indice]);
                                gl.Vertex(pos.X, pos.Y, pos.Z);
                            }
                            gl.End();
                        }
                    }
                }

                for (int i = 0; i < node.ChildCount; i++)
                {
                    RecursiveRender(m_model, node.Children[i], ref gl);
                }
            }
        }
Beispiel #31
0
        void TestMesh(Assimp.Mesh netMesh, AssimpSharp.Mesh sharpMesh)
        {
            // Vertices
            Assert.AreEqual(netMesh.HasVertices, sharpMesh.Vertices != null);
            if (netMesh.HasVertices)
            {
                Assert.AreEqual(netMesh.VertexCount, sharpMesh.Vertices.Length);
                MathAssert.AreEqual(netMesh.Vertices, sharpMesh.Vertices);
            }
            // Faces
            Assert.AreEqual(netMesh.HasFaces, sharpMesh.Faces != null);
            if (netMesh.HasFaces)
            {
                Assert.AreEqual(netMesh.FaceCount, sharpMesh.Faces.Length);
                for (int i = 0; i < netMesh.FaceCount; i++)
                {
                    Assert.AreEqual(netMesh.Faces[i].HasIndices, sharpMesh.Faces[i].Indices != null);
                    Assert.AreEqual(netMesh.Faces[i].IndexCount, sharpMesh.Faces[i].Indices.Length);
                    Assert.AreEqual(netMesh.Faces[i].Indices, sharpMesh.Faces[i].Indices);
                }
            }
            // Normals
            Assert.AreEqual(netMesh.HasNormals, sharpMesh.Normals != null);
            if (netMesh.HasNormals)
            {
                MathAssert.AreEqual(netMesh.Normals, sharpMesh.Normals);
            }

            // BiTangents
            Assert.AreEqual(netMesh.HasTangentBasis, sharpMesh.Bitangents != null && sharpMesh.Bitangents.Length > 0);
            if (netMesh.HasTangentBasis)
            {
                MathAssert.AreEqual(netMesh.BiTangents, sharpMesh.Bitangents);
            }
            // PrimitiveType
            // AssimpNet BUG!!
            //Assert.AreEqual(netMesh.PrimitiveType.ToString(), Enum.GetName(typeof(AssimpSharp.PrimitiveType), sharpMesh.PrimitiveTypes));
            // TexureCoord
            for (int i = 0; i < netMesh.TextureCoordinateChannelCount; i++)
            {
                Assert.AreEqual(netMesh.HasTextureCoords(i), sharpMesh.HasTextureCoords(i));
                MathAssert.AreEqual(netMesh.TextureCoordinateChannels[i], sharpMesh.TextureCoords[i]);
            }
            // VertexColorChannels
            for (int i = 0; i < netMesh.VertexColorChannelCount; i++)
            {
                Assert.AreEqual(netMesh.HasVertexColors(i), sharpMesh.HasVertexColors(i));
                if (netMesh.HasVertexColors(i))
                {
                    Assert.AreEqual(netMesh.VertexColorChannels[i], sharpMesh.Colors[i]);
                }
            }
            // MaterialIndex
            Assert.AreEqual(netMesh.MaterialIndex, sharpMesh.MaterialIndex);
            // Name
            Assert.AreEqual(netMesh.Name, sharpMesh.Name);
            // UVComponentCount
            Assert.AreEqual(netMesh.UVComponentCount, sharpMesh.NumUVComponents);
            // MeshAnimationAttachments
            Assert.AreEqual(netMesh.HasMeshAnimationAttachments, sharpMesh.AnimMeshes != null);
            if (netMesh.HasMeshAnimationAttachments)
            {
                for (int i = 0; i < netMesh.MeshAnimationAttachmentCount; i++)
                {
                    TestAnimationAttachment(netMesh.MeshAnimationAttachments[i], sharpMesh.AnimMeshes[i]);
                }
            }
        }
 public void SetTexture(string rootPath, Assimp.Material meterial)
 {
     SetTexture(rootPath, meterial.TextureDiffuse.FilePath, TextureType.Diffuse);
     SetTexture(rootPath, meterial.TextureNormal.FilePath, TextureType.Normal);
     SetTexture(rootPath, meterial.TextureDiffuse.FilePath, TextureType.Gamma);
     SetTexture(rootPath, meterial.TextureDiffuse.FilePath, TextureType.Shadow);
     SetTexture(rootPath, meterial.TextureDiffuse.FilePath, TextureType.Bump);
 }
Beispiel #33
0
        /// <summary>
        /// Add a texture to the TextureSet. This is the only place where
        /// Texture instances are actually created. The actual image for textures
        /// added to the set is loaded using a background thread.
        /// </summary>
        /// <param name="path">Texture's given path or, in case an embedded data source
        ///    is specified for the texture, an arbitrary but unique value to identify 
        ///    the texture (preferably not a file path)
        /// </param>
        /// <param name="embeddedDataSource">Optional parameter that specifies
        ///    an in-memory, embedded data source for the texture. </param>
        public void Add(string path, Assimp.EmbeddedTexture embeddedDataSource = null)
        {
            if(_dict.ContainsKey(path))
            {
                return;
            }
            Texture.CompletionCallback closure = self =>
                {               
                    lock(_loaded)
                    {
                        if (_disposed)
                        {
                            return;
                        }

                        Debug.Assert(_dict.ContainsKey(path));
                        _loaded.Add(path);

                        // If this texture is being used as replacement for another texture,
                        // we need to invoke callbacks for its ID too
                        // TODO obviously, all the replacement code needs a re-design.
                        foreach (var kv in _replacements)
                        {
                            if (kv.Value.Value == path)
                            {
                                for (int i = 0, e = _textureCallbacks.Count; i < e; )
                                {
                                    var callback = _textureCallbacks[i];
                                    if (!callback(kv.Value.Key, self))
                                    {
                                        _textureCallbacks.RemoveAt(i);
                                        --e;
                                        continue;
                                    }
                                    ++i;
                                }
                            }
                        }
                        for (int i = 0, e = _textureCallbacks.Count; i < e; )
                        {
                            var callback = _textureCallbacks[i];
                            if (!callback(path, self))
                            {
                                _textureCallbacks.RemoveAt(i);
                                --e;
                                continue;
                            }
                            ++i;
                        }
                    }               
                };
 
            _dict.Add(path, embeddedDataSource == null 
                ? new Texture(path, _baseDir, closure) 
                : new Texture(embeddedDataSource, path, closure));
        }
Beispiel #34
0
    public static void readMesh(string path, string filename, string texturepath)
    {
        string importingAssetsDir;

        if (File.Exists(path + "/" + filename))
        {
            Assimp.PostProcessSteps flags = (
                //        Assimp.PostProcessSteps.MakeLeftHanded |

                Assimp.PostProcessSteps.OptimizeMeshes |
                Assimp.PostProcessSteps.OptimizeGraph |
                Assimp.PostProcessSteps.RemoveRedundantMaterials |
                Assimp.PostProcessSteps.SortByPrimitiveType |
                Assimp.PostProcessSteps.SplitLargeMeshes |
                Assimp.PostProcessSteps.Triangulate |
                Assimp.PostProcessSteps.CalculateTangentSpace |
                Assimp.PostProcessSteps.GenerateUVCoords |
                Assimp.PostProcessSteps.GenerateSmoothNormals |
                Assimp.PostProcessSteps.RemoveComponent |
                Assimp.PostProcessSteps.JoinIdenticalVertices);

            IntPtr config = Assimp.aiCreatePropertyStore();

            Assimp.aiSetImportPropertyFloat(config, Assimp.AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, 60.0f);

            // IntPtr scene = Assimp.aiImportFile(path + "/" + filename, (uint)flags);
            IntPtr scene = Assimp.aiImportFileWithProperties(path + "/" + filename, (uint)flags, config);
            Assimp.aiReleasePropertyStore(config);
            if (scene == null)
            {
                Debug.LogWarning("failed to read file: " + path + "/" + filename);
                return;
            }
            else
            {
                string nm = Path.GetFileNameWithoutExtension(filename);


                importingAssetsDir = "Assets/Prefabs/" + nm + "/";

                if (saveAssets)
                {
                    if (!Directory.Exists(importingAssetsDir))
                    {
                        Directory.CreateDirectory(importingAssetsDir);
                    }
                    AssetDatabase.Refresh();
                }


                GameObject ObjectRoot    = new GameObject(nm);
                GameObject meshContainer = new GameObject(nm + "_Mesh");
                meshContainer.transform.parent = ObjectRoot.transform;


                List <Material>   materials = new List <Material>();
                List <AssimpMesh> MeshList  = new List <AssimpMesh>();


                for (int i = 0; i < Assimp.aiScene_GetNumMaterials(scene); i++)
                {
                    string matName = Assimp.aiMaterial_GetName(scene, i);
                    matName = nm + "_mat" + i;

                    //  string fname = Path.GetFileNameWithoutExtension(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse));
                    string fname = Path.GetFileName(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse));
                    Debug.Log("texture " + fname + "Material :" + matName);

                    Color ambient  = Assimp.aiMaterial_GetAmbient(scene, i);
                    Color diffuse  = Assimp.aiMaterial_GetDiffuse(scene, i);
                    Color specular = Assimp.aiMaterial_GetSpecular(scene, i);
                    Color emissive = Assimp.aiMaterial_GetEmissive(scene, i);

                    Material mat = new Material(Shader.Find("Diffuse"));
                    mat.name = matName;

                    string texturename = path + "/" + fname;

                    Texture2D tex = null;
                    if (File.Exists(texturename))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename, typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".PNG"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".PNG", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".JPG"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".JPG", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".BMP"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".BMP", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".TGA"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".TGA", typeof(Texture2D));
                    }
                    else
                    if (File.Exists(texturename + ".DDS"))
                    {
                        tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename + ".DDS", typeof(Texture2D));
                    }



                    //Texture2D tex = Resources.Load(texturename) as Texture2D;

                    //  Texture2D tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename, typeof(Texture2D));


                    if (tex != null)
                    {
                        Debug.Log("LOAD (" + texturename + ") texture");
                        mat.SetTexture("_MainTex", tex);
                    }
                    else
                    {
                        Debug.LogError("Fail LOAD (" + texturename + ") error");
                    }


                    if (saveAssets)
                    {
                        string materialAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + mat.name + ".asset");
                        AssetDatabase.CreateAsset(mat, materialAssetPath);
                    }
                    materials.Add(mat);
                }

                AssetDatabase.Refresh();



                if (Assimp.aiScene_HasMeshes(scene))
                {
                    for (int i = 0; i < Assimp.aiScene_GetNumMeshes(scene); i++)
                    {
                        string name = "Mesh_";
                        name += i.ToString();


                        bool HasNormals  = Assimp.aiMesh_HasNormals(scene, i);
                        bool HasTexCoord = Assimp.aiMesh_HasTextureCoords(scene, i, 0);
                        bool HasFaces    = Assimp.aiMesh_HasFaces(scene, i);


                        AssimpMesh mesh = new AssimpMesh(meshContainer, ObjectRoot, name);
                        mesh.setmaterial(materials[Assimp.aiMesh_GetMaterialIndex(scene, i)]);
                        MeshList.Add(mesh);



                        for (int v = 0; v < Assimp.aiMesh_GetNumVertices(scene, i); v++)
                        {
                            Vector3 vertex = Assimp.aiMesh_Vertex(scene, i, v);
                            Vector3 n      = Assimp.aiMesh_Normal(scene, i, v);
                            float   x      = Assimp.aiMesh_TextureCoordX(scene, i, v, 0);
                            float   y      = Assimp.aiMesh_TextureCoordY(scene, i, v, 0);


                            Vector3 binormalf = Assimp.aiMesh_Bitangent(scene, i, v);
                            Vector3 tangentf  = Assimp.aiMesh_Tangent(scene, i, v);

                            Vector4 outputTangent = new Vector4(tangentf.x, tangentf.y, tangentf.z, 0.0F);

                            float dp = Vector3.Dot(Vector3.Cross(n, tangentf), binormalf);
                            if (dp > 0.0F)
                            {
                                outputTangent.w = 1.0F;
                            }
                            else
                            {
                                outputTangent.w = -1.0F;
                            }



                            mesh.addVertex(vertex, n, new Vector2(x, y), outputTangent);


                            //mesh.addVertex(vertex, new Vector3(1 * -n.x, n.y, n.z), new Vector2(x, y), outputTangent);
                        }

                        for (int f = 0; f < Assimp.aiMesh_GetNumFaces(scene, i); f++)
                        {
                            int a = Assimp.aiMesh_Indice(scene, i, f, 0);
                            int b = Assimp.aiMesh_Indice(scene, i, f, 1);
                            int c = Assimp.aiMesh_Indice(scene, i, f, 2);
                            mesh.addFace(a, b, c);
                        }



                        //**********



                        mesh.build();


                        if (saveAssets)
                        {
                            string meshAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + mesh.name + ".asset");
                            AssetDatabase.CreateAsset(mesh.geometry, meshAssetPath);
                        }

                        mesh.dispose();
                    }
                }



                if (saveAssets)
                {
                    string prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + filename + ".prefab");
                    var    prefab     = PrefabUtility.CreateEmptyPrefab(prefabPath);
                    PrefabUtility.ReplacePrefab(ObjectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
                    AssetDatabase.Refresh();
                }

                MeshList.Clear();
            }



            Assimp.aiReleaseImport(scene);
            Debug.LogWarning(path + "/" + filename + " Imported ;) ");
        }
    }