/// <summary>
        /// Finds all edges in the mesh (each edge is only included once).
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <returns>
        /// The edge indices (minimum index first).
        /// </returns>
        public static Int32Collection FindEdges(this MeshGeometry3D mesh)
        {
            var edges = new Int32Collection();
            var dict  = new HashSet <ulong>();

            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0 = i * 3;
                for (var j = 0; j < 3; j++)
                {
                    var index0   = mesh.TriangleIndices[i0 + j];
                    var index1   = mesh.TriangleIndices[i0 + ((j + 1) % 3)];
                    var minIndex = Math.Min(index0, index1);
                    var maxIndex = Math.Max(index1, index0);
                    var key      = CreateKey((uint)minIndex, (uint)maxIndex);
                    if (!dict.Contains(key))
                    {
                        edges.Add(minIndex);
                        edges.Add(maxIndex);
                        dict.Add(key);
                    }
                }
            }

            return(edges);
        }
        /// <summary>
        /// Creates a new mesh where no vertices are shared.
        /// </summary>
        /// <param name="input">
        /// The input mesh.
        /// </param>
        /// <returns>
        /// A new mesh.
        /// </returns>
        public static MeshGeometry3D NoSharedVertices(this MeshGeometry3D input)
        {
            var p  = new Point3DCollection();
            var ti = new Int32Collection();
            Vector3DCollection n = null;

            if (input.Normals != null)
            {
                n = new Vector3DCollection();
            }

            PointCollection tc = null;

            if (input.TextureCoordinates != null)
            {
                tc = new PointCollection();
            }

            for (var i = 0; i < input.TriangleIndices.Count; i += 3)
            {
                var i0     = i;
                var i1     = i + 1;
                var i2     = i + 2;
                var index0 = input.TriangleIndices[i0];
                var index1 = input.TriangleIndices[i1];
                var index2 = input.TriangleIndices[i2];
                var p0     = input.Positions[index0];
                var p1     = input.Positions[index1];
                var p2     = input.Positions[index2];
                p.Add(p0);
                p.Add(p1);
                p.Add(p2);
                ti.Add(i0);
                ti.Add(i1);
                ti.Add(i2);
                if (n != null && input.Normals.Count > 0)
                {
                    n.Add(input.Normals[index0]);
                    n.Add(input.Normals[index1]);
                    n.Add(input.Normals[index2]);
                }

                if (tc != null)
                {
                    tc.Add(input.TextureCoordinates[index0]);
                    tc.Add(input.TextureCoordinates[index1]);
                    tc.Add(input.TextureCoordinates[index2]);
                }
            }

#if SHARPDX
            return(new MeshGeometry3D {
                Positions = p, TriangleIndices = new IntCollection(ti), Normals = n, TextureCoordinates = tc
            });
#else
            return(new MeshGeometry3D {
                Positions = p, TriangleIndices = ti, Normals = n, TextureCoordinates = tc
            });
#endif
        }
Example #3
0
        public MeshBinder(Autodesk.Dynamo.MeshToolkit.Mesh mesh, Color color)
        {
            dynamoMesh        = false;
            StartingPositions = mesh.Vertices().ToTriples().ToArray();
            Color             = color;

            faceIndices = mesh.VertexIndicesByTri();
            int faceCount = faceIndices.Count / 3;

            faces = new IndexGroup[faceCount];

            for (int i = 0; i < faceCount; i++)
            {
                faces[i] = IndexGroup.ByIndices(
                    (uint)faceIndices[i * 3],
                    (uint)faceIndices[i * 3 + 1],
                    (uint)faceIndices[i * 3 + 2]);
            }

            meshIndices = new IntCollection();

            foreach (IndexGroup face in faces)
            {
                meshIndices.Add((int)face.A);
                meshIndices.Add((int)face.B);
                meshIndices.Add((int)face.C);
            }
        }
Example #4
0
        public TexturedMeshBinder(Autodesk.Dynamo.MeshToolkit.Mesh mesh, Color color, string textureFileName, Vector2Collection textureCoordinates)
        {
            StartingPositions = mesh.Vertices().ToTriples().ToArray();
            Color             = color;

            try { diffuseMap = new BitmapImage(new Uri(textureFileName)); }
            catch (FileNotFoundException) { throw new Exception("Could not locate the texture file"); }

            this.textureCoordinates = textureCoordinates;

            faceIndices = mesh.VertexIndicesByTri();
            int faceCount = faceIndices.Count / 3;

            faces = new IndexGroup[faceCount];

            for (int i = 0; i < faceCount; i++)
            {
                faces[i] = IndexGroup.ByIndices(
                    (uint)faceIndices[i * 3],
                    (uint)faceIndices[i * 3 + 1],
                    (uint)faceIndices[i * 3 + 2]);
            }

            meshFaceIndices = new IntCollection();

            foreach (IndexGroup face in faces)
            {
                meshFaceIndices.Add((int)face.A);
                meshFaceIndices.Add((int)face.B);
                meshFaceIndices.Add((int)face.C);
            }
        }
            public FileInfo(Archive owner, string name, int start, int parent) : base(owner, name, start, parent)
            {
                int i = start;

                do
                {
                    seq.Add(i);
                    owner.stream.Position = Archive.GetOffset(i);
                    lastct = owner.br.ReadUInt16();
                    i      = owner.br.ReadInt32();
                } while(i > 0);
            }
Example #6
0
        private static IntCollection ConvertFaceIndices(List <int> subFaces, List <int> faces)
        {
            var triangleIndices = new IntCollection(subFaces.Count * 3);// new List<int>(subFaces.Count * 3);

            foreach (int f in subFaces)
            {
                triangleIndices.Add(faces[f * 3]);
                triangleIndices.Add(faces[(f * 3) + 1]);
                triangleIndices.Add(faces[(f * 3) + 2]);
            }

            return(triangleIndices);
        }
        /// <summary>
        /// Finds all edges where the angle between adjacent triangle normal vectors.
        /// is larger than minimumAngle
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <param name="minimumAngle">
        /// The minimum angle between the normal vectors of two adjacent triangles (degrees).
        /// </param>
        /// <returns>
        /// The edge indices.
        /// </returns>
        public static Int32Collection FindSharpEdges(this MeshGeometry3D mesh, double minimumAngle)
        {
            var edgeIndices = new Int32Collection();
            var edgeNormals = new Dictionary <EdgeKey, Vector3D>();

            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0             = i * 3;
                var p0             = mesh.Positions[mesh.TriangleIndices[i0]];
                var p1             = mesh.Positions[mesh.TriangleIndices[i0 + 1]];
                var p2             = mesh.Positions[mesh.TriangleIndices[i0 + 2]];
                var triangleNormal = SharedFunctions.CrossProduct(p1 - p0, p2 - p0);

                // Handle degenerated triangles.
                if (SharedFunctions.LengthSquared(ref triangleNormal) < 0.001f)
                {
                    continue;
                }

                triangleNormal.Normalize();
                for (var j = 0; j < 3; j++)
                {
                    var index0         = mesh.TriangleIndices[i0 + j];
                    var index1         = mesh.TriangleIndices[i0 + (j + 1) % 3];
                    var position0      = SharedFunctions.ToVector3D(mesh.Positions[index0]);
                    var position1      = SharedFunctions.ToVector3D(mesh.Positions[index1]);
                    var edgeKey        = new EdgeKey(position0, position1);
                    var reverseEdgeKey = new EdgeKey(position1, position0);
                    if (edgeNormals.TryGetValue(edgeKey, out var value) ||
                        edgeNormals.TryGetValue(reverseEdgeKey, out value))
                    {
                        var rawDot = SharedFunctions.DotProduct(ref triangleNormal, ref value);

                        // Acos returns NaN if rawDot > 1 or rawDot < -1
                        var dot = Math.Max(-1, Math.Min(rawDot, 1));

                        var angle = 180 / Math.PI * Math.Acos(dot);
                        if (angle > minimumAngle)
                        {
                            edgeIndices.Add(index0);
                            edgeIndices.Add(index1);
                        }
                    }
                    else
                    {
                        edgeNormals.Add(edgeKey, triangleNormal);
                    }
                }
            }
            return(edgeIndices);
        }
Example #8
0
        private IntCollection ReadFaceList(BinaryReader reader)
        {
            int size  = reader.ReadUInt16();
            var faces = new IntCollection();

            for (int i = 0; i < size; i++)
            {
                faces.Add(reader.ReadUInt16());
                faces.Add(reader.ReadUInt16());
                faces.Add(reader.ReadUInt16());
                reader.ReadUInt16();
            }
            return(faces);
        }
