public static MeshGeometryModel3D MakeMeshGeometryModel3D(List <Point3D> allPoints, HelixToolkit.Wpf.SharpDX.Material mat) { var allIndices = new List <int>(); for (int i = 0; i < allPoints.Count; i++) { allIndices.Add(i); } var g3d = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); g3d.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); g3d.TriangleIndices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(); g3d.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); g3d.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(); for (int i = 0; i < allPoints.Count; i++) { var p3 = allPoints[i]; SharpDX.Vector3 v3 = P2V(p3); g3d.Positions.Add(v3); g3d.Normals.Add(new SharpDX.Vector3(0, 1, 0)); } for (int i = 0; i < allIndices.Count; i++) { g3d.Indices.Add(allIndices[i]); } var ret = new MeshGeometryModel3D(); ret.Material = mat; ret.Geometry = g3d; //ret. = new System.Windows.Controls.TextBlock() { Text = caption }; return(ret); }
public HelixRenderPackage() { points = InitPointGeometry(); lines = InitLineGeometry(); mesh = InitMeshGeometry(); lineStripVertexCounts = new List<int>(); }
public static MeshGeometryModel3D MakeMeshGeometryModel3DUnity(DHTriangle triangle, HelixToolkit.Wpf.SharpDX.Material mat) { var allIndices = new List <int>(new int[] { 0, 1, 2 }); var g3d = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); g3d.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); g3d.TriangleIndices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(); g3d.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); g3d.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(); g3d.Positions.Add(U2V(triangle.vertices0)); g3d.Positions.Add(U2V(triangle.vertices1)); g3d.Positions.Add(U2V(triangle.vertices2)); g3d.Normals.Add(new SharpDX.Vector3(0, 1, 0)); g3d.Normals.Add(new SharpDX.Vector3(0, 1, 0)); g3d.Normals.Add(new SharpDX.Vector3(0, 1, 0)); for (int i = 0; i < allIndices.Count; i++) { g3d.Indices.Add(allIndices[i]); } var ret = new MeshGeometryModel3D(); ret.Material = mat; ret.Geometry = g3d; //ret. = new System.Windows.Controls.TextBlock() { Text = caption }; return(ret); }
private void ClearModels() { Points.Positions = new Vector3Collection(); Points.Indices = new IntCollection(); Model = new MeshGeometry3D(); RaisePropertyChanged(nameof(Model)); }
public HelixRenderPackage() { points = InitPointGeometry(); lines = InitLineGeometry(); mesh = InitMeshGeometry(); lineStripVertexCounts = new List<int>(); Transform = System.Windows.Media.Media3D.Matrix3D.Identity.ToArray(); }
/// <summary> /// 儲存模型檔案,第一個參數指定路徑,第二個參數指定是否要儲存轉移後的模型 /// </summary> public void SaveModel(string filepath, bool isSavedTransform) { HelixToolkit.Wpf.SharpDX.MeshGeometry3D geometry = Geometry as HelixToolkit.Wpf.SharpDX.MeshGeometry3D; if (geometry == null) { return; } MeshGeometry3D mesh = new MeshGeometry3D { Positions = new Point3DCollection(), Normals = new Vector3DCollection(), TriangleIndices = new Int32Collection() }; foreach (Vector3 position in geometry.Positions) { mesh.Positions.Add(new Point3D(position.X, position.Y, position.Z)); } foreach (Vector3 normal in geometry.Normals) { mesh.Normals.Add(new Vector3D(normal.X, normal.Y, normal.Z)); } foreach (int triangleindice in geometry.TriangleIndices) { mesh.TriangleIndices.Add(triangleindice); } GeometryModel3D model = new GeometryModel3D { Geometry = mesh, }; StlExporter export = new StlExporter(); if (isSavedTransform) { model.Transform = Transform; string fileAfterTransform = System.IO.Path.GetFileNameWithoutExtension(SafeFileName); fileAfterTransform += "(transform).stl"; using (var fileStream = File.Create(System.IO.Path.Combine(filepath, fileAfterTransform))) { export.Export(model, fileStream); } return; } using (var fileStream = File.Create(System.IO.Path.Combine(filepath, SafeFileName))) { export.Export(model, fileStream); } }
private MeshGeometry3D GetMeshGeometry(TTModel model, int meshGroupId) { var group = model.MeshGroups[meshGroupId]; var mg = new MeshGeometry3D { Positions = new Vector3Collection((int)group.VertexCount), Normals = new Vector3Collection((int)group.VertexCount), Colors = new Color4Collection((int)group.VertexCount), TextureCoordinates = new Vector2Collection((int)group.VertexCount), BiTangents = new Vector3Collection((int)group.VertexCount), Tangents = new Vector3Collection((int)group.VertexCount), Indices = new IntCollection((int)group.IndexCount) }; var indexCount = 0; var vertCount = 0; for (int mi = 0; mi < meshGroupId; mi++) { var g = model.MeshGroups[mi]; //vertCount += (int) g.VertexCount; //indexCount += (int)g.IndexCount; } foreach (var p in group.Parts) { foreach (var v in p.Vertices) { // I don't think our current shader actually utilizes this data anyways // but may as well include it correctly. var color = new Color4(); color.Red = v.VertexColor[0] / 255f; color.Green = v.VertexColor[1] / 255f; color.Blue = v.VertexColor[2] / 255f; color.Alpha = v.VertexColor[3] / 255f; mg.Positions.Add(v.Position); mg.Normals.Add(v.Normal); mg.TextureCoordinates.Add(v.UV1); mg.Colors.Add(color); mg.BiTangents.Add(v.Binormal); mg.Tangents.Add(v.Tangent); } foreach (var vertexId in p.TriangleIndices) { // Have to bump these to account for merging the lists together. mg.Indices.Add(vertCount + vertexId); } vertCount += p.Vertices.Count; indexCount += p.TriangleIndices.Count; } return(mg); }
/// <summary> /// /// </summary> /// <param name="mesh"></param> /// <returns></returns> public static System.Windows.Media.Media3D.MeshGeometry3D ToMeshGeometry3D(SharpDX.MeshGeometry3D mesh) { return(new System.Windows.Media.Media3D.MeshGeometry3D() { Normals = ToVector3DCollection(mesh.Normals), Positions = ToPoint3DCollection(mesh.Positions), TextureCoordinates = ToPointCollection(mesh.TextureCoordinates), TriangleIndices = ToInt32Collection(mesh.TriangleIndices) }); }
public static void UpdateFrom(this MeshGeometry3D dest, DMesh3 src) { //if (!src.IsCompact) src.CompactInPlace(); //var vertices = src.VerticesBuffer; //foreach (int vId in src.VerticesRefCounts) //{ // int i = vId * 3; // dest.Positions.Add(new Point3D(vertices[i], vertices[i + 1], vertices[i + 2])); //} //var triangles = src.TrianglesBuffer; //foreach (int tId in src.TrianglesRefCounts) //{ // int i = tId * 3; // dest.TriangleIndices.Add(triangles[i]); // dest.TriangleIndices.Add(triangles[i + 1]); // dest.TriangleIndices.Add(triangles[i + 2]); //} var positions = new List <Point3D>(src.VerticesRefCounts.count); var tringleindices = new List <int>(src.TrianglesRefCounts.count); var tasks = new Task[2]; tasks[0] = Task.Run(() => { var vertices = src.VerticesBuffer; foreach (int vId in src.VerticesRefCounts) { int i = vId * 3; positions.Add(new Point3D(vertices[i], vertices[i + 1], vertices[i + 2])); } }); tasks[1] = Task.Run(() => { var triangles = src.TrianglesBuffer; foreach (int tId in src.TrianglesRefCounts) { int i = tId * 3; tringleindices.Add(triangles[i]); tringleindices.Add(triangles[i + 1]); tringleindices.Add(triangles[i + 2]); } }); Task.WaitAll(tasks); dest.Positions = positions.ToVector3Collection(); dest.TriangleIndices = new IntCollection(tringleindices); }
public static MeshGeometry3D ToWPF(this Mesh m) { var result = new MeshGeometry3D() { Positions = new Vector3Collection(m.Vertices.Select(ToVector3)), Indices = new IntCollection(m.Faces.ToIntArray(true)), Normals = new Vector3Collection(m.Normals.Select(ToVector3)), }; return(result); }
public static void OutputObj(string ifcId, MeshGeometry3D rep) { using (var writer = new StreamWriter("./" + ifcId + ".obj")) { for (int i = 0, count = rep.Positions.Count; i < count; i++) { writer.WriteLine("v {0} {1} {2}", rep.Positions[i].X, rep.Positions[i].Y, rep.Positions[i].Z); writer.WriteLine("vn {0} {1} {2}", rep.Normals[i].X, rep.Normals[i].Y, rep.Normals[i].Z); } var indices = rep.Indices.ToArray().Reverse().ToList();//HACK winding for (int i = 0, count = indices.Count / 3; i < count; i++) { writer.WriteLine("f {0}//{0} {1}//{1} {2}//{2}", indices[i * 3] + 1, indices[i * 3 + 1] + 1, indices[i * 3 + 2] + 1); } } }
public void Clear() { points = null; mesh = null; lines = null; points = InitPointGeometry(); mesh = InitMeshGeometry(); lines = InitLineGeometry(); lineStripVertexCounts.Clear(); IsSelected = false; DisplayLabels = false; }
public static DMesh3 ToDMesh3(this MeshGeometry3D mesh) { var dMesh = new DMesh3(); var positions = mesh.Positions; var indexes = mesh.TriangleIndices; foreach (var p in positions) { dMesh.AppendVertex(p.ToVector3d()); } for (int i = 0; i < indexes.Count; i += 3) { dMesh.AppendTriangle(indexes[i], indexes[i + 1], indexes[i + 2]); } return(dMesh); }
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; } }
private static void Draw(IFCItem element, ref List <IfcMeshGeometryModel3D> modelList, string[] filter) { while (element != null) { if (element.child != null) { Draw(element.child, ref modelList, filter); } if (!(element.noPrimitivesForFaces > 0)) { element = element.next; continue; } if (filter != null) { var index = Array.FindIndex(filter, x => x.Equals(element.name, StringComparison.InvariantCultureIgnoreCase)); if (filter.Any() && index == -1) { element = element.next; continue; } } MeshGeometry3D geometry = new MeshGeometry3D() { Positions = new Vector3Collection(), Normals = new Vector3Collection(), Indices = new IntCollection(), TextureCoordinates = new Vector2Collection() }; var positions = new Vector3Collection(); var normals = new Vector3Collection(); //ToDo: Depending on if the model is modelled in meter or millimeter this divident has to be changed var divident = 1000; for (int i = 0; i < element.noVerticesForFaces; i++) { var offset = i * 6; positions.Add(new SharpDX.Vector3( element.verticesForFaces[offset + 0] / divident, element.verticesForFaces[offset + 2] / divident, -element.verticesForFaces[offset + 1] / divident )); normals.Add(new SharpDX.Vector3( element.verticesForFaces[offset + 3], element.verticesForFaces[offset + 5], -element.verticesForFaces[offset + 4] )); } for (int i = 0; i < element.indicesForFaces.Length; i++) { geometry.Indices.Add(i); geometry.Positions.Add(positions[(int)element.indicesForFaces[i]]); geometry.Normals.Add(normals[(int)element.indicesForFaces[i]]); //just needs to be filled with something geometry.TextureCoordinates.Add(new Vector2(0, 0)); } modelList.Add(new IfcMeshGeometryModel3D() { Geometry = geometry, IfcName = element.name, IfcGlobalId = element.globalID }); element = element.next; } }
public static void Draw(IFCItem element, ref List<IfcMeshGeometryModel3D> modelList) { while (element != null) { if (element.child != null) { Draw(element.child, ref modelList); } if (!(element.noPrimitivesForFaces > 0)) { element = element.next; continue; } MeshGeometry3D geometry = new MeshGeometry3D() { Positions = new Vector3Collection(), Normals = new Vector3Collection(), Indices = new IntCollection(), TextureCoordinates = new Vector2Collection() }; var positions = new Vector3Collection(); var normals = new Vector3Collection(); //ToDo: Depending on if the model is modelled in meter or millimeter this divident has to be changed var divident = 1000; for (int i = 0; i < element.noVerticesForFaces; i++) { var offset = i * 6; positions.Add(new SharpDX.Vector3( element.verticesForFaces[offset + 0] / divident, element.verticesForFaces[offset + 2] / divident, -element.verticesForFaces[offset + 1] / divident )); normals.Add(new SharpDX.Vector3( element.verticesForFaces[offset + 3], element.verticesForFaces[offset + 5], -element.verticesForFaces[offset + 4] )); } for (int i = 0; i < element.indicesForFaces.Length; i++) { geometry.Indices.Add(i); geometry.Positions.Add(positions[(int)element.indicesForFaces[i]]); geometry.Normals.Add(normals[(int)element.indicesForFaces[i]]); //just needs to be filled with something geometry.TextureCoordinates.Add(new Vector2(0,0)); } modelList.Add(new IfcMeshGeometryModel3D() { Geometry = geometry, IfcName = element.name }); element = element.next; } }
public static void ComputeTangents(MeshGeometry3D meshGeometry) { Vector3Collection t1, t2; ComputeTangents(meshGeometry.Positions, meshGeometry.Normals, meshGeometry.TextureCoordinates, meshGeometry.Indices, out t1, out t2); meshGeometry.Tangents = t1; meshGeometry.BiTangents = t2; }
/// <summary> /// Updates the model in the 3D viewport /// </summary> /// <param name="mdlData">The model data</param> /// <param name="textureDataDictionary">The texture dictionary for the model</param> public void UpdateModel(XivMdl mdlData, Dictionary <int, ModelTextureData> textureDataDictionary) { SharpDX.BoundingBox?boundingBox = null; var totalMeshCount = mdlData.LoDList[0].MeshCount + mdlData.LoDList[0].ExtraMeshCount; for (var i = 0; i < totalMeshCount; i++) { var meshData = mdlData.LoDList[0].MeshDataList[i].VertexData; var meshGeometry3D = new MeshGeometry3D { Positions = new Vector3Collection(meshData.Positions), Normals = new Vector3Collection(meshData.Normals), Indices = new IntCollection(meshData.Indices), Colors = new Color4Collection(meshData.Colors4), TextureCoordinates = new Vector2Collection(meshData.TextureCoordinates0), }; try { MeshBuilder.ComputeTangents(meshGeometry3D); } catch { Debug.WriteLine($"Unable to compute tangents for mesh {i}"); } if (meshData.BiNormals != null && meshData.BiNormals.Count > 0) { meshGeometry3D.BiTangents = new Vector3Collection(meshData.BiNormals); } var textureData = textureDataDictionary[mdlData.LoDList[0].MeshDataList[i].MeshInfo.MaterialIndex]; Stream diffuse = null, specular = null, normal = null, alpha = null, emissive = null; if (textureData.Diffuse != null && textureData.Diffuse.Length > 0) { using (var img = Image.LoadPixelData <Rgba32>(textureData.Diffuse, textureData.Width, textureData.Height)) { diffuse = new MemoryStream(); img.Save(diffuse, new PngEncoder()); } streamList.Add(diffuse); } if (textureData.Specular != null && textureData.Specular.Length > 0) { using (var img = Image.LoadPixelData <Rgba32>(textureData.Specular, textureData.Width, textureData.Height)) { specular = new MemoryStream(); img.Save(specular, new PngEncoder()); } streamList.Add(specular); } if (textureData.Normal != null && textureData.Normal.Length > 0) { using (var img = Image.LoadPixelData <Rgba32>(textureData.Normal, textureData.Width, textureData.Height)) { normal = new MemoryStream(); img.Save(normal, new PngEncoder()); } streamList.Add(normal); } if (textureData.Alpha != null && textureData.Alpha.Length > 0) { using (var img = Image.LoadPixelData <Rgba32>(textureData.Alpha, textureData.Width, textureData.Height)) { alpha = new MemoryStream(); img.Save(alpha, new PngEncoder()); } streamList.Add(alpha); } if (textureData.Emissive != null && textureData.Emissive.Length > 0) { using (var img = Image.LoadPixelData <Rgba32>(textureData.Emissive, textureData.Width, textureData.Height)) { emissive = new MemoryStream(); img.Save(emissive, new PngEncoder()); } streamList.Add(emissive); } var material = new PhongMaterial { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = 1f, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, SpecularColorMap = specular, NormalMap = normal, EmissiveMap = emissive }; var mgm3d = new CustomMeshGeometryModel3D { Geometry = meshGeometry3D, Material = material, IsBody = mdlData.LoDList[0].MeshDataList[i].IsBody }; boundingBox = meshGeometry3D.Bound; mgm3d.CullMode = Properties.Settings.Default.Cull_Mode.Equals("None") ? CullMode.None : CullMode.Back; Models.Add(mgm3d); } SpecularShine = 1; var center = boundingBox.GetValueOrDefault().Center; _lightX = center.X; _lightY = center.Y; _lightZ = center.Z; Light3Direction = new Vector3D(_lightX, _lightY, _lightZ); Camera.UpDirection = new Vector3D(0, 1, 0); Camera.CameraInternal.PropertyChanged += CameraInternal_PropertyChanged; }
public void LoadOsp() { //ModelGeometry已經有幾何模型存在內部 及 阻擋檔案不存在的情況 if (this.IsLoaded || !System.IO.File.Exists(FilePath)) { return; } //利用helixtoolkit.wpf裡面提供的StlReader讀檔案,後續要轉成wpf.sharpdx可用的格式 StLReader reader = new HelixToolkit.Wpf.StLReader(); this.ModelContainer = reader.Read(FilePath); var geometryModel = this.ModelContainer.Children[0] as System.Windows.Media.Media3D.GeometryModel3D; var mesh = geometryModel.Geometry as System.Windows.Media.Media3D.MeshGeometry3D; //MIP產生的OSP一定是六個點 if (mesh.Positions.Count != 6) { return; } this.OspOriNormal = new Vector3D(mesh.Normals[0].X, mesh.Normals[0].Y, mesh.Normals[0].Z); this.OspOriNormal.Normalize();//將上述向量正規化 this.OspPlanePoint = mesh.Positions[0]; //設定模型幾何形狀 HelixToolkit.Wpf.SharpDX.MeshGeometry3D modelGeometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); modelGeometry.Normals = new Vector3Collection(); modelGeometry.Positions = new Vector3Collection(); modelGeometry.Indices = new IntCollection(); //將從stlreader讀到的資料轉入 foreach (Point3D position in mesh.Positions) { modelGeometry.Positions.Add(new Vector3( Convert.ToSingle(position.X) , Convert.ToSingle(position.Y) , Convert.ToSingle(position.Z))); } modelGeometry.Colors = new Color4Collection(); for (int i = 0; i < mesh.Positions.Count; i++) { modelGeometry.Colors.Add(new Color4(0.1f, 0.1f, 0.8f, 0.2f)); } foreach (Vector3D normal in mesh.Normals) { modelGeometry.Normals.Add(new Vector3( Convert.ToSingle(normal.X) , Convert.ToSingle(normal.Y) , Convert.ToSingle(normal.Z))); } foreach (Int32 triangleindice in mesh.TriangleIndices) { modelGeometry.Indices.Add(triangleindice); } this.Geometry = modelGeometry; SetOspMaterial(); this.Transform = new MatrixTransform3D(); this.IsLoaded = true; }
/// <summary> /// Appends the specified mesh. /// </summary> /// <param name="mesh"> /// The mesh. /// </param> public void Append(MeshGeometry3D mesh) { if (mesh == null) { throw new ArgumentNullException("mesh"); } this.Append(mesh.Positions, mesh.Indices, mesh.Normals, mesh.TextureCoordinates); }
//用來輸入文字文件,然後輸出球的模型檔案 private void SaveBall() { string path = "D:\\Desktop\\新文字文件.txt"; try { string fileContent = File.ReadAllText(path); string[] contentArray = fileContent.Split((string[])null, StringSplitOptions.RemoveEmptyEntries); float[] pointInfo = Array.ConvertAll(contentArray, float.Parse); if (pointInfo.Length % 3 != 0) { throw new Exception(); } var ballContainer = new HelixToolkit.Wpf.SharpDX.MeshBuilder(); for (int i = 0; i < pointInfo.Length / 3; i++) { ballContainer.AddSphere(new Vector3(pointInfo[i * 3], pointInfo[i * 3 + 1], pointInfo[i * 3 + 2]), 1.5); } System.Windows.Media.Media3D.MeshGeometry3D ballMesh = new System.Windows.Media.Media3D.MeshGeometry3D { Positions = new Point3DCollection(), Normals = new Vector3DCollection(), TriangleIndices = new Int32Collection() }; HelixToolkit.Wpf.SharpDX.MeshGeometry3D geometry = ballContainer.ToMeshGeometry3D(); foreach (Vector3 position in geometry.Positions) { ballMesh.Positions.Add(new Point3D(position.X, position.Y, position.Z)); } foreach (Vector3 normal in geometry.Normals) { ballMesh.Normals.Add(new Vector3D(normal.X, normal.Y, normal.Z)); } foreach (int triangleindice in geometry.TriangleIndices) { ballMesh.TriangleIndices.Add(triangleindice); } System.Windows.Media.Media3D.GeometryModel3D ballModel = new System.Windows.Media.Media3D.GeometryModel3D { Geometry = ballMesh, }; Model3DGroup ballGroup = new Model3DGroup(); ballGroup.Children.Add(ballModel); StlExporter export1 = new StlExporter(); string name1 = "ball.stl"; using (var fileStream = File.Create("D:\\Desktop\\" + name1)) { export1.Export(ballGroup, fileStream); } } catch { System.Windows.MessageBox.Show("點的讀取錯誤"); } }
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; }
internal MeshTemplate(IGeometryModel model, IGeometryMesh mesh) { submeshCount = mesh.Submeshes.Count; matIndex = new int[submeshCount]; submeshes = new Helix.MeshGeometry3D[submeshCount]; var texMatrix = SharpDX.Matrix.Identity; var boundsMatrix = SharpDX.Matrix.Identity; if (mesh.BoundsIndex >= 0) { var bounds = model.Bounds[mesh.BoundsIndex.Value]; boundsMatrix = bounds.ToMatrix3(); texMatrix = bounds.ToMatrix2(); } for (int i = 0; i < submeshCount; i++) { var sub = mesh.Submeshes[i]; matIndex[i] = sub.MaterialIndex; var subIndices = mesh.Indicies.Skip(sub.IndexStart).Take(sub.IndexLength).ToList(); if (mesh.IndexFormat == IndexFormat.TriangleStrip) { subIndices = subIndices.Unstrip().ToList(); } var vertStart = subIndices.Min(); var vertLength = subIndices.Max() - vertStart + 1; var subVerts = mesh.Vertices.Skip(vertStart).Take(vertLength); IEnumerable <SharpDX.Vector3> subPositions; if (boundsMatrix.IsIdentity) { subPositions = subVerts.Select(v => v.Position[0].ToVector3()); } else { subPositions = subVerts.Select(v => SharpDX.Vector3.TransformCoordinate(v.Position[0].ToVector3(), boundsMatrix)); } IEnumerable <SharpDX.Vector2> subTexcoords; if (texMatrix.IsIdentity) { subTexcoords = subVerts.Select(v => v.TexCoords[0].ToVector2()); } else { subTexcoords = subVerts.Select(v => SharpDX.Vector2.TransformCoordinate(v.TexCoords[0].ToVector2(), texMatrix)); } submeshes[i] = new Helix.MeshGeometry3D { Indices = new Helix.IntCollection(subIndices.Select(j => j - vertStart)), Positions = new Helix.Vector3Collection(subPositions), TextureCoordinates = new Helix.Vector2Collection(subTexcoords) }; if (mesh.Vertices[0].Normal.Count > 0) { var subNormals = subVerts.Select(v => new SharpDX.Vector3(v.Normal[0].X, v.Normal[0].Y, v.Normal[0].Z)); submeshes[i].Normals = new Helix.Vector3Collection(subNormals); } submeshes[i].UpdateOctree(); } }
/// <summary> /// load進模型檔案 /// </summary> public void LoadModel() { //ModelGeometry已經有幾何模型存在內部 及 阻擋檔案不存在的情況 if (IsLoaded || !File.Exists(FilePath)) { return; } //利用helixtoolkit.wpf裡面提供的StlReader讀檔案,後續要轉成wpf.sharpdx可用的格式 StLReader reader = new StLReader(); ModelContainer = reader.Read(FilePath); Rect3D bound = ModelContainer.Bounds; ModelCenter = new Vector3(Convert.ToSingle(bound.X + bound.SizeX / 2.0), Convert.ToSingle(bound.Y + bound.SizeY / 2.0), Convert.ToSingle(bound.Z + bound.SizeZ / 2.0)); HelixToolkit.Wpf.SharpDX.MeshGeometry3D modelGeometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D { Normals = new Vector3Collection(), Positions = new Vector3Collection(), Indices = new IntCollection() }; foreach (Model3D model in ModelContainer.Children) { var geometryModel = model as GeometryModel3D; MeshGeometry3D mesh = geometryModel?.Geometry as MeshGeometry3D; if (mesh == null) { continue; } //將從stlreader讀到的資料轉入 foreach (Point3D position in mesh.Positions) { modelGeometry.Positions.Add(new Vector3( Convert.ToSingle(position.X) , Convert.ToSingle(position.Y) , Convert.ToSingle(position.Z))); } foreach (Vector3D normal in mesh.Normals) { modelGeometry.Normals.Add(new Vector3( Convert.ToSingle(normal.X) , Convert.ToSingle(normal.Y) , Convert.ToSingle(normal.Z))); } foreach (Int32 triangleindice in mesh.TriangleIndices) { modelGeometry.Indices.Add(triangleindice); } } SetBoneMaterial(); Geometry = modelGeometry; IsLoaded = true; }
public static void OutputObj(string ifcId, MeshGeometry3D rep) { using (var writer = new StreamWriter("./" + ifcId + ".obj")) { for (int i = 0, count = rep.Positions.Count; i < count; i++) { writer.WriteLine("v {0} {1} {2}", rep.Positions[i].X, rep.Positions[i].Y, rep.Positions[i].Z); writer.WriteLine("vn {0} {1} {2}", rep.Normals[i].X, rep.Normals[i].Y, rep.Normals[i].Z); } var indices = rep.Indices.ToArray().Reverse().ToList();//HACK winding for (int i = 0, count = indices.Count / 3; i < count; i++) { writer.WriteLine("f {0}//{0} {1}//{1} {2}//{2}", indices[i * 3] + 1, indices[i * 3 + 1] + 1, indices[i * 3 + 2] + 1); } } }
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; } }
/// <summary> /// Updates the model in the 3D viewport /// </summary> /// <param name="mdlData">The model data</param> /// <param name="textureDataDictionary">The texture dictionary for the model</param> public void UpdateModel(XivMdl mdlData, Dictionary <int, ModelTextureData> textureDataDictionary) { SharpDX.BoundingBox?boundingBox = null; var totalMeshCount = mdlData.LoDList[0].MeshCount + mdlData.LoDList[0].ExtraMeshCount; for (var i = 0; i < totalMeshCount; i++) { var meshData = mdlData.LoDList[0].MeshDataList[i].VertexData; var meshGeometry3D = new MeshGeometry3D { Positions = meshData.Positions, Normals = meshData.Normals, Indices = meshData.Indices, TextureCoordinates = meshData.TextureCoordinates0, }; try { MeshBuilder.ComputeTangents(meshGeometry3D); } catch { Debug.WriteLine($"Unable to compute tangents for mesh {i}"); } if (meshData.BiNormals != null && meshData.BiNormals.Count > 0) { meshGeometry3D.BiTangents = meshData.BiNormals; } var textureData = textureDataDictionary[mdlData.LoDList[0].MeshDataList[i].MeshInfo.MaterialIndex]; Stream diffuse = null, specular = null, normal = null, alpha = null, emissive = null; var pixelSettings = new PixelReadSettings(textureData.Width, textureData.Height, StorageType.Char, PixelMapping.RGBA); if (textureData.Diffuse != null && textureData.Diffuse.Length > 0) { using (var image = new MagickImage(textureData.Diffuse, pixelSettings)) { diffuse = new MemoryStream(image.ToByteArray(MagickFormat.Bmp)); } } if (textureData.Specular != null && textureData.Specular.Length > 0) { using (var image = new MagickImage(textureData.Specular, pixelSettings)) { specular = new MemoryStream(image.ToByteArray(MagickFormat.Bmp)); } } if (textureData.Normal != null && textureData.Normal.Length > 0) { using (var image = new MagickImage(textureData.Normal, pixelSettings)) { normal = new MemoryStream(image.ToByteArray(MagickFormat.Bmp)); } } if (textureData.Alpha != null && textureData.Alpha.Length > 0) { using (var image = new MagickImage(textureData.Alpha, pixelSettings)) { alpha = new MemoryStream(image.ToByteArray(MagickFormat.Bmp)); } } if (textureData.Emissive != null && textureData.Emissive.Length > 0) { using (var image = new MagickImage(textureData.Emissive, pixelSettings)) { emissive = new MemoryStream(image.ToByteArray(MagickFormat.Bmp)); } } var material = new PhongMaterial { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = 1f, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, SpecularColorMap = specular, NormalMap = normal, EmissiveMap = emissive }; var mgm3d = new CustomMeshGeometryModel3D { Geometry = meshGeometry3D, Material = material, IsBody = mdlData.LoDList[0].MeshDataList[i].IsBody }; boundingBox = meshGeometry3D.Bound; mgm3d.CullMode = Properties.Settings.Default.Cull_Mode.Equals("None") ? CullMode.None : CullMode.Back; Models.Add(mgm3d); } SpecularShine = 1; var center = boundingBox.GetValueOrDefault().Center; _lightX = center.X; _lightY = center.Y; _lightZ = center.Z; Light3Direction = new Vector3D(_lightX, _lightY, _lightZ); Camera.UpDirection = new Vector3D(0, 1, 0); Camera.CameraInternal.PropertyChanged += CameraInternal_PropertyChanged; }
public void Clear() { points = null; mesh = null; lines = null; points = InitPointGeometry(); mesh = InitMeshGeometry(); lines = InitLineGeometry(); lineStripVertexCounts.Clear(); Transform = System.Windows.Media.Media3D.Matrix3D.Identity.ToArray(); IsSelected = false; DisplayLabels = false; colors = null; }
public override void Attach(IRenderHost host) { /// --- attach this.renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.CubeMap]; base.Attach(host); /// --- get variables this.vertexLayout = renderHost.EffectsManager.GetLayout(this.renderTechnique); this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); this.effectTransforms = new EffectTransformVariables(this.effect); /// -- attach cube map if (this.Filename != null) { /// -- attach texture using (var texture = Texture2D.FromFile <Texture2D>(this.Device, this.Filename)) { this.texCubeMapView = new ShaderResourceView(this.Device, texture); } this.texCubeMap = effect.GetVariableByName("texCubeMap").AsShaderResource(); this.texCubeMap.SetResource(this.texCubeMapView); this.bHasCubeMap = effect.GetVariableByName("bHasCubeMap").AsScalar(); this.bHasCubeMap.Set(true); /// --- set up geometry var sphere = new MeshBuilder(false, true, false); sphere.AddSphere(new Vector3(0, 0, 0)); this.geometry = sphere.ToMeshGeometry3D(); /// --- set up vertex buffer this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, CubeVertex.SizeInBytes, this.geometry.Positions.Select((x, ii) => new CubeVertex() { Position = new Vector4(x, 1f) }).ToArray()); /// --- set up index buffer this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array); /// --- set up rasterizer states var rasterStateDesc = new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsMultisampleEnabled = true, IsAntialiasedLineEnabled = true, IsFrontCounterClockwise = false, }; this.rasterState = new RasterizerState(this.Device, rasterStateDesc); /// --- set up depth stencil state var depthStencilDesc = new DepthStencilStateDescription() { DepthComparison = Comparison.LessEqual, DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All, IsDepthEnabled = true, }; this.depthStencilState = new DepthStencilState(this.Device, depthStencilDesc); } /// --- flush this.Device.ImmediateContext.Flush(); }
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); }
public int LoadModel(String FilePath) { MeshGeometryModel3D m_model = new MeshGeometryModel3D(); //ModelGeometry已經有幾何模型存在內部 及 阻擋檔案不存在的情況 if (/*IsLoaded ||*/ !File.Exists(FilePath)) ///What the F**k is IsLoaded ?????? { return(1); } //利用helixtoolkit.wpf裡面提供的StlReader讀檔案,後續要轉成wpf.sharpdx可用的格式 StLReader reader = new StLReader(); Model3DGroup ModelContainer = reader.Read(FilePath); Rect3D bound = ModelContainer.Bounds; var ModelCenter = new Vector3(Convert.ToSingle(bound.X + bound.SizeX / 2.0), Convert.ToSingle(bound.Y + bound.SizeY / 2.0), Convert.ToSingle(bound.Z + bound.SizeZ / 2.0)); HelixToolkit.Wpf.SharpDX.MeshGeometry3D modelGeometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D { Normals = new Vector3Collection(), Positions = new Vector3Collection(), Indices = new IntCollection() }; foreach (System.Windows.Media.Media3D.Model3D model in ModelContainer.Children) { var geometryModel = model as System.Windows.Media.Media3D.GeometryModel3D; System.Windows.Media.Media3D.MeshGeometry3D mesh = geometryModel?.Geometry as System.Windows.Media.Media3D.MeshGeometry3D; if (mesh == null) { continue; } //將從stlreader讀到的資料轉入 foreach (Point3D position in mesh.Positions) { modelGeometry.Positions.Add(new Vector3( Convert.ToSingle(position.X) , Convert.ToSingle(position.Y) , Convert.ToSingle(position.Z))); } int i = 0; foreach (Vector3D normal in mesh.Normals) { //Vector3D v1 = new Vector3D((modelGeometry.Positions[i + 1].X - modelGeometry.Positions[i].X), (modelGeometry.Positions[i + 1].Y - modelGeometry.Positions[i].Y), (modelGeometry.Positions[i + 1].Z - modelGeometry.Positions[i].Z)); //Vector3D v2 = new Vector3D((modelGeometry.Positions[i + 2].X - modelGeometry.Positions[i].X), (modelGeometry.Positions[i + 2].Y - modelGeometry.Positions[i].Y), (modelGeometry.Positions[i + 2].Z - modelGeometry.Positions[i].Z)); //Vector3D n = Vector3D.CrossProduct(v1, v2); //modelGeometry.Normals.Add(new Vector3( // Convert.ToSingle(n.X) // , Convert.ToSingle(n.Y) // , Convert.ToSingle(n.Z))); modelGeometry.Normals.Add(new Vector3( Convert.ToSingle(normal.X) , Convert.ToSingle(normal.Y) , Convert.ToSingle(normal.Z))); } foreach (Int32 triangleindice in mesh.TriangleIndices) { modelGeometry.Indices.Add(triangleindice); } // MessageBox.Show(mesh.Normals.Count.ToString()); } SetModelMaterial(m_model); m_model.Geometry = modelGeometry; ModelGroup.Children.Add(m_model); m_group.Add(m_model); ResetCameraPosition(bound); return(0); }
internal static MeshGeometry3D InitMeshGeometry() { var mesh = new MeshGeometry3D() { Positions = new Vector3Collection(), Indices = new IntCollection(), Colors = new Color4Collection(), Normals = new Vector3Collection(), TextureCoordinates = new Vector2Collection() }; return mesh; }
private void button_Click_2(object sender, RoutedEventArgs e) { //ball的模型 Model3DGroup ballGroup = new Model3DGroup(); foreach (BallModel model in MainViewModel.ProjData.BallCollection) { System.Windows.Media.Media3D.MeshGeometry3D ballMesh = new System.Windows.Media.Media3D.MeshGeometry3D { Positions = new Point3DCollection(), Normals = new Vector3DCollection(), TriangleIndices = new Int32Collection() }; HelixToolkit.Wpf.SharpDX.MeshGeometry3D geometry = model.Geometry as HelixToolkit.Wpf.SharpDX.MeshGeometry3D; if (geometry == null) { return; } foreach (Vector3 position in geometry.Positions) { ballMesh.Positions.Add(new Point3D(position.X, position.Y, position.Z)); } foreach (Vector3 normal in geometry.Normals) { ballMesh.Normals.Add(new Vector3D(normal.X, normal.Y, normal.Z)); } foreach (int triangleindice in geometry.TriangleIndices) { ballMesh.TriangleIndices.Add(triangleindice); } System.Windows.Media.Media3D.GeometryModel3D ballModel = new System.Windows.Media.Media3D.GeometryModel3D { Geometry = ballMesh, }; ballGroup.Children.Add(ballModel); } StlExporter export1 = new StlExporter(); string name1 = "ball.stl"; using (var fileStream = File.Create("D:\\Desktop\\test\\" + name1)) { export1.Export(ballGroup, fileStream); } //存球資料 FileStream fs = new FileStream("D:\\Desktop\\test\\balldata.txt", FileMode.Create); StreamWriter sw = new StreamWriter(fs); foreach (BallModel model in MainViewModel.ProjData.BallCollection) { sw.Write(model.BallCenter.X + " " + model.BallCenter.Y + " " + model.BallCenter.Z + "\r\n"); } //清空緩衝區 sw.Flush(); //關閉流 sw.Close(); fs.Close(); }
/// <summary> /// Generate a simple Polygon and then triangulate it. /// The Result is then Displayed. /// </summary> /// <param name="sender">The Sender (i.e. the Button)</param> /// <param name="e">The routet Event Args</param> private void generatePolygonButton_Click(object sender, RoutedEventArgs e) { // Generate random Polygon var random = new Random(); var cnt = mViewModel.PointCount; mPolygonPoints = new List <Vector2>(); var angle = 0f; var angleDiff = 2f * (Single)Math.PI / cnt; var radius = 4f; // Random Radii for the Polygon var radii = new List <float>(); var innerRadii = new List <float>(); for (int i = 0; i < cnt; i++) { radii.Add(random.NextFloat(radius * 0.9f, radius * 1.1f)); innerRadii.Add(random.NextFloat(radius * 0.2f, radius * 0.3f)); } var hole1 = new List <Vector2>(); var hole2 = new List <Vector2>(); var holeDistance = 2f; var holeAngle = random.NextFloat(0, (float)Math.PI * 2); var cos = (float)Math.Cos(holeAngle); var sin = (float)Math.Sin(holeAngle); var offset1 = new Vector2(holeDistance * cos, holeDistance * sin); var offset2 = new Vector2(-holeDistance * cos, -holeDistance * sin); for (int i = 0; i < cnt; i++) { // Flatten a bit var radiusUse = radii[i]; mPolygonPoints.Add(new Vector2(radii[i] * (Single)Math.Cos(angle), radii[i] * (Single)Math.Sin(angle))); hole1.Add(offset1 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); hole2.Add(offset2 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); angle += angleDiff; } var holes = new List <List <Vector2> >() { hole1, hole2 }; // Triangulate and measure the Time needed for the Triangulation var before = DateTime.Now; var sLTI = SweepLinePolygonTriangulator.Triangulate(mPolygonPoints, holes); var after = DateTime.Now; // Generate the Output var geometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); geometry.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); geometry.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); foreach (var point in mPolygonPoints.Union(holes.SelectMany(h => h))) { geometry.Positions.Add(new Vector3(point.X, 0, point.Y + 5)); geometry.Normals.Add(new Vector3(0, 1, 0)); } geometry.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(sLTI); triangulatedPolygon.Geometry = geometry; var lb = new LineBuilder(); for (int i = 0; i < sLTI.Count; i += 3) { lb.AddLine(geometry.Positions[sLTI[i]], geometry.Positions[sLTI[i + 1]]); lb.AddLine(geometry.Positions[sLTI[i + 1]], geometry.Positions[sLTI[i + 2]]); lb.AddLine(geometry.Positions[sLTI[i + 2]], geometry.Positions[sLTI[i]]); } mViewModel.LineGeometry = lb.ToLineGeometry3D(); // Set the Lines if activated if (mViewModel.ShowTriangleLines) { lineTriangulatedPolygon.Geometry = mViewModel.LineGeometry; } else { lineTriangulatedPolygon.Geometry = null; } // Set the InfoLabel Text var timeNeeded = (after - before).TotalMilliseconds; infoLabel.Content = String.Format("Last triangulation of {0} Points took {1:0.##} Milliseconds!", triangulatedPolygon.Geometry.Positions.Count, timeNeeded); }
/// <summary> /// Generate a simple Polygon and then triangulate it. /// The Result is then Displayed. /// </summary> /// <param name="sender">The Sender (i.e. the Button)</param> /// <param name="e">The routet Event Args</param> private void generatePolygonButton_Click(object sender, RoutedEventArgs e) { // Generate random Polygon var random = new Random(); var cnt = mViewModel.PointCount; mPolygonPoints = new List <Vector2>(); var angle = 0f; var angleDiff = 2f * (Single)Math.PI / cnt; var radius = 4f; // Random Radii for the Polygon var radii = new List <float>(); for (int i = 0; i < cnt; i++) { radii.Add(radius + random.NextFloat(-radius, radius)); } for (int i = 0; i < cnt; i++) { var last = i > 0 ? i - 1 : cnt - 1; var next = i < cnt - 1 ? i + 1 : 0; // Flatten a bit var radiusUse = radii[last] * 0.25f + radii[i] * 0.5f + radii[next] * 0.25f; mPolygonPoints.Add(new Vector2(radiusUse * (Single)Math.Cos(angle), radiusUse * (Single)Math.Sin(angle))); angle += angleDiff; } // Triangulate and measure the Time needed for the Triangulation var before = DateTime.Now; var sLTI = SweepLinePolygonTriangulator.Triangulate(mPolygonPoints); var after = DateTime.Now; // Generate the Output var geometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); geometry.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); geometry.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); foreach (var point in mPolygonPoints) { geometry.Positions.Add(new Vector3(point.X, 0, point.Y + 5)); geometry.Normals.Add(new Vector3(0, 1, 0)); } geometry.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(sLTI); triangulatedPolygon.Geometry = geometry; var lb = new LineBuilder(); for (int i = 0; i < sLTI.Count; i += 3) { lb.AddLine(geometry.Positions[sLTI[i]], geometry.Positions[sLTI[i + 1]]); lb.AddLine(geometry.Positions[sLTI[i + 1]], geometry.Positions[sLTI[i + 2]]); lb.AddLine(geometry.Positions[sLTI[i + 2]], geometry.Positions[sLTI[i]]); } mViewModel.LineGeometry = lb.ToLineGeometry3D(); // Set the Lines if activated if (mViewModel.ShowTriangleLines) { lineTriangulatedPolygon.Geometry = mViewModel.LineGeometry; } else { lineTriangulatedPolygon.Geometry = null; } // Set the InfoLabel Text var timeNeeded = (after - before).TotalMilliseconds; infoLabel.Content = String.Format("Last triangulation of {0} Points took {1:0.##} Milliseconds!", triangulatedPolygon.Geometry.Positions.Count, timeNeeded); }
public override void Attach(IRenderHost host) { /// --- attach this.renderTechnique = Techniques.RenderCubeMap; base.Attach(host); /// --- get variables this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique); this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); this.effectTransforms = new EffectTransformVariables(this.effect); /// -- attach cube map if (this.Filename != null) { /// -- attach texture using (var texture = Texture2D.FromFile<Texture2D>(this.Device, this.Filename)) { this.texCubeMapView = new ShaderResourceView(this.Device, texture); } this.texCubeMap = effect.GetVariableByName("texCubeMap").AsShaderResource(); this.texCubeMap.SetResource(this.texCubeMapView); this.bHasCubeMap = effect.GetVariableByName("bHasCubeMap").AsScalar(); this.bHasCubeMap.Set(true); /// --- set up geometry var sphere = new MeshBuilder(false,true,false); sphere.AddSphere(new Vector3(0, 0, 0)); this.geometry = sphere.ToMeshGeometry3D(); /// --- set up vertex buffer this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, CubeVertex.SizeInBytes, this.geometry.Positions.Select((x, ii) => new CubeVertex() { Position = new Vector4(x, 1f) }).ToArray()); /// --- set up index buffer this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array); /// --- set up rasterizer states var rasterStateDesc = new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsMultisampleEnabled = true, IsAntialiasedLineEnabled = true, IsFrontCounterClockwise = false, }; this.rasterState = new RasterizerState(this.Device, rasterStateDesc); /// --- set up depth stencil state var depthStencilDesc = new DepthStencilStateDescription() { DepthComparison = Comparison.LessEqual, DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All, IsDepthEnabled = true, }; this.depthStencilState = new DepthStencilState(this.Device, depthStencilDesc); } /// --- flush this.Device.ImmediateContext.Flush(); }
/// <summary> /// Generate a simple Polygon and then triangulate it. /// The Result is then Displayed. /// </summary> /// <param name="sender">The Sender (i.e. the Button)</param> /// <param name="e">The routet Event Args</param> private void generatePolygonButton_Click(object sender, RoutedEventArgs e) { // Generate random Polygon var random = new Random(); var cnt = mViewModel.PointCount; mPolygonPoints = new List<Vector2>(); var angle = 0f; var angleDiff = 2f * (Single)Math.PI / cnt; var radius = 4f; // Random Radii for the Polygon var radii = new List<float>(); var innerRadii = new List<float>(); for (int i = 0; i < cnt; i++) { radii.Add(random.NextFloat(radius * 0.9f, radius * 1.1f)); innerRadii.Add(random.NextFloat(radius * 0.2f, radius * 0.3f)); } var hole1 = new List<Vector2>(); var hole2 = new List<Vector2>(); var holeDistance = 2f; var holeAngle = random.NextFloat(0, (float)Math.PI * 2); var cos = (float)Math.Cos(holeAngle); var sin = (float)Math.Sin(holeAngle); var offset1 = new Vector2(holeDistance * cos, holeDistance * sin); var offset2 = new Vector2(-holeDistance * cos, -holeDistance * sin); for (int i = 0; i < cnt; i++) { // Flatten a bit var radiusUse = radii[i]; mPolygonPoints.Add(new Vector2(radii[i] * (Single)Math.Cos(angle), radii[i] * (Single)Math.Sin(angle))); hole1.Add(offset1 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); hole2.Add(offset2 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); angle += angleDiff; } var holes = new List<List<Vector2>>() { hole1, hole2 }; // Triangulate and measure the Time needed for the Triangulation var before = DateTime.Now; var sLTI = SweepLinePolygonTriangulator.Triangulate(mPolygonPoints, holes); var after = DateTime.Now; // Generate the Output var geometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); geometry.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); geometry.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); foreach (var point in mPolygonPoints.Union(holes.SelectMany(h => h))) { geometry.Positions.Add(new Vector3(point.X, 0, point.Y + 5)); geometry.Normals.Add(new Vector3(0, 1, 0)); } geometry.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(sLTI); triangulatedPolygon.Geometry = geometry; var lb = new LineBuilder(); for (int i = 0; i < sLTI.Count; i += 3) { lb.AddLine(geometry.Positions[sLTI[i]], geometry.Positions[sLTI[i + 1]]); lb.AddLine(geometry.Positions[sLTI[i + 1]], geometry.Positions[sLTI[i + 2]]); lb.AddLine(geometry.Positions[sLTI[i + 2]], geometry.Positions[sLTI[i]]); } mViewModel.LineGeometry = lb.ToLineGeometry3D(); // Set the Lines if activated if (mViewModel.ShowTriangleLines) { lineTriangulatedPolygon.Geometry = mViewModel.LineGeometry; } else { lineTriangulatedPolygon.Geometry = null; } // Set the InfoLabel Text var timeNeeded = (after - before).TotalMilliseconds; infoLabel.Content = String.Format("Last triangulation of {0} Points took {1:0.##} Milliseconds!", triangulatedPolygon.Geometry.Positions.Count, timeNeeded); }
public override void Detach() { if (!this.IsAttached) return; this.bHasCubeMap.Set(false); this.effectTechnique = null; this.effectTechnique = null; this.vertexLayout = null; this.geometry = null; Disposer.RemoveAndDispose(ref this.vertexBuffer); Disposer.RemoveAndDispose(ref this.indexBuffer); Disposer.RemoveAndDispose(ref this.texCubeMap); Disposer.RemoveAndDispose(ref this.texCubeMapView); Disposer.RemoveAndDispose(ref this.bHasCubeMap); Disposer.RemoveAndDispose(ref this.rasterState); Disposer.RemoveAndDispose(ref this.depthStencilState); Disposer.RemoveAndDispose(ref this.effectTransforms); base.Detach(); }
/// <summary> /// Create a Mesh, with found props /// </summary> /// <param name="positions"></param> /// <param name="textureCoordinates"></param> /// <param name="triangleIndices"></param> /// <param name="normals"></param> /// <param name="tangents"></param> /// <param name="bitangents"></param> /// <param name="material"></param> private void CreateMesh(Vector3Collection positions, Vector2Collection textureCoordinates, IntCollection triangleIndices, out Vector3Collection normals, out Vector3Collection tangents, out Vector3Collection bitangents,Material material) { ComputeNormals(positions, triangleIndices, out normals); if (textureCoordinates == null) { textureCoordinates = new Vector2Collection(); foreach(var pos in positions) { textureCoordinates.Add(Vector2.One); } } MeshBuilder.ComputeTangents(positions, normals, textureCoordinates, triangleIndices, out tangents, out bitangents); MeshGeometry3D mesh = new MeshGeometry3D() { Positions = positions, Normals = normals, TextureCoordinates = textureCoordinates, Indices = triangleIndices, Tangents = tangents, BiTangents = bitangents }; Object3D ob3d = new Object3D(); ob3d.Geometry = mesh; ob3d.Material = material; ob3d.Transform = Matrix.Identity; ob3d.Name = "Default"; this.obGroup.Add(ob3d); }