public static IEnumerable <IFileGeometry3D> ReadStl(FileInfo file) { var builder = new SimpleMeshBuilder(); var stl = new STLReader(); IOReadResult res; var reader = new ASCIIBinarySTLParser(); using (var fs = file.OpenRead()) { reader.Read(fs); //using (var br = new BinaryReader(fs)) { // res = stl.Read(br, new ReadOptions { }, builder); //} } return(reader.Geometry); // if (res.code == IOCode.Ok && builder.Meshes.Any()) { // var mesh = builder.Meshes.Single(); // return new[] { // new MeshData("STL", // mesh.GetVertexArrayFloat().ToVector3List().AsReadOnly(), // mesh.HasVertexNormals ? // mesh.GetVertexNormalArray().ToVector3List().AsReadOnly() // : new ReadOnlyCollection<Vector3>(new List<Vector3>()), // mesh.GetTriangleArray().AsReadOnly(), // mesh.HasVertexUVs ? // mesh.GetVertexUVArray().ToVector2List().AsReadOnly() // : new ReadOnlyCollection<Vector2>(new List<Vector2>()), // mesh.HasVertexColors ? // mesh.GetVertexColorArray().ToVector3List().AsReadOnly() // : new ReadOnlyCollection<Vector3>(new List<Vector3>()) // ) // }; // } // throw new Exception("Can't read STL."); }
private void OpenFile(object sender, RoutedEventArgs e) { string FilePath = null; OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == true) { FilePath = openFileDialog.FileName; STLReader stlReader = new STLReader(openFileDialog.FileName); meshArray = stlReader.ReadFile(); TriangleMesh[] normalArray = new TriangleMesh[meshArray.Length]; //Перобразование в лист Point3D for (int i = 0; i < meshArray.Length; i++) { point.Add(new Point3D(meshArray[i].vert1.x, meshArray[i].vert1.y, meshArray[i].vert1.z)); point.Add(new Point3D(meshArray[i].vert2.x, meshArray[i].vert2.y, meshArray[i].vert2.z)); point.Add(new Point3D(meshArray[i].vert3.x, meshArray[i].vert3.y, meshArray[i].vert3.z)); } //удаление дубликатов точек list = point.Distinct().ToList <Point3D>(); //Преобразование в модель device = create3dmodel(list); device3D.Content = device; Cutt.IsEnabled = true; Count.IsEnabled = true; //-------------------------------------- viewPort3d.Children.Add(device3D); viewPort3d.Children.Add(new SunLight()); viewPort3d.ZoomExtents(); } }
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { if (this.Page.Request.Files.Count > 0) { UploadFileInfo fi = new UploadFileInfo(); string fileName = GetNewFilename("STL", "stl"); string fileFullPath = Server.MapPath(Path.Combine(uploadPath, fileName)); fi.gg_tj = fi.gg_bmj = fi.gg_length = fi.gg_width = fi.gg_height = fi.code = fi.error = ""; fi.source_name = this.Page.Request.Files[0].FileName; fi.file_name = this.Page.ResolveUrl("~") + uploadPath + "/" + fileName; fi.success = false; try { this.Page.Request.Files[0].SaveAs(fileFullPath); STLReader stl = new STLReader(fileFullPath); if (stl.IsValid) { fi.gg_tj = stl.Volume.ToString(); //fi.gg_bmj = stl.SurfaceArea.ToString(); fi.gg_length = stl.Size.Length.ToString(); fi.gg_width = stl.Size.Width.ToString(); fi.gg_height = stl.Size.Height.ToString(); fi.success = true; } else { fi.error = stl.ErrorMessage; } } catch (Exception ex) { fi.code = "-1"; fi.error = ex.Message; } string jsonString; JavaScriptSerializer serializer = new JavaScriptSerializer(); List <UploadFileInfo> jsonList = new List <UploadFileInfo>(); jsonList.Add(fi); jsonString = serializer.Serialize(jsonList); jsonString = jsonString.Replace("[", "").Replace("]", ""); this.Context.Response.Clear(); this.Context.Response.Write(jsonString); this.Context.Response.Flush(); this.Context.Response.End(); } } }
static private void TestSTLReader() { var Part = new STLReader("Sk20.stl"); int MaxCount = 512; var SubDivisions = Part.RecursiveSplit(MaxCount); foreach (var item in SubDivisions) { if (item.TriangleCount > MaxCount) { throw new Exception("This must be less than " + MaxCount.ToString() + " Triangles"); } } int NumPoints = 512 * 100; var Mesher = new PointInserter(SubDivisions.ToArray()); var Pts = Mesher.GetPointsGPU(NumPoints); }
private void fileSelectBt_Click(object sender, EventArgs e) { OpenFileDialog stldosyaSec = new OpenFileDialog(); stldosyaSec.Filter = "STL Files|*.stl;*.txt;"; if (stldosyaSec.ShowDialog() == DialogResult.OK) { dosyaSecTxb.Text = stldosyaSec.SafeFileName; STLReader stlReader = new STLReader(stldosyaSec.FileName); TriangleMesh[] meshArray = stlReader.ReadFile(); modelVAO = new Batu_GL.VAO_TRIANGLES(); STLExport stlExporter = new STLExport(); modelVAO.parameterArray = stlExporter.Get_Mesh_Vertices(meshArray); modelVAO.normalArray = stlExporter.Get_Mesh_Normals(meshArray); modelVAO.color = Color.CadetBlue; if (!stlReader.Get_Process_Error()) { rotation = 0; drawTimer.Enabled = true; fileSelectBt.BackColor = Color.DeepSkyBlue; } else { drawTimer.Enabled = false; fileSelectBt.BackColor = Color.Tomato; /* if there is an error, deinitialize the gl monitor to clear the screen */ glController.glInit(monitor, Batu_GL.Ortho_Mode.CENTER); monitor.SwapBuffers(); } } else { // intentionally left blank } }
public List <Mesh> LoadMeshes() { using var stream = File.OpenRead(_filePath); using var binaryReader = new BinaryReader(stream); var builder = new DMesh3Builder(); var reader = new STLReader(); var result = reader.Read(binaryReader, ReadOptions.Defaults, builder); binaryReader.Close(); stream.Close(); if (result.code != IOCode.Ok) { throw new Exception("Something went wrong when reading the STL file!"); } return(builder.Meshes.Select(m => new Mesh(m)) .ToList()); }
private void ReadSelectedFile(string fileName) { STLReader stlReader = new STLReader(fileName); TriangleMesh[] meshArray = stlReader.ReadFile(); modelVAO = new Batu_GL.VAO_TRIANGLES(); modelVAO.parameterArray = STLExport.Get_Mesh_Vertices(meshArray); modelVAO.normalArray = STLExport.Get_Mesh_Normals(meshArray); modelVAO.color = Color.Crimson; minPos = stlReader.GetMinMeshPosition(meshArray); maxPos = stlReader.GetMaxMeshPosition(meshArray); orb.Reset_Orientation(); orb.Reset_Pan(); orb.Reset_Scale(); if (stlReader.Get_Process_Error()) { modelVAO = null; /* if there is an error, deinitialize the gl monitor to clear the screen */ Batu_GL.Configure(GL_Monitor, Batu_GL.Ortho_Mode.CENTER); GL_Monitor.SwapBuffers(); } }
static void Main(string[] args) { STLReader reader = new STLReader("C:/Users/Becarios/Documents/Ferreyra/Scripts/CenterlineComputation/Centerline/Meshes/testmesh.stl"); TriangleMesh[] mesh = reader.ReadFile(); Vertex3[] vertices = new Vertex3[3 * mesh.Length]; int j = 0; for (int i = 0; i < mesh.Length; i++) { vertices[j] = new Vertex3(mesh[i].vert1.x, mesh[i].vert1.y, mesh[i].vert1.z); vertices[j + 1] = new Vertex3(mesh[i].vert2.x, mesh[i].vert2.y, mesh[i].vert2.z); vertices[j + 2] = new Vertex3(mesh[i].vert3.x, mesh[i].vert3.y, mesh[i].vert3.z); j += 3; } DelaunayTriangulation3 delaunay = new DelaunayTriangulation3(); delaunay.Generate(vertices); //VoronoiMesh3 voronoi = new VoronoiMesh3(); //voronoi.Generate(vertices); //SAVE CENTROIDS using (StreamWriter writetext = new StreamWriter("C:/Users/Becarios/Documents/Ferreyra/Scripts/CenterlineComputation/DelaunayCentroids.txt")) { for (int k = 0; k < delaunay.Cells.Count; k++) { writetext.WriteLine(delaunay.Cells[k].CircumCenter.X + " " + delaunay.Cells[k].CircumCenter.Y + " " + delaunay.Cells[k].CircumCenter.Z + " " + delaunay.Cells[k].Radius); } } }
// Load STL file public bool load_stl(string model_file) { //Util.alert(MODULE + " Loading STL: " + model_file); Vector3 min, max; try { STLReader stl_reader = new STLReader(model_file);; mesh = stl_reader.ReadFile(); // Determine bounding box min = stl_reader.GetMinMeshPosition(mesh); max = stl_reader.GetMaxMeshPosition(mesh); } catch (Exception ex) { Util.error(MODULE + "Unable to load " + model_file + " " + ex.Message); return(true); } //Util.alert(MODULE + " Mesh triangles: " + mesh.Length); // ReCenter Vector3 center = new Vector3((min.X + max.X) / 2.0f, (min.Y + max.Y) / 2.0f, (min.Z + max.Z) / 2.0f); for (int i = 0; i < mesh.Length; i++) { mesh[i].vert1.X -= center.X; mesh[i].vert1.Y -= center.Y; mesh[i].vert1.Z -= center.Z; mesh[i].vert2.X -= center.X; mesh[i].vert2.Y -= center.Y; mesh[i].vert2.Z -= center.Z; mesh[i].vert3.X -= center.X; mesh[i].vert3.Y -= center.Y; mesh[i].vert3.Z -= center.Z; } return(false); }
public PrintModule(IDbConnection db, ILog log, IRootPathProvider pathProvider) : base("/print") { Get["/"] = parameters => { base.Page.Title = "3D打印"; return(View["Index", base.Model]); }; Get["/materials"] = parameters => { var materials = db.Select <Material>(q => q.State == 0); return(Response.AsJson(materials)); //return Response.AsJson(( new List<string> { "Foo","Bar","Hello","World"}).Select(i => new { // message = i //})); }; Post["/upload"] = parameters => { string uploadDirectory; string filepath = ""; if (Context.CurrentUser == null) { uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "temp"); filepath = "/Content/uploads/temp/"; } else { uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "3d"); filepath = "/Content/uploads/3d/"; } if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } string _filename = ""; string filename = ""; List <Models.File> files = new List <Models.File>(); foreach (var file in Request.Files) { if (System.IO.Path.GetExtension(file.Name).ToLower() != ".stl") { //return Response.AsJson("{\"files\":[{error:\"文件格式不是stl\"}]}",Nancy.HttpStatusCode.BadRequest); files.Add(new Models.File() { error = "文件格式不是stl!" }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); } if (file.Name.IndexOf("$") >= 0) { files.Add(new Models.File() { error = "文件名不能包含'$'符号!" }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); } //_filename = file.Name; if (Context.CurrentUser == null) { _filename = Session["TempUserId"].ToString() + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file.Name; filename = Path.Combine(uploadDirectory, _filename); } else { string userid = ""; userid = db.Select <string>("select Id from T_User where Email=@email", new { email = base.Page.CurrentUser }).FirstOrDefault(); _filename = userid + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file.Name; filename = Path.Combine(uploadDirectory, _filename); } using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } } STLReader stl = new STLReader(filename); if (stl.IsValid) { //jsonfile.files= stl.Size.Length.ToString(); //fi.gg_width = stl.Size.Width.ToString(); //fi.gg_height = stl.Size.Height.ToString(); //stl.Surface. files.Add(new Models.File() { name = _filename, fullname = filepath + _filename, length = stl.Size.Length.ToString(), width = stl.Size.Width.ToString(), height = stl.Size.Height.ToString(), surface = stl.Surface.ToString(), volume = stl.Volume.ToString() }); } else { files.Add(new Models.File() { error = stl.ErrorMessage }); } //return Response.AsJson("{\"files\":[{name:\"" + _filename + "\"}]}", Nancy.HttpStatusCode.OK); //files.Add(new Models.File() { name = _filename }); return(Response.AsJson <JsonFileUpload>(new JsonFileUpload() { files = files })); //base.Page.Title = "上传成功"; //return View["Index", base.Model]; }; Get["/suppliers"] = parameters => { string materialid = Request.Query["materialid"].Value; string _distance = Request.Query["distance"].Value; double distance = 20000; if (_distance != null) { bool b = double.TryParse(_distance, out distance); if (!b) { distance = 20000; } } double lng = 0, lat = 0; string url = $"http://api.map.baidu.com/location/ip?ak=26904d2efeb684d7d59d493098e7295d&ip={Request.UserHostAddress}&coor=bd09ll"; WebClient wc = new WebClient(); wc.Encoding = Encoding.UTF8; string json = wc.DownloadString(url); JObject m = JObject.Parse(json); if (m["status"].ToString() == "0") { lng = double.Parse(m["point"]["x"].ToString()); //经度 lat = double.Parse(m["point"]["y"].ToString()); //纬度 } //lng = 118.645297; //lat = 24.879442; double range = 180 / Math.PI * distance / 6372.797; //distance代表距离,单位是km double lngR = range / Math.Cos(lat * Math.PI / 180.0); double maxLat = lat + range; double minLat = lat - range; double maxLng = lng + lngR; double minLng = lng - lngR; //暂时精确到供应商,不精确到供应商的打印机 string sql = $@" SELECT t1.supplierId,t1.fname,address,tel,qq,logo,t2.Price as MatPrice,t3.fname as PrintCompleteName,t2.id as SupplierPrinterMaterialId FROM t_supplier t1 join t_supplier_printer_material t2 on t2.supplierId=t1.supplierId join t_printcomplete t3 on t3.completeid=t2.completeid WHERE ((lat BETWEEN '{minLat}' AND '{maxLat}') AND (lng BETWEEN '{minLng}' AND '{maxLng}')) and t2.MaterialId=@MaterialId and t1.state='0' Group by t1.supplierId,t1.fname,address,tel,qq,logo;"; var suppliers = db.Select <SupplierWithCompletePriceModel>(sql, new { MaterialId = materialid }); return(Response.AsJson(suppliers.Select(i => new { supplierId = i.SupplierId, fname = i.Fname, address = i.Address, tel = i.Tel, qq = i.QQ, logo = i.Logo, matprice = i.MatPrice, printcompletename = i.PrintCompleteName, supplierprintermaterialid = i.SupplierPrinterMaterialId }))); }; }
static private void TestPointInPolygon() { var STLFile = new STLReader("Cable support hook.stl"); }