Example #9
0
        private static IntCollection GetTriangleIndices(DMesh3 mesh)
        {
            var tringleindices = new IntCollection(mesh.TrianglesRefCounts.count);
            var triangles      = mesh.TrianglesBuffer;

            foreach (int tId in mesh.TrianglesRefCounts)
            {
                int i = tId * 3;
                tringleindices.Add(triangles[i]);
                tringleindices.Add(triangles[i + 1]);
                tringleindices.Add(triangles[i + 2]);
            }

            return(tringleindices);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public MeshGeometry3D GetMesh()
        {
            var pos  = new Point3DCollection(vertices.Select(x => new Point3D(x.p.X, x.p.Y, x.p.Z)));
            var tris = new Int32Collection(triangles.Count * 3);

            foreach (var tri in triangles)
            {
                tris.Add(tri.v[0]);
                tris.Add(tri.v[1]);
                tris.Add(tri.v[2]);
            }
            return(new MeshGeometry3D()
            {
                Positions = pos, TriangleIndices = tris
            });
        }
Example #11
0
        private void LoadThreadFunction()
        {
            PCD wrapper = new PCD();

            Points[] rawPoints = wrapper.LoadPointcloud(Location);

            var points    = new PointGeometry3D();
            var col       = new Color4Collection();
            var ptPos     = new Vector3Collection();
            var ptIdx     = new IntCollection();
            var ptNormals = new Vector3Collection();

            var numberOfElements = rawPoints.Length;

            var additionalTurns = 0;

            foreach (var point in rawPoints)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(new Vector3(point.x, point.z, -point.y));
                col.Add(new Color4(new Color3(point.r / (float)255, point.g / (float)255, point.b / (float)255)));
                ptNormals.Add(new Vector3(0, 1, 0));
            }

            if ((rawPoints.Length / 3) * 3 != rawPoints.Length)
            {
                additionalTurns = ((rawPoints.Length / 3 + 1) * 3) - rawPoints.Length;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count - 1]);
                col.Add(col[col.Count - 1]);
                ptNormals.Add(ptNormals[ptNormals.Count - 1]);
            }

            points.Positions = ptPos;
            points.Indices   = ptIdx;
            points.Colors    = col;
            //points.Normals = ptNormals;

            Data = points;
        }
        /// <summary>
        /// Finds all edges where the angle between adjacent triangle normal vectors.
        /// is larger than minimumAngle
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <param name="minimumAngle">
        /// The minimum angle between the normal vectors of two adjacent triangles (degrees).
        /// </param>
        /// <returns>
        /// The edge indices.
        /// </returns>
        public static Int32Collection FindSharpEdges(this MeshGeometry3D mesh, double minimumAngle)
        {
            var edgeIndices = new Int32Collection();

            // the keys of the dictionary are created from the triangle indices of the edge
            var edgeNormals = new Dictionary <ulong, Vector3D>();

            for (int i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                int i0  = i * 3;
                var p0  = mesh.Positions[mesh.TriangleIndices[i0]];
                var p1  = mesh.Positions[mesh.TriangleIndices[i0 + 1]];
                var p2  = mesh.Positions[mesh.TriangleIndices[i0 + 2]];
                var p10 = p1 - p0;
                var p20 = p2 - p0;
                var n   = SharedFunctions.CrossProduct(ref p10, ref p20);
                n.Normalize();
                for (int j = 0; j < 3; j++)
                {
                    int      index0   = mesh.TriangleIndices[i0 + j];
                    int      index1   = mesh.TriangleIndices[i0 + ((j + 1) % 3)];
                    int      minIndex = Math.Min(index0, index1);
                    int      maxIndex = Math.Max(index0, index1);
                    ulong    key      = CreateKey((uint)minIndex, (uint)maxIndex);
                    Vector3D value;
                    if (edgeNormals.TryGetValue(key, out value))
                    {
                        var n2 = value;
                        n2.Normalize();
                        var angle = 180 / (DoubleOrSingle)Math.PI * (DoubleOrSingle)Math.Acos(SharedFunctions.DotProduct(ref n, ref n2));
                        if (angle > minimumAngle)
                        {
                            edgeIndices.Add(minIndex);
                            edgeIndices.Add(maxIndex);
                        }
                    }
                    else
                    {
                        edgeNormals.Add(key, n);
                    }
                }
            }

            return(edgeIndices);
        }
Example #13
0
        private void AddGrid()
        {
            if (_intCollection.Count >= MaxGrid)
            {
                return;
            }

            _intCollection.Add(0);
        }
Example #14
0
        /// <summary>
        /// Adds the circle.
        /// </summary>
        /// <param name="position">The position.</param>
        /// <param name="normal">The normal.</param>
        /// <param name="radius">The radius.</param>
        /// <param name="segments">The segments.</param>
        public void AddCircle(Vector3 position, Vector3 normal, float radius, int segments)
        {
            if (segments < 3)
            {
                throw new ArgumentNullException("too few segments, at least 3");
            }
            normal.Normalize();
            float sectionAngle = (float)(2.0 * Math.PI / segments);
            var   start        = new Vector3(radius, 0.0f, 0.0f);
            var   current      = new Vector3(radius, 0.0f, 0.0f);
            var   next         = new Vector3(0.0f, 0.0f, 0.0f);
            int   posStart     = positions.Count;

            positions.Add(current);
            int currIndex = posStart;

            for (int i = 1; i < segments; i++)
            {
                next.X  = radius * (float)Math.Cos(i * sectionAngle);
                next.Z  = radius * (float)Math.Sin(i * sectionAngle);
                current = next;
                positions.Add(current);
                lineListIndices.Add(currIndex);
                lineListIndices.Add(++currIndex);
            }

            lineListIndices.Add(currIndex);
            lineListIndices.Add(posStart);
            var axis      = Vector3.Cross(Vector3.UnitY, normal);
            var transform = Matrix.Translation(position);

            if (axis.LengthSquared() > 1e-6)
            {
                axis.Normalize();
                transform = Matrix.RotationAxis(axis, (float)Math.Acos(Vector3.Dot(Vector3.UnitY, normal))) * transform;
            }

            for (int i = posStart; i < positions.Count; ++i)
            {
                positions[i] = Vector3.TransformCoordinate(positions[i], transform);
            }
        }
        /// <summary>
        /// Simplifies the specified mesh.
        /// </summary>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        /// <param name="eps">
        /// The tolerance.
        /// </param>
        /// <returns>
        /// A simplified mesh.
        /// </returns>
        public static MeshGeometry3D Simplify(this MeshGeometry3D mesh, DoubleOrSingle eps)
        {
            // Find common positions
            var dict = new Dictionary <int, int>(); // map position index to first occurence of same position

            for (var i = 0; i < mesh.Positions.Count; i++)
            {
                for (var j = i + 1; j < mesh.Positions.Count; j++)
                {
                    if (dict.ContainsKey(j))
                    {
                        continue;
                    }
                    var v  = mesh.Positions[i] - mesh.Positions[j];
                    var l2 = SharedFunctions.LengthSquared(ref v);
                    if (l2 < eps)
                    {
                        dict.Add(j, i);
                    }
                }
            }

            var p  = new Point3DCollection();
            var ti = new Int32Collection();

            // create new positions array
            var newIndex = new Dictionary <int, int>(); // map old index to new index

            for (var i = 0; i < mesh.Positions.Count; i++)
            {
                if (!dict.ContainsKey(i))
                {
                    newIndex.Add(i, p.Count);
                    p.Add(mesh.Positions[i]);
                }
            }

            // Update triangle indices
            foreach (var index in mesh.TriangleIndices)
            {
                int j;
                ti.Add(dict.TryGetValue(index, out j) ? newIndex[j] : newIndex[index]);
            }
#if SHARPDX
            var result = new MeshGeometry3D {
                Positions = p, TriangleIndices = new IntCollection(ti),
            };
#else
            var result = new MeshGeometry3D {
                Positions = p, TriangleIndices = ti
            };
#endif
            return(result);
        }
        /// <summary>
        /// Finds edges that are only connected to one triangle.
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <returns>
        /// The edge indices for the edges that are only used by one triangle.
        /// </returns>
        public static Int32Collection FindBorderEdges(this MeshGeometry3D mesh)
        {
            var dict = new Dictionary <ulong, int>();

            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0 = i * 3;
                for (var j = 0; j < 3; j++)
                {
                    var index0   = mesh.TriangleIndices[i0 + j];
                    var index1   = mesh.TriangleIndices[i0 + ((j + 1) % 3)];
                    var minIndex = Math.Min(index0, index1);
                    var maxIndex = Math.Max(index1, index0);
                    var key      = CreateKey((uint)minIndex, (uint)maxIndex);
                    if (dict.ContainsKey(key))
                    {
                        dict[key] = dict[key] + 1;
                    }
                    else
                    {
                        dict.Add(key, 1);
                    }
                }
            }

            var edges = new Int32Collection();

            foreach (var kvp in dict)
            {
                // find edges only used by 1 triangle
                if (kvp.Value == 1)
                {
                    uint i0, i1;
                    ReverseKey(kvp.Key, out i0, out i1);
                    edges.Add((int)i0);
                    edges.Add((int)i1);
                }
            }

            return(edges);
        }
Example #17
0
        private void LoadThreadFunction()
        {
            var pt = new Potree(new Uri(Filename));

            var points = new PointGeometry3D();
            var col = new Color4Collection();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            var j = 0;

            foreach (var p in pt.Compilation.Points)
            {
                ptPos.Add(new Vector3(p.x, p.y, p.z));
                ptIdx.Add(j);
                col.Add(new Color4(p.r/255f, p.g / 255f, p.b / 255f, p.a / 255f));
                j++;
            }

            var additionalTurns = 0;

            if ((pt.Compilation.Points.Count / 3) * 3 != pt.Compilation.Points.Count)
            {
                additionalTurns = ((pt.Compilation.Points.Count / 3 + 1) * 3) - pt.Compilation.Points.Count;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count - 1]);
                col.Add(col[col.Count - 1]);
            }

            points.Positions = ptPos;
            points.Indices = ptIdx;
            points.Colors = col;

            Data = points;
        }
Example #18
0
        private void LoadThreadFunction()
        {
            var pt = new PotreeNode(new Uri(Location));

            var points = new PointGeometry3D();
            var col    = new Color4Collection();
            var ptPos  = new Vector3Collection();
            var ptIdx  = new IntCollection();

            var j = 0;

            foreach (var p in pt.Compilation.Points)
            {
                ptPos.Add(new Vector3(p.x, p.y, p.z));
                ptIdx.Add(j);
                col.Add(new Color4(p.r / 255f, p.g / 255f, p.b / 255f, p.a / 255f));
                j++;
            }

            var additionalTurns = 0;

            if ((pt.Compilation.Points.Count / 3) * 3 != pt.Compilation.Points.Count)
            {
                additionalTurns = ((pt.Compilation.Points.Count / 3 + 1) * 3) - pt.Compilation.Points.Count;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count - 1]);
                col.Add(col[col.Count - 1]);
            }

            points.Positions = ptPos;
            points.Indices   = ptIdx;
            points.Colors    = col;

            Data = points;
        }
Example #19
0
        public MeshBinder(Autodesk.DesignScript.Geometry.Mesh mesh, Color color)
        {
            dynamoMesh        = true;
            StartingPositions = mesh.VertexPositions.ToTriples().ToArray();
            Color             = color;
            faces             = mesh.FaceIndices;

            meshIndices = new IntCollection();

            foreach (IndexGroup face in faces)
            {
                meshIndices.Add((int)face.A);
                meshIndices.Add((int)face.B);
                meshIndices.Add((int)face.C);

                if (face.D == uint.MaxValue)
                {
                    continue;
                }

                meshIndices.Add((int)face.A);
                meshIndices.Add((int)face.C);
                meshIndices.Add((int)face.D);
            }
        }
Example #20
0
        public static PointGeometry3D ConvertToPointGeometry3D(Points[] points)
        {
            var geometry  = new PointGeometry3D();
            var col       = new Color4Collection();
            var ptPos     = new Vector3Collection();
            var ptIdx     = new IntCollection();
            var ptNormals = new Vector3Collection();

            var additionalTurns = 0;

            foreach (var point in points)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(new Vector3(point.x, point.y, point.z));
                col.Add(new Color4(new Color3(point.r / (float)255, point.g / (float)255, point.b / (float)255)));
                ptNormals.Add(new Vector3(0, 1, 0));
            }

            if ((points.Length / 3) * 3 != points.Length)
            {
                additionalTurns = ((points.Length / 3 + 1) * 3) - points.Length;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count - 1]);
                col.Add(col[col.Count - 1]);
                ptNormals.Add(ptNormals[ptNormals.Count - 1]);
            }

            geometry.Positions = ptPos;
            geometry.Indices   = ptIdx;
            geometry.Colors    = col;

            return(geometry);
        }
Example #21
0
        public static IntCollection Parse(string source)
        {
            IFormatProvider formatProvider = CultureInfo.InvariantCulture;
            var             th             = new TokenizerHelper(source, formatProvider);
            var             resource       = new IntCollection();

            while (th.NextToken())
            {
                var value = Convert.ToInt32(th.GetCurrentToken(), formatProvider);
                resource.Add(value);
            }

            return(resource);
        }
Example #22
0
        /// <summary>
        /// Converts a delimited string to a generic list of ints.
        /// </summary>
        /// <param name="value">A delimited string.</param>
        /// <param name="delimiter">The delimiter in the delimited string.</param>
        /// <returns>A generic list of strings: StringCollection</returns>
        public static IntCollection DelimitedStringToIntList(string value, char delimiter)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("value");
            }

            IntCollection result = new IntCollection();

            string[] valueArray = value.Split(delimiter);
            foreach (string val in valueArray)
            {
                result.Add(ToInt(val));
            }

            return(result);
        }
Example #23
0
        public void UpdateSLAMPointCloud()
        {
            int     Error        = 0;
            var     pose         = new List <HelixToolkit.Wpf.SharpDX.Geometry3D.Line>();
            var     line         = new LineBuilder();
            Vector3 previousPose = new Vector3(Convert.ToSingle(poseX), Convert.ToSingle(poseY), Convert.ToSingle(poseZ));

            while (IsSLAMOn)
            {
                var vc = new Vector3Collection();
                var id = new IntCollection();
                var cc = new Color4Collection();

                var     poseVect    = new List <double[]>();
                var     colorVect   = new List <double[]>();
                Vector3 currentPose = new Vector3(Convert.ToSingle(poseX), Convert.ToSingle(poseY), Convert.ToSingle(poseZ));

                line.AddLine(previousPose, currentPose);

                SLAMPoseInfo = line.ToLineGeometry3D();
                previousPose = currentPose;

                try
                {
                    RealsenseControl.GetSLAMPointCloud(ref poseVect, ref colorVect, T265ToLACCOffset.X, T265ToLACCOffset.Y, T265ToLACCOffset.Z);

                    for (int i = 0; i < poseVect.Count; i++)
                    {
                        vc.Add(new Vector3(Convert.ToSingle(poseVect[i][0]), Convert.ToSingle(poseVect[i][1]), Convert.ToSingle(poseVect[i][2])));
                        cc.Add(new Color4(0.1f, 0.1f, 0.1f, 0.5f));
                        //cc.Add(new Color4(Convert.ToSingle(colorVect[i][0]), Convert.ToSingle(colorVect[i][1]), Convert.ToSingle(colorVect[i][2]), 0.5f));
                        id.Add(i);
                    }
                    SLAMPointCloud = new PointGeometry3D()
                    {
                        Positions = vc, Indices = id, Colors = cc
                    };
                }
                catch
                {
                    Error++;
                    Trace.WriteLine("Error Count is " + Error);
                }
                Thread.Sleep(50);
            }
        }
Example #24
0
        /// <summary>
        /// Returns a list of month ints that represent the months YTD based on specified month int.
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        public static IntCollection MonthIntToMonthYtdIntList(int month)
        {
            //validate params
            if (month < 1 || month > 12)
            {
                throw new ArgumentOutOfRangeException("month", "The month int given was out of range.");
            }

            IntCollection monthList = new IntCollection();

            for (int i = 0; i <= month; i++)
            {
                monthList.Add(i);
            }

            return(monthList);
        }
Example #25
0
        /// <summary>
        /// Create the grid
        /// </summary>
        private void DrawGrid()
        {
            Grid = new LineGeometry3D();
            var positions = new Vector3Collection();
            var indices   = new IntCollection();
            var colors    = new Color4Collection();

            for (var i = 0; i < 10; i += 1)
            {
                for (var j = 0; j < 10; j += 1)
                {
                    DrawGridPatch(positions, indices, colors, -50 + i * 10, -50 + j * 10);
                }
            }

            Grid.Positions = positions;
            Grid.Indices   = indices;
            Grid.Colors    = colors;

            Axes = new LineGeometry3D();
            var axesPositions = new Vector3Collection();
            var axesIndices   = new IntCollection();
            var axesColors    = new Color4Collection();

            // Draw the coordinate axes
            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(50, 0, 0));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Red);
            axesColors.Add(SharpDX.Color.Red);

            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(0, 5, 0));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Blue);
            axesColors.Add(SharpDX.Color.Blue);

            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(0, 0, -50));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Green);
            axesColors.Add(SharpDX.Color.Green);

            Axes.Positions = axesPositions;
            Axes.Indices   = axesIndices;
            Axes.Colors    = axesColors;
        }
Example #26
0
        /// <summary>
        /// Converts a 3 character month string list to a month int list.
        /// </summary>
        /// <param name="monthList"></param>
        /// <returns></returns>
        public static IntCollection ThreeCharacterMonthListToMonthIntList(StringCollection threeCharacterMonthList)
        {
            //Validate params
            if (threeCharacterMonthList == null)
            {
                throw new ArgumentNullException("threeCharacterMonthList");
            }
            if (threeCharacterMonthList.Count < 1)
            {
                throw new ArgumentOutOfRangeException("threeCharacterMonthList");
            }

            IntCollection monthList = new IntCollection();

            foreach (string month in threeCharacterMonthList)
            {
                monthList.Add(ThreeCharacterMonthToMonthInt(month));
            }

            return(monthList);
        }
Example #27
0
        /// <summary>
        /// Creates the resulting <see cref="LineGeometry3D"/>.
        /// </summary>
        /// <param name="unshareVertices">
        /// If true, the resulting <see cref="LineGeometry3D"/> has no shared vertices.
        /// </param>
        /// <returns>Returns the resulting <see cref="LineGeometry3D"/>.</returns>
        public LineGeometry3D ToLineGeometry3D(bool unshareVertices = false)
        {
            if (unshareVertices)
            {
                var count = this.lineListIndices.Count;
                var pos   = new Vector3Collection(count);
                var idx   = new IntCollection(count);
                for (var i = 0; i < count; i++)
                {
                    pos.Add(this.positions[this.lineListIndices[i]]);
                    idx.Add(i);
                }

                return(new LineGeometry3D {
                    Positions = pos, Indices = idx
                });
            }

            return(new LineGeometry3D {
                Positions = this.positions, Indices = this.lineListIndices
            });
        }
Example #28
0
        public static MeshGeometry3D ToMeshGeometry3D(this DMesh3 mesh)
        {
            var vertices  = mesh.Vertices();
            var uiPoints  = new Point3DCollection(mesh.VertexCount);
            var indexes   = mesh.TriangleIndices();
            var uiIndexes = new IntCollection();

            foreach (var v in vertices)
            {
                uiPoints.Add(v.ToPoint3D());
            }

            foreach (var i in indexes)
            {
                uiIndexes.Add(i);
            }

            return(new MeshGeometry3D()
            {
                Positions = uiPoints.ToVector3Collection(),
                TriangleIndices = uiIndexes
            });
        }
Example #29
0
        public MainViewModel()
        {
            // titles
            this.Title    = "Simple Demo";
            this.SubTitle = "WPF & SharpDX";

            // camera setup
            this.Camera = new PerspectiveCamera {
                Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0)
            };

            // default render technique
            this.RenderTechnique = Techniques.RenderBlinn;

            // setup lighting
            this.AmbientLightColor         = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor     = Color.White;
            this.DirectionalLightDirection = new Vector3(-2, -5, -2);

            // floor plane grid
            this.Grid          = LineBuilder.GenerateGrid();
            this.GridColor     = SharpDX.Color.Black;
            this.GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5);

            // scene model3d
            var b1 = new MeshBuilder();

            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);

            var meshGeometry = b1.ToMeshGeometry3D();

            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            this.Model          = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();

            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            this.Lines = e1.ToLineGeometry3D();

            // model trafos
            this.Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            this.Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            this.Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            this.RedMaterial   = PhongMaterials.Red;
            this.GreenMaterial = PhongMaterials.Green;
            this.BlueMaterial  = PhongMaterials.Blue;
            //var diffColor = this.RedMaterial.DiffuseColor;
            //diffColor.Alpha = 0.5f;
            //this.RedMaterial.DiffuseColor = diffColor;

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 10; y++)
                {
                    for (int z = 0; z < 10; z++)
                    {
                        ptIdx.Add(ptPos.Count);
                        ptPos.Add(new Vector3(x, y, z));
                    }
                }
            }

            Points.Positions = ptPos;
            Points.Indices   = ptIdx;

            Text = new BillboardText3D();

            for (var i = 0; i < 50; i++)
            {
                for (var j = 0; j < 50; j++)
                {
                    Text.TextInfo.Add(new TextInfo("Hello World", new Vector3(i, j, 0)));
                }
            }
        }
Example #30
0
        /// <summary>
        /// Parses the MDL file to obtain model information
        /// </summary>
        /// <param name="selectedItem">The currently selected item</param>
        /// <param name="selectedRace">The currently selected race</param>
        /// <param name="selectedBody">The currently selected body</param>
        /// <param name="selectedPart">The currently selected part</param>
        /// <param name="selectedCategory">The items category </param>
        public MDL(ItemData selectedItem, string selectedCategory, string selectedRace, string selectedBody, string selectedPart)
        {
            string itemType  = Helper.GetCategoryType(selectedCategory);
            string MDLFolder = "";

            if (itemType.Equals("weapon") || itemType.Equals("food"))
            {
                if (selectedPart.Equals("Secondary"))
                {
                    MDLFolder = string.Format(Strings.WeapMDLFolder, selectedItem.SecondaryModelID, selectedItem.SecondaryModelBody);
                    MDLFile   = string.Format(Strings.WeapMDLFile, selectedItem.SecondaryModelID, selectedItem.SecondaryModelBody);
                }
                else
                {
                    MDLFolder = string.Format(Strings.WeapMDLFolder, selectedItem.PrimaryModelID, selectedItem.PrimaryModelBody);
                    MDLFile   = string.Format(Strings.WeapMDLFile, selectedItem.PrimaryModelID, selectedItem.PrimaryModelBody);
                }
            }
            else if (itemType.Equals("accessory"))
            {
                MDLFolder = string.Format(Strings.AccMDLFolder, selectedItem.PrimaryModelID);
                MDLFile   = string.Format(Strings.AccMDLFile, selectedRace, selectedItem.PrimaryModelID, Info.slotAbr[selectedCategory]);
            }
            else if (itemType.Equals("character"))
            {
                if (selectedItem.ItemName.Equals(Strings.Body))
                {
                    MDLFolder = string.Format(Strings.BodyMDLFolder, selectedRace, selectedBody.PadLeft(4, '0'));
                    MDLFile   = string.Format(Strings.BodyMDLFile, selectedRace, selectedBody.PadLeft(4, '0'), selectedPart);
                }
                else if (selectedItem.ItemName.Equals(Strings.Face))
                {
                    MDLFolder = string.Format(Strings.FaceMDLFolder, selectedRace, selectedBody.PadLeft(4, '0'));
                    MDLFile   = string.Format(Strings.FaceMDLFile, selectedRace, selectedBody.PadLeft(4, '0'), selectedPart);
                }
                else if (selectedItem.ItemName.Equals(Strings.Hair))
                {
                    MDLFolder = string.Format(Strings.HairMDLFolder, selectedRace, selectedBody.PadLeft(4, '0'));
                    MDLFile   = string.Format(Strings.HairMDLFile, selectedRace, selectedBody.PadLeft(4, '0'), selectedPart);
                }
                else if (selectedItem.ItemName.Equals(Strings.Tail))
                {
                    MDLFolder = string.Format(Strings.TailMDLFolder, selectedRace, selectedBody.PadLeft(4, '0'));
                    MDLFile   = string.Format(Strings.TailMDLFile, selectedRace, selectedBody.PadLeft(4, '0'), selectedPart);
                }
            }
            else if (itemType.Equals("monster"))
            {
                bool isDemiHuman = false;
                if (selectedItem.PrimaryMTRLFolder != null)
                {
                    isDemiHuman = selectedItem.PrimaryMTRLFolder.Contains("demihuman");
                }

                string ID   = "";
                string body = "";

                if (selectedCategory.Equals(Strings.Pets))
                {
                    int part = 1;

                    if (selectedItem.ItemName.Equals(Strings.Selene) || selectedItem.ItemName.Equals(Strings.Bishop_Autoturret))
                    {
                        part = 2;
                    }

                    ID   = Info.petID[selectedItem.ItemName];
                    body = part.ToString().PadLeft(4, '0');
                }
                else
                {
                    ID   = selectedItem.PrimaryModelID.PadLeft(4, '0');
                    body = selectedItem.PrimaryModelBody;
                }

                if (isDemiHuman)
                {
                    MDLFolder = string.Format(Strings.DemiMDLFolder, ID, body);
                    MDLFile   = string.Format(Strings.DemiMDLFile, ID, body, selectedPart);
                }
                else
                {
                    MDLFolder = string.Format(Strings.MonsterMDLFolder, ID, body);
                    MDLFile   = string.Format(Strings.MonsterMDLFile, ID, body);
                }
            }
            else
            {
                MDLFolder = string.Format(Strings.EquipMDLFolder, selectedItem.PrimaryModelID);

                if (selectedPart.Equals("-"))
                {
                    MDLFile = string.Format(Strings.EquipMDLFile, selectedRace, selectedItem.PrimaryModelID, Info.slotAbr[selectedCategory]);
                }
                else
                {
                    MDLFile = string.Format(Strings.EquipMDLFile, selectedRace, selectedItem.PrimaryModelID, selectedPart);
                }
            }

            fullPath = MDLFolder + "/" + MDLFile;
            int offset = Helper.GetDataOffset(FFCRC.GetHash(MDLFolder), FFCRC.GetHash(MDLFile), Strings.ItemsDat);

            if (offset == 0)
            {
                if (itemType.Equals("weapon"))
                {
                    if (selectedPart.Equals("Secondary"))
                    {
                        MDLFolder = string.Format(Strings.EquipMDLFolder, selectedItem.SecondaryModelID);
                        MDLFile   = string.Format(Strings.EquipMDLFile, "0101", selectedItem.SecondaryModelID, Info.slotAbr[Strings.Hands]);

                        offset = Helper.GetDataOffset(FFCRC.GetHash(MDLFolder), FFCRC.GetHash(MDLFile), Strings.ItemsDat);
                    }
                }
            }

            int datNum = ((offset / 8) & 0x000f) / 2;

            var MDLDatData = Helper.GetType3DecompressedData(offset, datNum, Strings.ItemsDat);

            using (BinaryReader br = new BinaryReader(new MemoryStream(MDLDatData.Item1)))
            {
                // The size of the header + (size of the mesh information block (136 bytes) * the number of meshes) + padding
                br.BaseStream.Seek(64 + 136 * MDLDatData.Item2 + 4, SeekOrigin.Begin);

                var modelStringCount = br.ReadInt32();
                var stringBlockSize  = br.ReadInt32();
                var stringBlock      = br.ReadBytes(stringBlockSize);

                var unknown = br.ReadBytes(4);

                var totalMeshCount       = br.ReadInt16();
                var attributeStringCount = br.ReadInt16();
                var meshPartsCount       = br.ReadInt16();
                var materialStringCount  = br.ReadInt16();
                var boneStringCount      = br.ReadInt16();
                var boneListCount        = br.ReadInt16();

                var unknown1 = br.ReadInt16();
                var unknown2 = br.ReadInt16();
                var unknown3 = br.ReadInt16();
                var unknown4 = br.ReadInt16();
                var unknown5 = br.ReadInt16();
                var unknown6 = br.ReadInt16();

                br.ReadBytes(10);

                var unknown7 = br.ReadInt16();

                br.ReadBytes(16);

                using (BinaryReader br1 = new BinaryReader(new MemoryStream(stringBlock)))
                {
                    br1.BaseStream.Seek(0, SeekOrigin.Begin);

                    for (int i = 0; i < attributeStringCount; i++)
                    {
                        while (br1.ReadByte() != 0)
                        {
                            //extract each atribute string here
                        }
                    }

                    for (int i = 0; i < boneStringCount; i++)
                    {
                        byte        b;
                        List <byte> boneName = new List <byte>();
                        while ((b = br1.ReadByte()) != 0)
                        {
                            boneName.Add(b);
                        }
                        string bone = Encoding.ASCII.GetString(boneName.ToArray());
                        bone = bone.Replace("\0", "");

                        boneStrings.Add(bone);
                    }

                    for (int i = 0; i < materialStringCount; i++)
                    {
                        byte        b;
                        List <byte> name = new List <byte>();
                        while ((b = br1.ReadByte()) != 0)
                        {
                            name.Add(b);
                        }
                        string material = Encoding.ASCII.GetString(name.ToArray());
                        material = material.Replace("\0", "");

                        materialStrings.Add(material);
                    }
                }

                br.ReadBytes(32 * unknown5);

                for (int i = 0; i < 3; i++)
                {
                    LevelOfDetail LoD = new LevelOfDetail();
                    LoD.MeshOffset = br.ReadInt16();
                    LoD.MeshCount  = br.ReadInt16();

                    br.ReadBytes(40);

                    LoD.VertexDataSize = br.ReadInt32();
                    LoD.IndexDataSize  = br.ReadInt32();
                    LoD.VertexOffset   = br.ReadInt32();
                    LoD.IndexOffset    = br.ReadInt32();

                    modelData.LoD.Add(LoD);
                }

                var savePos = br.BaseStream.Position;

                for (int i = 0; i < modelData.LoD.Count; i++)
                {
                    List <MeshDataInfo> meshInfoList = new List <MeshDataInfo>();

                    for (int j = 0; j < modelData.LoD[i].MeshCount; j++)
                    {
                        modelData.LoD[i].MeshList.Add(new Mesh());
                        meshInfoList.Clear();

                        br.BaseStream.Seek((i * 136) + 68, SeekOrigin.Begin);
                        var dataBlockNum = br.ReadByte();

                        while (dataBlockNum != 255)
                        {
                            MeshDataInfo meshInfo = new MeshDataInfo()
                            {
                                VertexDataBlock = dataBlockNum,
                                Offset          = br.ReadByte(),
                                DataType        = br.ReadByte(),
                                UseType         = br.ReadByte()
                            };

                            meshInfoList.Add(meshInfo);

                            br.ReadBytes(4);

                            dataBlockNum = br.ReadByte();
                        }

                        modelData.LoD[i].MeshList[j].MeshDataInfoList = meshInfoList.ToArray();
                    }
                }

                br.BaseStream.Seek(savePos, SeekOrigin.Begin);

                for (int x = 0; x < modelData.LoD.Count; x++)
                {
                    for (int i = 0; i < modelData.LoD[x].MeshCount; i++)
                    {
                        MeshInfo meshInfo = new MeshInfo()
                        {
                            VertexCount     = br.ReadInt32(),
                            IndexCount      = br.ReadInt32(),
                            MaterialNum     = br.ReadInt16(),
                            MeshPartOffset  = br.ReadInt16(),
                            MeshPartCount   = br.ReadInt16(),
                            BoneListIndex   = br.ReadInt16(),
                            IndexDataOffset = br.ReadInt32()
                        };

                        for (int j = 0; j < 3; j++)
                        {
                            meshInfo.VertexDataOffsets.Add(br.ReadInt32());
                        }

                        for (int k = 0; k < 3; k++)
                        {
                            meshInfo.VertexSizes.Add(br.ReadByte());
                        }

                        meshInfo.VertexDataBlockCount = br.ReadByte();

                        modelData.LoD[x].MeshList[i].MeshInfo = meshInfo;
                    }
                }

                br.ReadBytes(attributeStringCount * 4);
                br.ReadBytes(unknown6 * 20);

                for (int i = 0; i < modelData.LoD.Count; i++)
                {
                    foreach (var mesh in modelData.LoD[i].MeshList)
                    {
                        for (int j = 0; j < mesh.MeshInfo.MeshPartCount; j++)
                        {
                            MeshPart meshPart = new MeshPart()
                            {
                                IndexOffset = br.ReadInt32(),
                                IndexCount  = br.ReadInt32(),
                                Attributes  = br.ReadInt32(),
                                BoneOffset  = br.ReadInt16(),
                                BoneCount   = br.ReadInt16()
                            };

                            mesh.MeshPartList.Add(meshPart);
                        }
                    }
                }

                br.ReadBytes(unknown7 * 12);
                br.ReadBytes(materialStringCount * 4);
                br.ReadBytes(boneStringCount * 4);

                for (int i = 0; i < boneListCount; i++)
                {
                    Bones bones = new Bones();

                    for (int j = 0; j < 64; j++)
                    {
                        bones.BoneData.Add(br.ReadInt16());
                    }

                    bones.BoneCount = br.ReadInt32();

                    modelData.BoneSet.Add(bones);
                }

                //br.ReadBytes(unknown1 * 16);

                Dictionary <int, int>         indexMin     = new Dictionary <int, int>();
                Dictionary <int, List <int> > extraIndices = new Dictionary <int, List <int> >();
                List <ExtraIndex>             indexCounts  = new List <ExtraIndex>();

                var pCount  = 0;
                var pCount1 = 0;
                var pCount2 = 0;

                if (unknown1 > 0)
                {
                    for (int i = 0; i < unknown1; i++)
                    {
                        //not sure
                        br.ReadBytes(4);

                        //LoD[0] Extra Data Index
                        var p1 = br.ReadUInt16();

                        //LoD[1] Extra Data Index
                        var p2 = br.ReadUInt16();

                        //LoD[2] Extra Data Index
                        var p3 = br.ReadUInt16();


                        //LoD[0] Extra Data Part Count
                        var p1n = br.ReadUInt16();
                        pCount += p1n;

                        //LoD[1] Extra Data Part Count
                        var p2n = br.ReadUInt16();
                        pCount1 += p2n;

                        //LoD[2] Extra Data Part Count
                        var p3n = br.ReadUInt16();
                        pCount2 += p3n;
                    }
                }

                Dictionary <int, int> indexLoc = new Dictionary <int, int>();

                if (unknown1 > 0)
                {
                    for (int i = 0; i < modelData.LoD[0].MeshCount; i++)
                    {
                        var ido = modelData.LoD[0].MeshList[i].MeshInfo.IndexDataOffset;
                        indexLoc.Add(ido, i);
                    }
                }


                List <int>            maskCounts       = new List <int>();
                Dictionary <int, int> totalExtraCounts = new Dictionary <int, int>();
                if (unknown2 > 0)
                {
                    for (int i = 0; i < pCount; i++)
                    {
                        //Index Offset Start
                        var m1   = br.ReadInt32();
                        var iLoc = 0;
                        if (indexLoc.ContainsKey(m1))
                        {
                            iLoc = indexLoc[m1];
                        }

                        //index count
                        var mCount = br.ReadInt32();

                        //index offset in unk3
                        var mOffset = br.ReadInt32();

                        indexCounts.Add(new ExtraIndex()
                        {
                            IndexLocation = iLoc, IndexCount = mCount
                        });
                        maskCounts.Add(mCount);
                    }

                    br.ReadBytes((pCount1 + pCount2) * 12);
                }

                int totalLoD0MaskCount = 0;

                if (unknown2 > 0)
                {
                    for (int i = 0; i < pCount; i++)
                    {
                        totalLoD0MaskCount += maskCounts[i];
                    }
                }

                if (unknown3 > 0)
                {
                    var unk3Remainder = (unknown3 * 4) - (totalLoD0MaskCount * 4);

                    foreach (var ic in indexCounts)
                    {
                        HashSet <int> mIndexList = new HashSet <int>();

                        for (int i = 0; i < ic.IndexCount; i++)
                        {
                            //index its replacing? attatched to?
                            br.ReadBytes(2);
                            //extra index following last equipment index
                            var mIndex = br.ReadInt16();
                            mIndexList.Add(mIndex);

                            if (extraIndices.ContainsKey(ic.IndexLocation))
                            {
                                extraIndices[ic.IndexLocation].Add(mIndex);
                            }
                            else
                            {
                                extraIndices.Add(ic.IndexLocation, new List <int>()
                                {
                                    mIndex
                                });
                            }
                        }

                        if (totalExtraCounts.ContainsKey(ic.IndexLocation))
                        {
                            totalExtraCounts[ic.IndexLocation] += mIndexList.Count;
                        }
                        else
                        {
                            totalExtraCounts.Add(ic.IndexLocation, mIndexList.Count);
                        }
                    }
                    //the rest of unk3
                    br.ReadBytes(unk3Remainder);
                }



                if (unknown3 > 0)
                {
                    foreach (var ei in extraIndices)
                    {
                        indexMin.Add(ei.Key, ei.Value.Min());
                    }

                    extraIndexData.indexCounts      = indexCounts;
                    extraIndexData.indexMin         = indexMin;
                    extraIndexData.totalExtraCounts = totalExtraCounts;
                    extraIndexData.extraIndices     = extraIndices;

                    modelData.ExtraData = extraIndexData;
                }

                //br.ReadBytes(unknown3 * 4);

                var boneIndexSize = br.ReadInt32();

                for (int i = 0; i < boneIndexSize / 2; i++)
                {
                    modelData.BoneIndicies.Add(br.ReadInt16());
                }

                int padding = br.ReadByte();
                br.ReadBytes(padding);

                for (int i = 0; i < 4; i++)
                {
                    ModelMaterial.BoundingBox boundingBox = new ModelMaterial.BoundingBox();
                    for (int j = 0; j < 4; j++)
                    {
                        boundingBox.PointA.Add(br.ReadSingle());
                    }
                    for (int k = 0; k < 4; k++)
                    {
                        boundingBox.PointB.Add(br.ReadSingle());
                    }

                    modelData.BoundingBoxes.Add(boundingBox);
                }

                //float4x4
                for (int i = 0; i < boneStringCount; i++)
                {
                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());

                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());
                    boneTransforms.Add(br.ReadSingle());
                }

                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < modelData.LoD[i].MeshCount; j++)
                    {
                        Mesh mesh = modelData.LoD[i].MeshList[j];

                        for (int k = 0; k < mesh.MeshInfo.VertexDataBlockCount; k++)
                        {
                            br.BaseStream.Seek(modelData.LoD[i].VertexOffset + mesh.MeshInfo.VertexDataOffsets[k], SeekOrigin.Begin);

                            mesh.MeshVertexData.Add(br.ReadBytes(mesh.MeshInfo.VertexSizes[k] * mesh.MeshInfo.VertexCount));
                        }

                        br.BaseStream.Seek(modelData.LoD[i].IndexOffset + (mesh.MeshInfo.IndexDataOffset * 2), SeekOrigin.Begin);

                        mesh.IndexData = br.ReadBytes(2 * mesh.MeshInfo.IndexCount);
                    }
                }

                int vertex = 0, coordinates = 0, normals = 0, tangents = 0, colors = 0, blendWeights = 0, blendIndices = 0;

                for (int i = 0; i < modelData.LoD[0].MeshCount; i++)
                {
                    objBytes.Clear();

                    var vertexList        = new Vector3Collection();
                    var texCoordList      = new Vector2Collection();
                    var texCoordList2     = new Vector2Collection();
                    var normalList        = new Vector3Collection();
                    var tangentList       = new Vector3Collection();
                    var colorsList        = new Color4Collection();
                    var indexList         = new IntCollection();
                    var blendWeightList   = new List <float>();
                    var blendWeightList2  = new List <float[]>();
                    var blendIndicesList  = new List <int>();
                    var blendIndicesList2 = new List <int[]>();
                    var weightCounts      = new List <int>();


                    Mesh mesh = modelData.LoD[0].MeshList[i];

                    MeshDataInfo[] meshDataInfoList = mesh.MeshDataInfoList;

                    int c = 0;
                    foreach (var meshDataInfo in meshDataInfoList)
                    {
                        if (meshDataInfo.UseType == 0)
                        {
                            vertex = c;
                        }
                        else if (meshDataInfo.UseType == 1)
                        {
                            blendWeights = c;
                        }
                        else if (meshDataInfo.UseType == 2)
                        {
                            blendIndices = c;
                        }
                        else if (meshDataInfo.UseType == 3)
                        {
                            normals = c;
                        }
                        else if (meshDataInfo.UseType == 4)
                        {
                            coordinates = c;
                        }
                        else if (meshDataInfo.UseType == 6)
                        {
                            tangents = c;
                        }
                        else if (meshDataInfo.UseType == 7)
                        {
                            colors = c;
                        }

                        c++;
                    }

                    /*
                     * -----------------
                     * Vertex
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[vertex].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[vertex].VertexDataBlock] + meshDataInfoList[vertex].Offset, SeekOrigin.Begin);

                            Vector3 vVector = new Vector3();
                            if (meshDataInfoList[vertex].DataType == 13 || meshDataInfoList[vertex].DataType == 14)
                            {
                                System.Half h1 = System.Half.ToHalf((ushort)br1.ReadInt16());
                                System.Half h2 = System.Half.ToHalf((ushort)br1.ReadInt16());
                                System.Half h3 = System.Half.ToHalf((ushort)br1.ReadInt16());

                                float x = HalfHelper.HalfToSingle(h1);
                                float y = HalfHelper.HalfToSingle(h2);
                                float z = HalfHelper.HalfToSingle(h3);

                                vVector = new Vector3(x, y, z);
                                objBytes.Add("v " + x.ToString("N5") + " " + y.ToString("N5") + " " + z.ToString("N5") + " ");
                            }
                            else if (meshDataInfoList[vertex].DataType == 2)
                            {
                                var x = BitConverter.ToSingle(br1.ReadBytes(4), 0);
                                var y = BitConverter.ToSingle(br1.ReadBytes(4), 0);
                                var z = BitConverter.ToSingle(br1.ReadBytes(4), 0);

                                vVector = new Vector3(x, y, z);
                                objBytes.Add("v " + x.ToString("N5") + " " + y.ToString("N5") + " " + z.ToString("N5") + " ");
                            }

                            vertexList.Add(vVector);
                        }
                    }


                    /*
                     * -----------------
                     * Blend Weight
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[blendWeights].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[blendWeights].VertexDataBlock] + meshDataInfoList[blendWeights].Offset, SeekOrigin.Begin);

                            float x = br1.ReadByte() / 255.0f;
                            float y = br1.ReadByte() / 255.0f;
                            float z = br1.ReadByte() / 255.0f;
                            float w = br1.ReadByte() / 255.0f;

                            int count = 0;
                            if (x != 0)
                            {
                                blendWeightList.Add(x);
                                count++;

                                if (y != 0)
                                {
                                    blendWeightList.Add(y);
                                    count++;

                                    if (z != 0)
                                    {
                                        blendWeightList.Add(z);
                                        count++;

                                        if (w != 0)
                                        {
                                            blendWeightList.Add(w);
                                            count++;
                                        }
                                    }
                                }
                            }

                            if (count == 1)
                            {
                                blendWeightList2.Add(new float[] { x });
                            }
                            else if (count == 2)
                            {
                                blendWeightList2.Add(new float[] { x, y });
                            }
                            else if (count == 3)
                            {
                                blendWeightList2.Add(new float[] { x, y, z });
                            }
                            else if (count == 4)
                            {
                                blendWeightList2.Add(new float[] { x, y, z, w });
                            }

                            weightCounts.Add(count);
                        }
                    }


                    /*
                     * -----------------
                     * Blend Index
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[blendIndices].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[blendIndices].VertexDataBlock] + meshDataInfoList[blendIndices].Offset, SeekOrigin.Begin);

                            int x = br1.ReadByte();
                            int y = br1.ReadByte();
                            int z = br1.ReadByte();
                            int w = br1.ReadByte();

                            if (weightCounts[j] == 1)
                            {
                                blendIndicesList.Add(x);
                                blendIndicesList2.Add(new int[] { x });
                            }
                            else if (weightCounts[j] == 2)
                            {
                                blendIndicesList.Add(x);
                                blendIndicesList.Add(y);
                                blendIndicesList2.Add(new int[] { x, y });
                            }
                            else if (weightCounts[j] == 3)
                            {
                                blendIndicesList.Add(x);
                                blendIndicesList.Add(y);
                                blendIndicesList.Add(z);
                                blendIndicesList2.Add(new int[] { x, y, z });
                            }
                            else if (weightCounts[j] == 4)
                            {
                                blendIndicesList.Add(x);
                                blendIndicesList.Add(y);
                                blendIndicesList.Add(z);
                                blendIndicesList.Add(w);
                                blendIndicesList2.Add(new int[] { x, y, z, w });
                            }
                        }
                    }


                    /*
                     * -----------------
                     * Texture Coordinates
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[coordinates].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[coordinates].VertexDataBlock] + meshDataInfoList[coordinates].Offset, SeekOrigin.Begin);

                            float x = 0;
                            float y = 0;
                            float z = 0;
                            float w = 0;
                            if (meshDataInfoList[coordinates].DataType == 13 || meshDataInfoList[coordinates].DataType == 14)
                            {
                                var sx = (ushort)br1.ReadInt16();
                                var sy = (ushort)br1.ReadInt16();
                                var sz = (ushort)br1.ReadInt16();
                                var sw = (ushort)br1.ReadInt16();

                                var h1 = new SharpDX.Half(sx);
                                var h2 = new SharpDX.Half(sy);
                                var h3 = new SharpDX.Half(sz);
                                var h4 = new SharpDX.Half(sw);

                                x = h1;
                                y = h2;
                                z = h3;
                                w = h4;
                            }
                            else if (meshDataInfoList[coordinates].DataType == 1)
                            {
                                x = br1.ReadSingle();
                                y = br1.ReadSingle();
                            }
                            else
                            {
                                x = br1.ReadSingle();
                                y = br1.ReadSingle();
                                z = br1.ReadSingle();
                                w = br1.ReadSingle();
                            }


                            var ox = x - Math.Truncate(x);
                            var oy = y - Math.Truncate(y);

                            objBytes.Add("vt " + ox.ToString("N5") + " " + (1 - y).ToString("N5") + " ");
                            texCoordList.Add(new Vector2(x, y));
                            texCoordList2.Add(new Vector2(z, w));
                        }
                    }



                    /*
                     * -----------------
                     * Normals
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[normals].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[normals].VertexDataBlock] + meshDataInfoList[normals].Offset, SeekOrigin.Begin);

                            float x = 0;
                            float y = 0;
                            float z = 0;
                            float w = 0;

                            if (meshDataInfoList[normals].DataType == 13 || meshDataInfoList[normals].DataType == 14)
                            {
                                System.Half h1 = System.Half.ToHalf((ushort)br1.ReadInt16());
                                System.Half h2 = System.Half.ToHalf((ushort)br1.ReadInt16());
                                System.Half h3 = System.Half.ToHalf((ushort)br1.ReadInt16());
                                System.Half h4 = System.Half.ToHalf((ushort)br1.ReadInt16());

                                x = HalfHelper.HalfToSingle(h1);
                                y = HalfHelper.HalfToSingle(h2);
                                z = HalfHelper.HalfToSingle(h3);
                                w = HalfHelper.HalfToSingle(h4);
                            }
                            else
                            {
                                x = br1.ReadSingle();
                                y = br1.ReadSingle();
                                z = br1.ReadSingle();
                            }

                            var nv = new Vector3(x, y, z);

                            objBytes.Add("vn " + x.ToString("N5") + " " + y.ToString("N5") + " " + z.ToString("N5") + " ");
                            normalList.Add(nv);
                        }
                    }


                    /*
                     * -----------------
                     * Tangents
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[tangents].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[tangents].VertexDataBlock] + meshDataInfoList[tangents].Offset, SeekOrigin.Begin);

                            int x = br1.ReadByte();
                            int y = br1.ReadByte();
                            int z = br1.ReadByte();
                            int w = br1.ReadByte();

                            var x1 = x * 2 / 255f - 1f;
                            var y1 = y * 2 / 255f - 1f;
                            var z1 = z * 2 / 255f - 1f;
                            var w1 = w * 2 / 255f - 1f;


                            var nv = new Vector3(x1, y1, z1);

                            tangentList.Add(nv);
                        }
                    }


                    /*
                     * -----------------
                     * Vertex Color
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.MeshVertexData[meshDataInfoList[colors].VertexDataBlock])))
                    {
                        for (int j = 0; j < mesh.MeshInfo.VertexCount; j++)
                        {
                            br1.BaseStream.Seek(j * mesh.MeshInfo.VertexSizes[meshDataInfoList[colors].VertexDataBlock] + meshDataInfoList[colors].Offset, SeekOrigin.Begin);

                            int a = br1.ReadByte();
                            int r = br1.ReadByte();
                            int g = br1.ReadByte();
                            int b = br1.ReadByte();

                            colorsList.Add(new Color4(r, g, b, a));
                        }
                    }


                    /*
                     * -----------------
                     * Index
                     * -----------------
                     */
                    using (BinaryReader br1 = new BinaryReader(new MemoryStream(mesh.IndexData)))
                    {
                        for (int j = 0; j < mesh.MeshInfo.IndexCount; j += 3)
                        {
                            int i1 = br1.ReadInt16();
                            int i2 = br1.ReadInt16();
                            int i3 = br1.ReadInt16();

                            objBytes.Add("f " + (i1 + 1) + "/" + (i1 + 1) + "/" + (i1 + 1) + " " + (i2 + 1) + "/" + (i2 + 1) + "/" + (i2 + 1) + " " + (i3 + 1) + "/" + (i3 + 1) + "/" + (i3 + 1) + " ");

                            indexList.Add(i1);
                            indexList.Add(i2);
                            indexList.Add(i3);
                        }
                    }

                    ModelMeshData modelMeshData = new ModelMeshData()
                    {
                        Vertices              = vertexList,
                        Normals               = normalList,
                        TextureCoordinates    = texCoordList,
                        TextureCoordinates2   = texCoordList2,
                        BiTangents            = tangentList,
                        Indices               = indexList,
                        VertexColors          = colorsList,
                        OBJFileData           = objBytes.ToArray(),
                        BoneStrings           = boneStrings,
                        BoneIndices           = modelData.BoneIndicies,
                        BoneTransforms        = boneTransforms,
                        BlendWeights          = blendWeightList,
                        BlendIndices          = blendIndicesList,
                        WeightCounts          = weightCounts,
                        MeshPartList          = mesh.MeshPartList,
                        BlendIndicesArrayList = blendIndicesList2,
                        BlendWeightsArrayList = blendWeightList2,
                        MaterialNum           = mesh.MeshInfo.MaterialNum,
                        MeshPartCount         = mesh.MeshInfo.MeshPartCount,
                        MeshPartOffset        = mesh.MeshInfo.MeshPartOffset
                    };

                    meshList.Add(modelMeshData);
                }
            }
        }
Example #31
0
        private void LoadThreadFunction()
        {
            PCD wrapper = new PCD();

            Points[] rawPoints = wrapper.LoadPointcloud(Filename);

            var points = new PointGeometry3D();
            var col = new Color4Collection();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();
            var ptNormals = new Vector3Collection();

            var numberOfElements = rawPoints.Length;

            var additionalTurns = 0;

            foreach (var point in rawPoints)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(new Vector3(point.x, point.z, -point.y));
                col.Add(new Color4(new Color3(point.r / (float)255, point.g / (float)255, point.b / (float)255)));
                ptNormals.Add(new Vector3(0, 1, 0));
            }

            if ((rawPoints.Length / 3) * 3 != rawPoints.Length)
            {
                additionalTurns = ((rawPoints.Length / 3 + 1) * 3) - rawPoints.Length;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count-1]);
                col.Add(col[col.Count - 1]);
                ptNormals.Add(ptNormals[ptNormals.Count - 1]);
            }

            points.Positions = ptPos;
            points.Indices = ptIdx;
            points.Colors = col;
            //points.Normals = ptNormals;

            Data = points;
        }
Example #32
0
        public MainViewModel()
        {
            EffectsManager = new DefaultEffectsManager();
            // titles
            Title    = "Simple Demo";
            SubTitle = "WPF & SharpDX";

            // camera setup
            Camera = new PerspectiveCamera {
                Position         = new Point3D(3, 3, 5),
                LookDirection    = new Vector3D(-3, -3, -5),
                UpDirection      = new Vector3D(0, 1, 0),
                FarPlaneDistance = 5000000
            };

            // setup lighting
            AmbientLightColor         = Colors.DimGray;
            DirectionalLightColor     = Colors.White;
            DirectionalLightDirection = new Vector3D(-2, -5, -2);

            // floor plane grid
            Grid          = LineBuilder.GenerateGrid(new Vector3(0, 1, 0), -5, 5, -5, 5);
            GridColor     = Colors.Black;
            GridTransform = new Media3D.TranslateTransform3D(0, -3, 0);

            // scene model3d
            var b1 = new MeshBuilder();

            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);

            var meshGeometry = b1.ToMeshGeometry3D();

            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            Model = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();

            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            Lines = e1.ToLineGeometry3D();

            var textBuilder = new MeshBuilder();

            textBuilder.ExtrudeText("HelixToolkit.SharpDX", "Arial", System.Windows.FontStyles.Normal, System.Windows.FontWeights.Bold,
                                    14, new Vector3(1, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 1));
            TextModel = textBuilder.ToMesh();

            // model trafos
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);
            Model4Transform = new Media3D.TranslateTransform3D(-8, 0, -5);

            // model materials
            RedMaterial   = PhongMaterials.Red;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial  = PhongMaterials.Blue;
            //var diffColor = this.RedMaterial.DiffuseColor;
            //diffColor.Alpha = 0.5f;
            //this.RedMaterial.DiffuseColor = diffColor;

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 10; y++)
                {
                    for (int z = 0; z < 10; z++)
                    {
                        ptIdx.Add(ptPos.Count);
                        ptPos.Add(new Vector3(x, y, z));
                    }
                }
            }

            Points.Positions = ptPos;
            Points.Indices   = ptIdx;

            Text = new BillboardText3D();
            int numRows    = 11;
            int numColumns = 11;

            string[] texts = new string[]
            {
                "HelixToolkit",
                "abcde",
                "random",
                "SharpDX",
                "DirectX"
            };
            float angle = 0;

            for (var i = 0; i < numRows; i++)
            {
                for (var j = 0; j < numColumns; j++)
                {
                    angle += (float)Math.PI / 10;
                    Text.TextInfo.Add(new TextInfo(texts[(i + j) % texts.Length], new Vector3((i - numRows / 2), 0.0f, (j - numColumns / 2)))
                    {
                        Foreground = new Color4((float)i / numRows, 1 - (float)i / numRows, (float)(numColumns - j) / numColumns, 1f),
                        Background = new Color4(1 - (float)i / numRows, (float)(numColumns - j) / numColumns, (float)i / numRows, 0.8f),
                        Scale      = Math.Max(0.01f, (float)i / numRows * 0.02f),
                        Angle      = angle
                    });
                }
            }

            Billboard1Model = new BillboardSingleText3D()
            {
                TextInfo = new TextInfo("Model 1", new Vector3(0, 1, 0))
                {
                    Angle = 0
                },
                FontColor       = Colors.Blue.ToColor4(),
                FontSize        = 12,
                BackgroundColor = Colors.Plum.ToColor4(),
                FontStyle       = System.Windows.FontStyles.Italic,
                Padding         = new System.Windows.Thickness(2),
            };

            var background = Colors.Blue;

            background.A    = (byte)120;
            Billboard2Model = new BillboardSingleText3D()
            {
                TextInfo = new TextInfo("Model 2", new Vector3(2, 1, 0))
                {
                    Angle = -(float)Math.PI / 3
                },
                FontSize        = 12,
                FontColor       = Colors.Green.ToColor4(),
                BackgroundColor = background.ToColor4(),
                FontWeight      = System.Windows.FontWeights.Bold,
                Padding         = new System.Windows.Thickness(2),
            };
            background      = Colors.Purple;
            background.A    = (byte)50;
            Billboard3Model = new BillboardSingleText3D(2, 0.8f)
            {
                TextInfo = new TextInfo("Model 3", new Vector3(-2, 1, 0))
                {
                    Angle = -(float)Math.PI / 6
                },
                FontSize        = 12,
                FontColor       = Colors.Red.ToColor4(),
                BackgroundColor = background.ToColor4(),
                FontFamily      = "Times New Roman",
                FontStyle       = System.Windows.FontStyles.Italic,
                Padding         = new System.Windows.Thickness(2),
            };


            //BillboardImageModel = new BillboardSingleImage3D(CreateBitmapSample()) { MaskColor = Color.Black };
            BillboardImageModel = new BillboardSingleImage3D(CreatePNGSample(), 1, 1)
            {
                Angle = -(float)Math.PI / 5
            };
            BillboardImageModel.Center = new Vector3(2, 2, 0);

            UpXCommand        = new RelayCommand(x => { UpDirection = new Vector3D(1, 0, 0); });
            UpYCommand        = new RelayCommand(x => { UpDirection = new Vector3D(0, 1, 0); });
            UpZCommand        = new RelayCommand(x => { UpDirection = new Vector3D(0, 0, 1); });
            BackgroundTexture =
                BitmapExtensions.CreateLinearGradientBitmapStream(EffectsManager, 128, 128, Direct2DImageFormat.Bmp,
                                                                  new Vector2(0, 0), new Vector2(0, 128), new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color = Colors.White.ToColor4(), Position = 0f
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color = Colors.DarkGray.ToColor4(), Position = 1f
                }
            });
        }
Example #33
0
        public MainViewModel()
        {
            // titles
            Title = "Simple Demo";
            SubTitle = "WPF & SharpDX";

            // camera setup
            Camera = new PerspectiveCamera { 
                Position = new Point3D(3, 3, 5), 
                LookDirection = new Vector3D(-3, -3, -5), 
                UpDirection = new Vector3D(0, 1, 0),
                FarPlaneDistance = 5000000
            };

            // Create a custom render techniques manager that 
            // only supports Phong and Blinn
            RenderTechniquesManager = new CustomRenderTechniquesManager();
            RenderTechnique = RenderTechniquesManager.RenderTechniques["RenderCustom"];
            EffectsManager = new CustomEffectsManager(RenderTechniquesManager);

            // setup lighting            
            AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            DirectionalLightColor = Color.White;
            DirectionalLightDirection = new Vector3(-2, -5, -2);

            // floor plane grid
            Grid = LineBuilder.GenerateGrid();
            GridColor = Color.Black;
            GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5);

            // scene model3d
            var b1 = new MeshBuilder();            
            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);
           
            var meshGeometry = b1.ToMeshGeometry3D();
            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            Model = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();
            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            Lines = e1.ToLineGeometry3D();

            // model transform
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            RedMaterial = PhongMaterials.Red;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial = PhongMaterials.Blue;

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            Text = new BillboardText3D();

            for (int x = -5; x <= 5; x++)
            {
                for (int y = -5; y <= 5; y++)
                {
                    ptIdx.Add(ptPos.Count);
                    ptPos.Add(new Vector3(x, -1, y));
                    Text.TextInfo.Add(new TextInfo(string.Format("{0}:{1}", x, y), new Vector3(x, -1, y)));
                }
            }

            Points.Positions = ptPos;
            Points.Indices = ptIdx;
        }
Example #34
0
 private IntCollection ReadFaceList(BinaryReader reader)
 {
   int size = reader.ReadUInt16();
   var faces = new IntCollection();
   for(int i=0;i< size; i++)
   {
     faces.Add(reader.ReadUInt16());
     faces.Add(reader.ReadUInt16());
     faces.Add(reader.ReadUInt16());
     reader.ReadUInt16();
   }
   return faces;
 }
Example #35
0
        public static PointGeometry3D ConvertToPointGeometry3D(Points[] points)
        {
            var geometry = new PointGeometry3D();
            var col = new Color4Collection();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();
            var ptNormals = new Vector3Collection();

            var additionalTurns = 0;

            foreach (var point in points)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(new Vector3(point.x, point.y, point.z));
                col.Add(new Color4(new Color3(point.r / (float)255, point.g / (float)255, point.b / (float)255)));
                ptNormals.Add(new Vector3(0, 1, 0));
            }

            if ((points.Length / 3) * 3 != points.Length)
            {
                additionalTurns = ((points.Length / 3 + 1) * 3) - points.Length;
            }

            for (int i = 0; i < additionalTurns; i++)
            {
                ptIdx.Add(ptPos.Count);

                ptPos.Add(ptPos[ptPos.Count - 1]);
                col.Add(col[col.Count - 1]);
                ptNormals.Add(ptNormals[ptNormals.Count - 1]);
            }

            geometry.Positions = ptPos;
            geometry.Indices = ptIdx;
            geometry.Colors = col;

            return geometry;
        }
Example #36
0
		public override void Save()
		{
			if (IsReadOnly)
			{
				throw new ReadOnlyException();
			}

			Mode = FileAccessMode.Write;

			IntCollection pageGroup = new IntCollection();

			foreach (int page in dirtyPages)
				if (!pageGroup.IsEmpty && pageGroup[pageGroup.Count - 1] + 1 != page)
				{
					WritePageGroup(pageGroup);
					pageGroup.Clear();
				}
				else
					pageGroup.Add(page);

			WritePageGroup(pageGroup);
			dirtyPages.Clear();
			dirtyPackets.Clear();

			Mode = FileAccessMode.Closed;
		}
Example #37
0
        /// <summary>
        /// Makes sure no triangles share the same vertex.
        /// </summary>
        private void NoSharedVertices()
        {
            var p = new Vector3Collection();
            var ti = new IntCollection();
            Vector3Collection n = null;
            if (this.normals != null)
            {
                n = new Vector3Collection();
            }

            Vector2Collection tc = null;
            if (this.textureCoordinates != null)
            {
                tc = new Vector2Collection();
            }

            for (int i = 0; i < this.triangleIndices.Count; i += 3)
            {
                int i0 = i;
                int i1 = i + 1;
                int i2 = i + 2;
                int index0 = this.triangleIndices[i0];
                int index1 = this.triangleIndices[i1];
                int index2 = this.triangleIndices[i2];
                var p0 = this.positions[index0];
                var p1 = this.positions[index1];
                var p2 = this.positions[index2];
                p.Add(p0);
                p.Add(p1);
                p.Add(p2);
                ti.Add(i0);
                ti.Add(i1);
                ti.Add(i2);
                if (n != null)
                {
                    n.Add(this.normals[index0]);
                    n.Add(this.normals[index1]);
                    n.Add(this.normals[index2]);
                }

                if (tc != null)
                {
                    tc.Add(this.textureCoordinates[index0]);
                    tc.Add(this.textureCoordinates[index1]);
                    tc.Add(this.textureCoordinates[index2]);
                }
            }

            this.positions = p;
            this.triangleIndices = ti;
            this.normals = n;
            this.textureCoordinates = tc;
        }
Example #38
0
        private void CreateFaceModels(IFCItem item, Vector3 center)
        {
            while (item != null) {
                if (item.ifcID != IntPtr.Zero && item.noVerticesForFaces != 0 && item.noPrimitivesForFaces != 0) {
                    var positions = new Vector3Collection();
                    var normals = new Vector3Collection();
                    if (item.verticesForFaces != null) {
                        for (int i = 0; i < item.noVerticesForFaces; i++) {
                            var point = new Vector3(item.verticesForFaces[6 * i + 0] - center.X, item.verticesForFaces[6 * i + 1] - center.Y, item.verticesForFaces[6 * i + 2] - center.Z);
                            var normal = new Vector3(item.verticesForFaces[6 * i + 3], item.verticesForFaces[6 * i + 4], item.verticesForFaces[6 * i + 5]);
                            positions.Add(point);
                            normals.Add(normal);
                        }

                        Debug.Assert(item.verticesForFaces.Length == item.noVerticesForFaces * 6);
                    }

                    var indices = new IntCollection();
                    if (item.indicesForFaces != null) {
                        for (int i = 0; i < 3 * item.noPrimitivesForFaces; i++) {
                            indices.Add(item.indicesForFaces[i]);
                        }
                    }

                    var meshGeometry = new MeshGeometry3D();
                    meshGeometry.Positions = positions;
                    meshGeometry.Normals = normals;
                    meshGeometry.Indices = indices;
                    meshGeometry.TextureCoordinates = null;
                    meshGeometry.Colors = null;
                    meshGeometry.Tangents = null;
                    meshGeometry.BiTangents = null;

                    MeshGeometryModel3D mesh = new MeshGeometryModel3D() { Geometry = meshGeometry };
                    //                    var builder = new MeshBuilder(true, false);
                    //                    builder.Positions.AddRange(positions);
                    //                    builder.Normals.AddRange(normals);
                    //                    builder.TriangleIndices.AddRange(indices);
                    //                    MeshGeometryModel3D mesh = new MeshGeometryModel3D() { Geometry = builder.ToMeshGeometry3D() };
                    item.Mesh3d = mesh;
                    _meshToIfcItems[mesh] = item;
                    //#if DEBUG
                    //                    OutputObj(item.ifcID.ToString(), meshGeometry);
                    //#endif
                    FillMeshByIfcColor(item);

                    mesh.Tag = item.ifcType + ":" + item.ifcID;
                    model.Add(mesh);
                }

                CreateFaceModels(item.child, center);
                item = item.next;
            }
        }
Example #39
0
        private static void AppendSphere(Vector3 center, double radius, int thetaSteps, int phiSteps,
            out Vector3Collection positions, out Vector3Collection normals, out Vector2Collection textureCoordinates, out IntCollection triangleIndices)
        {
            positions = new Vector3Collection();
            normals = new Vector3Collection();
            textureCoordinates = new Vector2Collection();
            triangleIndices = new IntCollection();

            double dt = DegToRad(360.0) / thetaSteps;
            double dp = DegToRad(180.0) / phiSteps;

            for (int pi = 0; pi <= phiSteps; pi++)
            {
                double phi = pi * dp;
                for (int ti = 0; ti <= thetaSteps; ti++)
                {
                    // we want to start the mesh on the x axis
                    double theta = ti * dt;

                    positions.Add(GetPosition(theta, phi, radius) + center);
                    normals.Add(GetNormal(theta, phi));
                    textureCoordinates.Add(GetTextureCoordinate(theta, phi));
                }
            }

            for (int pi = 0; pi < phiSteps; pi++)
            {
                for (int ti = 0; ti < thetaSteps; ti++)
                {
                    int x0 = ti;
                    int x1 = ti + 1;
                    int y0 = pi * (thetaSteps + 1);
                    int y1 = (pi + 1) * (thetaSteps + 1);

                    triangleIndices.Add(x0 + y0);
                    triangleIndices.Add(x0 + y1);
                    triangleIndices.Add(x1 + y0);

                    triangleIndices.Add(x1 + y0);
                    triangleIndices.Add(x0 + y1);
                    triangleIndices.Add(x1 + y1);
                }
            }
        }
Example #40
0
        /// <summary>
        /// Create the grid
        /// </summary>
        private void DrawGrid()
        {
            Grid = new LineGeometry3D();
            var positions = new Vector3Collection();
            var indices = new IntCollection();
            var colors = new Color4Collection();

            for(var i= 0; i < 10; i += 1)
            {
                for (var j = 0; j < 10; j += 1)
                {
                    DrawGridPatch(positions, indices, colors, -50 + i * 10, -50 + j * 10);
                }
            }

            Grid.Positions = positions;
            Grid.Indices = indices;
            Grid.Colors = colors;

            Axes = new LineGeometry3D();
            var axesPositions = new Vector3Collection();
            var axesIndices = new IntCollection();
            var axesColors = new Color4Collection();

            // Draw the coordinate axes
            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(50, 0, 0));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Red);
            axesColors.Add(SharpDX.Color.Red);

            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(0, 5, 0));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Blue);
            axesColors.Add(SharpDX.Color.Blue);

            axesPositions.Add(new Vector3());
            axesIndices.Add(axesPositions.Count - 1);
            axesPositions.Add(new Vector3(0, 0, -50));
            axesIndices.Add(axesPositions.Count - 1);
            axesColors.Add(SharpDX.Color.Green);
            axesColors.Add(SharpDX.Color.Green);

            Axes.Positions = axesPositions;
            Axes.Indices = axesIndices;
            Axes.Colors = axesColors;

        }
Example #41
0
        private static void DrawGridPatch(
            Vector3Collection positions, IntCollection indices, Color4Collection colors, int startX, int startY)
        {
            var c1 = (Color)ColorConverter.ConvertFromString("#c5d1d8");
            c1.Clamp();
            var c2 = (Color)ColorConverter.ConvertFromString("#ddeaf2");
            c2.Clamp();

            var darkGridColor = new Color4(new Vector4(c1.ScR,c1.ScG ,c1.ScB, 1));
            var lightGridColor = new Color4(new Vector4(c2.ScR, c2.ScG, c2.ScB, 1));

            const int size = 10;

            for (var x = startX; x <= startX + size; x++)
            {
                if (x == 0 && startY < 0) continue;

                var v = new Vector3(x, -.001f, startY);
                positions.Add(v);
                indices.Add(positions.Count - 1);
                positions.Add(new Vector3(x, -.001f, startY + size));
                indices.Add(positions.Count - 1);

                if (x % 5 == 0)
                {
                    colors.Add(darkGridColor);
                    colors.Add(darkGridColor);
                }
                else
                {
                    colors.Add(lightGridColor);
                    colors.Add(lightGridColor);
                }
            }

            for (var y = startY; y <= startY + size; y++)
            {
                if (y == 0 && startX >= 0) continue;

                positions.Add(new Vector3(startX, -.001f, y));
                indices.Add(positions.Count - 1);
                positions.Add(new Vector3(startX + size, -.001f, y));
                indices.Add(positions.Count - 1);

                if (y % 5 == 0)
                {
                    colors.Add(darkGridColor);
                    colors.Add(darkGridColor);
                }
                else
                {
                    colors.Add(lightGridColor);
                    colors.Add(lightGridColor);
                }
            }
        }
Example #42
0
    private static IntCollection ConvertFaceIndices(List<int> subFaces, List<int> faces)
    {
      var triangleIndices = new IntCollection(subFaces.Count * 3);// new List<int>(subFaces.Count * 3);
      foreach (int f in subFaces)
      {
        triangleIndices.Add(faces[f * 3]);
        triangleIndices.Add(faces[(f * 3) + 1]);
        triangleIndices.Add(faces[(f * 3) + 2]);
      }

      return triangleIndices;
    }
Example #43
0
        public MainViewModel()
        {
            // titles
            this.Title = "Simple Demo";
            this.SubTitle = "WPF & SharpDX";

            // camera setup
            this.Camera = new PerspectiveCamera {
                Position = new Point3D(3, 3, 5),
                LookDirection = new Vector3D(-3, -3, -5),
                UpDirection = new Vector3D(0, 1, 0),
                FarPlaneDistance = 5000000
            };

            // default render technique
            this.RenderTechnique = Techniques.RenderBlinn;

            // setup lighting
            this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor = Color.White;
            this.DirectionalLightDirection = new Vector3(-2, -5, -2);

            // floor plane grid
            this.Grid = LineBuilder.GenerateGrid();
            this.GridColor = SharpDX.Color.Black;
            this.GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5);

            // scene model3d
            var b1 = new MeshBuilder();
            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);

            var meshGeometry = b1.ToMeshGeometry3D();
            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            this.Model = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();
            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            this.Lines = e1.ToLineGeometry3D();

            // model trafos
            this.Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            this.Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            this.Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            this.RedMaterial = PhongMaterials.Red;
            this.GreenMaterial = PhongMaterials.Green;
            this.BlueMaterial = PhongMaterials.Blue;
            //var diffColor = this.RedMaterial.DiffuseColor;
            //diffColor.Alpha = 0.5f;
            //this.RedMaterial.DiffuseColor = diffColor;

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 10; y++)
                {
                    for (int z = 0; z < 10; z++)
                    {
                        ptIdx.Add(ptPos.Count);
                        ptPos.Add(new Vector3(x, y, z));
                    }
                }
            }

            Points.Positions = ptPos;
            Points.Indices = ptIdx;

            Text = new BillboardText3D();

            for (var i = 0; i < 50; i++)
            {
                for (var j = 0; j < 50; j++)
                {
                    Text.TextInfo.Add(new TextInfo("Hello World", new Vector3(i,j,0)));
                }
            }
        }
Example #44
0
        public static MeshGeometry3D Merge(params MeshGeometry3D[] meshes)
        {
            var positions = new Vector3Collection();
            var indices = new IntCollection();

            var normals = meshes.All(x => x.Normals != null) ? new Vector3Collection() : null;
            var colors = meshes.All(x => x.Colors != null) ? new Color4Collection() : null;
            var textureCoods = meshes.All(x => x.TextureCoordinates != null) ? new Vector2Collection() : null;
            var tangents = meshes.All(x => x.Tangents != null) ? new Vector3Collection() : null;
            var bitangents = meshes.All(x => x.BiTangents != null) ? new Vector3Collection() : null;

            int index = 0;
            foreach (var part in meshes)
            {
                for (int i = 0; i < part.Positions.Count; i++)
                {
                    positions.Add(part.Positions[i]);
                }

                for (int i = 0; i < part.Indices.Count; i++)
                {
                    indices.Add(index + part.Indices[i]);
                }

                index += part.Indices.Count;
            }

            if (normals != null)
            {
                normals = new Vector3Collection(meshes.SelectMany(x => x.Normals));
            }

            if (colors != null)
            {
                colors = new Color4Collection(meshes.SelectMany(x => x.Colors));
            }

            if (textureCoods != null)
            {
                textureCoods = new Vector2Collection(meshes.SelectMany(x => x.TextureCoordinates));
            }

            if (tangents != null)
            {
                tangents = new Vector3Collection(meshes.SelectMany(x => x.Tangents));
            }

            if (bitangents != null)
            {
                bitangents = new Vector3Collection(meshes.SelectMany(x => x.BiTangents));
            }

            var mesh = new MeshGeometry3D()
            {
                Positions = positions,
                Indices = indices,
            };

            mesh.Normals = normals;
            mesh.Colors = colors;
            mesh.TextureCoordinates = textureCoods;
            mesh.Tangents = tangents;
            mesh.BiTangents = bitangents;

            return mesh;
        }