Example #1
0
        public static bool Save(List <MeshGroup> meshGroupsToSave, string meshPathAndFileName, MeshOutputSettings outputInfo = null, ReportProgressRatio reportProgress = null)
        {
            try
            {
                if (outputInfo == null)
                {
                    outputInfo = new MeshOutputSettings();
                }
                switch (Path.GetExtension(meshPathAndFileName).ToUpper())
                {
                case ".STL":
                    Mesh mesh = DoMerge(meshGroupsToSave, outputInfo);
                    return(StlProcessing.Save(mesh, meshPathAndFileName, outputInfo));

                case ".AMF":
                    outputInfo.ReportProgress = reportProgress;
                    return(AmfProcessing.Save(meshGroupsToSave, meshPathAndFileName, outputInfo));

                default:
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #2
0
		public static bool SaveUncompressed(List<MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
		{
			using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
			{
				return Save(meshToSave, file, outputInfo);
			}
		}
		static public void SaveToLibraryFolder2(PrintItemWrapper printItemWrapper, List<MeshGroup> meshGroups, bool AbsolutePositioned)
		{
			string[] metaData = { "Created By", "MatterControl" };
			if (AbsolutePositioned)
			{
				metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" };
			}
			if (printItemWrapper.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath))
			{
				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
				MeshFileIo.Save(meshGroups, printItemWrapper.FileLocation, outputInfo);
			}
			else // save a copy to the library and update this to point at it
			{
				string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".amf");
				printItemWrapper.FileLocation = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, fileName);

				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
				MeshFileIo.Save(meshGroups, printItemWrapper.FileLocation, outputInfo);

				printItemWrapper.PrintItem.Commit();

				// let the queue know that the item has changed so it load the correct part
				QueueData.Instance.SaveDefaultQueue();
			}

			printItemWrapper.OnFileHasChanged();
		}
Example #4
0
		public static bool Save(Mesh meshToSave, string fileName, MeshOutputSettings outputInfo = null)
		{
			using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
			{
				if (outputInfo == null)
				{
					outputInfo = new MeshOutputSettings();
				}
				return Save(meshToSave, file, outputInfo);
			}
		}
 public static bool Save(Mesh meshToSave, string fileName, MeshOutputSettings outputInfo = null)
 {
     using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
     {
         if (outputInfo == null)
         {
             outputInfo = new MeshOutputSettings();
         }
         return(Save(meshToSave, file, outputInfo));
     }
 }
Example #6
0
        public static bool Save(this Mesh meshToSave, string fileName, CancellationToken cancellationToken, MeshOutputSettings outputInfo = null)
        {
            using (var file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                if (outputInfo == null)
                {
                    outputInfo = new MeshOutputSettings();
                }

                return(Save(meshToSave, file, cancellationToken, outputInfo));
            }
        }
Example #7
0
		/// <summary>
		/// Writes the mesh to disk in a zip container
		/// </summary>
		/// <param name="meshToSave">The mesh to save</param>
		/// <param name="fileName">The file path to save at</param>
		/// <param name="outputInfo">Extra meta data to store in the file</param>
		/// <returns>The results of the save operation</returns>
		public static bool Save(List<MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
		{
			using (Stream stream = File.OpenWrite(fileName))
			using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
			{
				ZipArchiveEntry zipEntry = archive.CreateEntry(Path.GetFileName(fileName));
				using (var entryStream = zipEntry.Open())
				{
					return Save(meshToSave, entryStream, outputInfo);
				}
			}
		}
Example #8
0
 /// <summary>
 /// Writes the mesh to disk in a zip container
 /// </summary>
 /// <param name="meshToSave">The mesh to save</param>
 /// <param name="fileName">The file path to save at</param>
 /// <param name="outputInfo">Extra meta data to store in the file</param>
 /// <returns>The results of the save operation</returns>
 public static bool Save(List <MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
 {
     using (Stream stream = File.OpenWrite(fileName))
         using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
         {
             ZipArchiveEntry zipEntry = archive.CreateEntry(Path.GetFileName(fileName));
             using (var entryStream = zipEntry.Open())
             {
                 return(Save(meshToSave, entryStream, outputInfo));
             }
         }
 }
Example #9
0
        public static Mesh DoMerge(List <MeshGroup> meshGroupsToMerge, MeshOutputSettings outputInfo)
        {
            Mesh allPolygons = new Mesh();

            if (outputInfo.CsgOptionState == MeshOutputSettings.CsgOption.DoCsgMerge)
            {
                foreach (MeshGroup meshGroup in meshGroupsToMerge)
                {
                    foreach (Mesh mesh in meshGroup.Meshes)
                    {
                        allPolygons = CsgOperations.Union(allPolygons, mesh);
                    }
                }
            }
            else
            {
                foreach (MeshGroup meshGroup in meshGroupsToMerge)
                {
                    foreach (Mesh mesh in meshGroup.Meshes)
                    {
                        int currentMeshMaterialIntdex = MeshMaterialData.Get(mesh).MaterialIndex;
                        if (outputInfo.MaterialIndexsToSave == null || outputInfo.MaterialIndexsToSave.Contains(currentMeshMaterialIntdex))
                        {
                            foreach (Face face in mesh.Faces)
                            {
                                List <Vertex> faceVertices = new List <Vertex>();
                                foreach (FaceEdge faceEdgeToAdd in face.FaceEdges())
                                {
                                    // we allow duplicates (the true) to make sure we are not changing the loaded models acuracy.
                                    Vertex newVertex = allPolygons.CreateVertex(faceEdgeToAdd.firstVertex.Position, CreateOption.CreateNew, SortOption.WillSortLater);
                                    faceVertices.Add(newVertex);
                                }

                                // we allow duplicates (the true) to make sure we are not changing the loaded models acuracy.
                                allPolygons.CreateFace(faceVertices.ToArray(), CreateOption.CreateNew);
                            }
                        }
                    }
                }

                allPolygons.CleanAndMergMesh();
            }

            return(allPolygons);
        }
Example #10
0
		/// <summary>
		/// Writes the mesh to disk in a zip container
		/// </summary>
		/// <param name="meshToSave">The mesh to save</param>
		/// <param name="fileName">The file path to save at</param>
		/// <param name="outputInfo">Extra meta data to store in the file</param>
		/// <returns>The results of the save operation</returns>
		public static bool Save(List<MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
		{
			try
			{
				using (Stream stream = File.OpenWrite(fileName))
				using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
				{
					ZipArchiveEntry zipEntry = archive.CreateEntry(Path.GetFileName(fileName));
					using (var entryStream = zipEntry.Open())
					{
						return Save(meshToSave, entryStream, outputInfo);
					}
				}
			}
			catch (Exception e)
			{
				Debug.Print(e.Message);
				BreakInDebugger();
				return false;
			}
		}
Example #11
0
 /// <summary>
 /// Writes the mesh to disk in a zip container
 /// </summary>
 /// <param name="meshToSave">The mesh to save</param>
 /// <param name="fileName">The file path to save at</param>
 /// <param name="outputInfo">Extra meta data to store in the file</param>
 /// <returns>The results of the save operation</returns>
 public static bool Save(List <MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
 {
     try
     {
         using (Stream stream = File.OpenWrite(fileName))
             using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
             {
                 ZipArchiveEntry zipEntry = archive.CreateEntry(Path.GetFileName(fileName));
                 using (var entryStream = zipEntry.Open())
                 {
                     return(Save(meshToSave, entryStream, outputInfo));
                 }
             }
     }
     catch (Exception e)
     {
         Debug.Print(e.Message);
         BreakInDebugger();
         return(false);
     }
 }
Example #12
0
		public static bool Save(List<MeshGroup> meshGroupsToSave, string meshPathAndFileName, MeshOutputSettings outputInfo = null, ReportProgressRatio reportProgress = null)
		{
			try
			{
				if (outputInfo == null)
				{
					outputInfo = new MeshOutputSettings();
				}
				switch (Path.GetExtension(meshPathAndFileName).ToUpper())
				{
					case ".STL":
						Mesh mesh = DoMerge(meshGroupsToSave, outputInfo);
						return StlProcessing.Save(mesh, meshPathAndFileName, outputInfo);

					case ".AMF":
						outputInfo.ReportProgress = reportProgress;
						return AmfProcessing.Save(meshGroupsToSave, meshPathAndFileName, outputInfo);

					default:
						return false;
				}
			}
			catch (Exception)
			{
				return false;
			}
		}
Example #13
0
		public static bool Save(Mesh mesh, string meshPathAndFileName, MeshOutputSettings outputInfo = null)
		{
			return Save(new MeshGroup(mesh), meshPathAndFileName, outputInfo);
		}
Example #14
0
		public static bool Save(MeshGroup meshGroupToSave, string meshPathAndFileName, MeshOutputSettings outputInfo = null)
		{
			List<MeshGroup> meshGroupsToSave = new List<MeshGroup>();
			meshGroupsToSave.Add(meshGroupToSave);
			return Save(meshGroupsToSave, meshPathAndFileName, outputInfo);
		}
		public override IEnumerable<PrintItemAction> GetMenuItems()
		{
			return new List<PrintItemAction>()
			{
				new PrintItemAction()
				{
					SingleItemOnly = false,
					Title = "Merge...",
					Action = (items, queueDataWidget) =>
					{
						List<QueueRowItem> allRowItems = new List<QueueRowItem>(items);
						if (allRowItems.Count > 1)
						{
							RenameItemWindow renameItemWindow = new RenameItemWindow(allRowItems[0].PrintItemWrapper.Name, (returnInfo) =>
							{
								Task.Run(() =>
								{
									List<MeshGroup> combinedMeshes = new List<MeshGroup>();

									// Load up all the parts and merge them together
									foreach(QueueRowItem item in allRowItems)
									{
										List<MeshGroup> loadedMeshGroups = MeshFileIo.Load(item.PrintItemWrapper.FileLocation);
										combinedMeshes.AddRange(loadedMeshGroups);
									}

									// save them out
									string[] metaData = { "Created By", "MatterControl", "BedPosition", "Absolute" };
									MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
									string libraryDataPath = ApplicationDataStorage.Instance.ApplicationLibraryDataPath;
									if (!Directory.Exists(libraryDataPath))
									{
										Directory.CreateDirectory(libraryDataPath);
									}

									string tempFileNameToSaveTo = Path.Combine(libraryDataPath, Path.ChangeExtension(Path.GetRandomFileName(), "amf"));
									bool savedSuccessfully = MeshFileIo.Save(combinedMeshes, tempFileNameToSaveTo, outputInfo);

									// Swap out the files if the save operation completed successfully
									if (savedSuccessfully && File.Exists(tempFileNameToSaveTo))
									{
										// create a new print item
										// add it to the queue
										PrintItemWrapper newPrintItem = new PrintItemWrapper(new PrintItem(returnInfo.newName, tempFileNameToSaveTo));
										QueueData.Instance.AddItem(newPrintItem, 0);

										// select the part we added, if possible
										QueueData.Instance.SelectedIndex = 0;

										queueDataWidget.LeaveEditMode();
									}
								});
							}, "Set Name".Localize())
							{
								Title = "MatterHackers - Set Name".Localize(),
								ElementHeader = "Set Name".Localize(),
							};
						}
					}
				}
			};
		}
        public static bool Save(Mesh meshToSave, Stream stream, MeshOutputSettings outputInfo)
        {
            switch (outputInfo.OutputTypeSetting)
            {
            case MeshOutputSettings.OutputType.Ascii:
            {
                StreamWriter streamWriter = new StreamWriter(stream);

                streamWriter.WriteLine("solid Default");

                foreach (Face face in meshToSave.Faces)
                {
                    List <Vector3> positionsCCW = new List <Vector3>();
                    foreach (FaceEdge faceEdge in face.FaceEdges())
                    {
                        positionsCCW.Add(faceEdge.firstVertex.Position);
                    }

                    int numPolys    = positionsCCW.Count - 2;
                    int secondIndex = 1;
                    int thirdIndex  = 2;
                    for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
                    {
                        streamWriter.WriteLine("  facet normal " + FormatForStl(face.normal));
                        streamWriter.WriteLine("    outer loop");
                        streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[0]));
                        streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[secondIndex]));
                        streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[thirdIndex]));
                        streamWriter.WriteLine("    endloop");
                        streamWriter.WriteLine("  endfacet");

                        secondIndex = thirdIndex;
                        thirdIndex++;
                    }
                }

                streamWriter.WriteLine("endsolid Default");

                streamWriter.Close();
            }
            break;

            case MeshOutputSettings.OutputType.Binary:
                using (BinaryWriter bw = new BinaryWriter(stream))
                {
                    // 80 bytes of nothing
                    bw.Write(new Byte[80]);
                    // the number of tranigles
                    bw.Write(meshToSave.Faces.Count);
                    int binaryPolyCount = 0;
                    foreach (Face face in meshToSave.Faces)
                    {
                        List <Vector3> positionsCCW = new List <Vector3>();
                        foreach (FaceEdge faceEdge in face.FaceEdges())
                        {
                            positionsCCW.Add(faceEdge.firstVertex.Position);
                        }

                        int numPolys    = positionsCCW.Count - 2;
                        int secondIndex = 1;
                        int thirdIndex  = 2;
                        for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
                        {
                            binaryPolyCount++;
                            // save the normal (all 0 so it can compress better)
                            bw.Write((float)0);
                            bw.Write((float)0);
                            bw.Write((float)0);
                            // save the position
                            bw.Write((float)positionsCCW[0].x); bw.Write((float)positionsCCW[0].y); bw.Write((float)positionsCCW[0].z);
                            bw.Write((float)positionsCCW[secondIndex].x); bw.Write((float)positionsCCW[secondIndex].y); bw.Write((float)positionsCCW[secondIndex].z);
                            bw.Write((float)positionsCCW[thirdIndex].x); bw.Write((float)positionsCCW[thirdIndex].y); bw.Write((float)positionsCCW[thirdIndex].z);

                            // and the attribute
                            bw.Write((ushort)0);

                            secondIndex = thirdIndex;
                            thirdIndex++;
                        }
                    }
                    bw.BaseStream.Position = 80;
                    // the number of tranigles
                    bw.Write(binaryPolyCount);
                }
                break;
            }
            return(true);
        }
Example #17
0
		public static bool Save(Mesh meshToSave, Stream stream, MeshOutputSettings outputInfo)
		{
			switch (outputInfo.OutputTypeSetting)
			{
				case MeshOutputSettings.OutputType.Ascii:
					{
						StreamWriter streamWriter = new StreamWriter(stream);

						streamWriter.WriteLine("solid Default");

						foreach (Face face in meshToSave.Faces)
						{
							List<Vector3> positionsCCW = new List<Vector3>();
							foreach (FaceEdge faceEdge in face.FaceEdges())
							{
								positionsCCW.Add(faceEdge.firstVertex.Position);
							}

							int numPolys = positionsCCW.Count - 2;
							int secondIndex = 1;
							int thirdIndex = 2;
							for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
							{
								streamWriter.WriteLine("  facet normal " + FormatForStl(face.normal));
								streamWriter.WriteLine("    outer loop");
								streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[0]));
								streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[secondIndex]));
								streamWriter.WriteLine("      vertex " + FormatForStl(positionsCCW[thirdIndex]));
								streamWriter.WriteLine("    endloop");
								streamWriter.WriteLine("  endfacet");

								secondIndex = thirdIndex;
								thirdIndex++;
							}
						}

						streamWriter.WriteLine("endsolid Default");

						streamWriter.Close();
					}
					break;

				case MeshOutputSettings.OutputType.Binary:
					using (BinaryWriter bw = new BinaryWriter(stream))
					{
						// 80 bytes of nothing
						bw.Write(new Byte[80]);
						// the number of tranigles
						bw.Write(meshToSave.Faces.Count);
						int binaryPolyCount = 0;
						foreach (Face face in meshToSave.Faces)
						{
							List<Vector3> positionsCCW = new List<Vector3>();
							foreach (FaceEdge faceEdge in face.FaceEdges())
							{
								positionsCCW.Add(faceEdge.firstVertex.Position);
							}

							int numPolys = positionsCCW.Count - 2;
							int secondIndex = 1;
							int thirdIndex = 2;
							for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
							{
								binaryPolyCount++;
								// save the normal (all 0 so it can compress better)
								bw.Write((float)0);
								bw.Write((float)0);
								bw.Write((float)0);
								// save the position
								bw.Write((float)positionsCCW[0].x); bw.Write((float)positionsCCW[0].y); bw.Write((float)positionsCCW[0].z);
								bw.Write((float)positionsCCW[secondIndex].x); bw.Write((float)positionsCCW[secondIndex].y); bw.Write((float)positionsCCW[secondIndex].z);
								bw.Write((float)positionsCCW[thirdIndex].x); bw.Write((float)positionsCCW[thirdIndex].y); bw.Write((float)positionsCCW[thirdIndex].z);

								// and the attribute
								bw.Write((ushort)0);

								secondIndex = thirdIndex;
								thirdIndex++;
							}
						}
						bw.BaseStream.Position = 80;
						// the number of tranigles
						bw.Write(binaryPolyCount);
					}
					break;
			}
			return true;
		}
Example #18
0
        public static bool Save(Mesh mesh, Stream stream, CancellationToken cancellationToken, MeshOutputSettings outputInfo)
        {
            switch (outputInfo.OutputTypeSetting)
            {
            case MeshOutputSettings.OutputType.Ascii:
            {
                var streamWriter = new StreamWriter(stream);

                streamWriter.WriteLine("solid Default");

                for (int faceIndex = 0; faceIndex < mesh.Faces.Count; faceIndex++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }

                    var face = mesh.Faces[faceIndex];

                    streamWriter.WriteLine("  facet normal " + FormatForStl(mesh.Faces[faceIndex].normal));
                    streamWriter.WriteLine("    outer loop");
                    streamWriter.WriteLine("      vertex " + FormatForStl(mesh.Vertices[face.v0]));
                    streamWriter.WriteLine("      vertex " + FormatForStl(mesh.Vertices[face.v1]));
                    streamWriter.WriteLine("      vertex " + FormatForStl(mesh.Vertices[face.v2]));
                    streamWriter.WriteLine("    endloop");
                    streamWriter.WriteLine("  endfacet");
                }

                streamWriter.WriteLine("endsolid Default");

                streamWriter.Close();
            }

            break;

            case MeshOutputSettings.OutputType.Binary:
                using (var bw = new BinaryWriter(stream))
                {
                    // 80 bytes of nothing
                    bw.Write(new byte[80]);
                    // the number of triangles
                    bw.Write(mesh.Faces.Count);
                    int binaryPolyCount = 0;
                    for (int faceIndex = 0; faceIndex < mesh.Faces.Count; faceIndex++)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            return(false);
                        }

                        var face = mesh.Faces[faceIndex];

                        binaryPolyCount++;
                        // save the normal (all 0 so it can compress better)
                        WriteToBinaryStl(bw, mesh.Faces[faceIndex].normal);
                        // save the position
                        WriteToBinaryStl(bw, mesh.Vertices[face.v0]);
                        WriteToBinaryStl(bw, mesh.Vertices[face.v1]);
                        WriteToBinaryStl(bw, mesh.Vertices[face.v2]);

                        // and the attribute
                        bw.Write((ushort)0);
                    }

                    bw.BaseStream.Position = 80;

                    // the number of triangles
                    bw.Write(binaryPolyCount);
                }

                break;
            }

            return(true);
        }
		private static string SaveAndGetFilenameForMaterial(MeshGroup extruderMeshGroup, List<int> materialIndexsToSaveInThisSTL)
		{
			string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".stl");
			string applicationUserDataPath = ApplicationDataStorage.ApplicationUserDataPath;
			string folderToSaveStlsTo = Path.Combine(applicationUserDataPath, "data", "temp", "amf_to_stl");
			if (!Directory.Exists(folderToSaveStlsTo))
			{
				Directory.CreateDirectory(folderToSaveStlsTo);
			}
			MeshOutputSettings settings = new MeshOutputSettings();
			settings.MaterialIndexsToSave = materialIndexsToSaveInThisSTL;
			string extruder1StlFileToSlice = Path.Combine(folderToSaveStlsTo, fileName);
			MeshFileIo.Save(extruderMeshGroup, extruder1StlFileToSlice, settings);
			return extruder1StlFileToSlice;
		}
		protected static void SaveToLibraryFolder(PrintItemWrapper printItemWrapper, List<MeshGroup> meshGroups, bool AbsolutePositioned)
		{
			string[] metaData = { "Created By", "MatterControl" };
			if (AbsolutePositioned)
			{
				metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" };
			}

			// if it is not already in the right location
			if (!printItemWrapper.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath))
			{
				// save a copy to the library and update this to point at it
				string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".amf");
				printItemWrapper.FileLocation = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, fileName);

				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
				MeshFileIo.Save(meshGroups, printItemWrapper.FileLocation, outputInfo);
			}
		}
Example #21
0
        public static bool Save(MeshGroup meshGroupToSave, string meshPathAndFileName, MeshOutputSettings outputInfo = null)
        {
            List <MeshGroup> meshGroupsToSave = new List <MeshGroup>();

            meshGroupsToSave.Add(meshGroupToSave);
            return(Save(meshGroupsToSave, meshPathAndFileName, outputInfo));
        }
Example #22
0
		public static bool Save(List<MeshGroup> meshToSave, Stream stream, MeshOutputSettings outputInfo)
		{
			TextWriter amfFile = new StreamWriter(stream);
			amfFile.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			amfFile.WriteLine("<amf unit=\"millimeter\" version=\"1.1\">");
			if (outputInfo != null)
			{
				foreach (KeyValuePair<string, string> metaData in outputInfo.MetaDataKeyValue)
				{
					amfFile.WriteLine(Indent(1) + "<metadata type=\"{0}\">{1}</metadata>".FormatWith(metaData.Key, metaData.Value));
				}
			}
			{
				int objectId = 1;
				foreach (MeshGroup meshGroup in meshToSave)
				{
					amfFile.WriteLine(Indent(1) + "<object id=\"{0}\">".FormatWith(objectId++));
					{
						int vertexCount = 0;
						List<int> meshVertexStart = new List<int>();
						amfFile.WriteLine(Indent(2) + "<mesh>");
						{
							amfFile.WriteLine(Indent(3) + "<vertices>");
							{
								foreach (Mesh mesh in meshGroup.Meshes)
								{
									meshVertexStart.Add(vertexCount);
									foreach (Vertex vertex in mesh.Vertices)
									{
										Vector3 position = vertex.Position;
										amfFile.WriteLine(Indent(4) + "<vertex>");
										{
											amfFile.WriteLine(Indent(5) + "<coordinates>");
											amfFile.WriteLine(Indent(6) + "<x>{0}</x>".FormatWith(position.x));
											amfFile.WriteLine(Indent(6) + "<y>{0}</y>".FormatWith(position.y));
											amfFile.WriteLine(Indent(6) + "<z>{0}</z>".FormatWith(position.z));
											amfFile.WriteLine(Indent(5) + "</coordinates>");
										}
										amfFile.WriteLine(Indent(4) + "</vertex>");
										vertexCount++;
									}
								}
							}
							amfFile.WriteLine(Indent(3) + "</vertices>");
							for (int meshIndex = 0; meshIndex < meshGroup.Meshes.Count; meshIndex++)
							{
								int firstVertexIndex = meshVertexStart[meshIndex];
								Mesh mesh = meshGroup.Meshes[meshIndex];
								MeshMaterialData material = MeshMaterialData.Get(mesh);
								if (material.MaterialIndex == -1)
								{
									amfFile.WriteLine(Indent(3) + "<volume>");
								}
								else
								{
									amfFile.WriteLine(Indent(3) + "<volume materialid=\"{0}\">".FormatWith(material.MaterialIndex));
								}
								{
									for (int faceIndex = 0; faceIndex < mesh.Faces.Count; faceIndex++)
									{
										Face face = mesh.Faces[faceIndex];
										List<Vertex> positionsCCW = new List<Vertex>();
										foreach (FaceEdge faceEdge in face.FaceEdges())
										{
											positionsCCW.Add(faceEdge.firstVertex);
										}

										int numPolys = positionsCCW.Count - 2;
										int secondIndex = 1;
										int thirdIndex = 2;
										for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
										{
											amfFile.WriteLine(Indent(4) + "<triangle>");
											amfFile.WriteLine(Indent(5) + "<v1>{0}</v1>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[0])));
											amfFile.WriteLine(Indent(5) + "<v2>{0}</v2>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[secondIndex])));
											amfFile.WriteLine(Indent(5) + "<v3>{0}</v3>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[thirdIndex])));
											amfFile.WriteLine(Indent(4) + "</triangle>");

											secondIndex = thirdIndex;
											thirdIndex++;
										}
									}
								}
								amfFile.WriteLine(Indent(3) + "</volume>");
							}
						}
						amfFile.WriteLine(Indent(2) + "</mesh>");
					}
					amfFile.WriteLine(Indent(1) + "</object>");
				}

				HashSet<int> materials = new HashSet<int>();
				foreach (MeshGroup meshGroup in meshToSave)
				{
					foreach (Mesh mesh in meshGroup.Meshes)
					{
						MeshMaterialData material = MeshMaterialData.Get(mesh);
						if (material.MaterialIndex != -1)
						{
							materials.Add(material.MaterialIndex);
						}
					}
				}

				foreach (int material in materials)
				{
					amfFile.WriteLine(Indent(1) + "<material id=\"{0}\">".FormatWith(material));
					amfFile.WriteLine(Indent(2) + "<metadata type=\"Name\">Material {0}</metadata>".FormatWith(material));
					amfFile.WriteLine(Indent(1) + "</material>");
				}
			}
			amfFile.WriteLine("</amf>");
			amfFile.Flush();
			return true;
		}
Example #23
0
 public static bool Save(Mesh mesh, string meshPathAndFileName, MeshOutputSettings outputInfo = null)
 {
     return(Save(new MeshGroup(mesh), meshPathAndFileName, outputInfo));
 }
Example #24
0
		private void MergeAndSavePartsDoWork(SaveAsWindow.SaveAsReturnInfo returnInfo)
		{
			if (returnInfo != null)
			{
				PrintItem printItem = new PrintItem();
				printItem.Name = returnInfo.newName;
				printItem.FileLocation = Path.GetFullPath(returnInfo.fileNameAndPath);
				printItemWrapper = new PrintItemWrapper(printItem, returnInfo.destinationLibraryProvider.GetProviderLocator());
			}

			// we sent the data to the asynch lists but we will not pull it back out (only use it as a temp holder).
			PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);

			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			try
			{
				// push all the transforms into the meshes
				for (int i = 0; i < asynchMeshGroups.Count; i++)
				{
					asynchMeshGroups[i].Transform(asynchMeshGroupTransforms[i].TotalTransform);

					bool continueProcessing;
					ReportProgressChanged((i + 1) * .4 / asynchMeshGroups.Count, "", out continueProcessing);
				}

				saveSucceded = true;

				string[] metaData = { "Created By", "MatterControl", "BedPosition", "Absolute" };

				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
				if (Path.GetExtension(printItemWrapper.FileLocation).ToUpper() == ".STL")
				{
					printItemWrapper.FileLocation = Path.ChangeExtension(printItemWrapper.FileLocation, ".AMF");
				}

				MeshFileIo.Save(asynchMeshGroups, printItemWrapper.FileLocation, outputInfo);

				printItemWrapper.ReportFileChange();

				if (returnInfo != null
					&& returnInfo.destinationLibraryProvider != null)
				{
					// save this part to correct library provider
					LibraryProvider libraryToSaveTo = returnInfo.destinationLibraryProvider;
					if (libraryToSaveTo != null)
					{
						libraryToSaveTo.AddItem(printItemWrapper);
						libraryToSaveTo.Dispose();
					}
				}
				else // we have already save it and the library should pick it up
				{

				}
			}
			catch (System.UnauthorizedAccessException e2)
			{
				Debug.Print(e2.Message);
				GuiWidget.BreakInDebugger();
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					//Do something special when unauthorized?
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}
			catch(Exception e)
			{
				Debug.Print(e.Message);
				GuiWidget.BreakInDebugger();
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}
		}
Example #25
0
		public static Mesh DoMerge(List<MeshGroup> meshGroupsToMerge, MeshOutputSettings outputInfo)
		{
			Mesh allPolygons = new Mesh();
			if (outputInfo.CsgOptionState == MeshOutputSettings.CsgOption.DoCsgMerge)
			{
				foreach (MeshGroup meshGroup in meshGroupsToMerge)
				{
					foreach (Mesh mesh in meshGroup.Meshes)
					{
						allPolygons = CsgOperations.Union(allPolygons, mesh);
					}
				}
			}
			else
			{
				foreach (MeshGroup meshGroup in meshGroupsToMerge)
				{
					foreach (Mesh mesh in meshGroup.Meshes)
					{
						int currentMeshMaterialIntdex = MeshMaterialData.Get(mesh).MaterialIndex;
						if (outputInfo.MaterialIndexsToSave == null || outputInfo.MaterialIndexsToSave.Contains(currentMeshMaterialIntdex))
						{
							foreach (Face face in mesh.Faces)
							{
								List<Vertex> faceVertices = new List<Vertex>();
								foreach (FaceEdge faceEdgeToAdd in face.FaceEdges())
								{
									// we allow duplicates (the true) to make sure we are not changing the loaded models acuracy.
									Vertex newVertex = allPolygons.CreateVertex(faceEdgeToAdd.firstVertex.Position, CreateOption.CreateNew, SortOption.WillSortLater);
									faceVertices.Add(newVertex);
								}

								// we allow duplicates (the true) to make sure we are not changing the loaded models acuracy.
								allPolygons.CreateFace(faceVertices.ToArray(), CreateOption.CreateNew);
							}
						}
					}
				}

				allPolygons.CleanAndMergMesh();
			}

			return allPolygons;
		}
Example #26
0
 public static bool SaveUncompressed(List <MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
 {
     using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
     {
         return(Save(meshToSave, file, outputInfo));
     }
 }
		private void MergeAndSavePartsDoWork(SaveAsWindow.SaveAsReturnInfo returnInfo)
		{
			if (returnInfo != null)
			{
				PrintItem printItem = new PrintItem();
				printItem.Name = returnInfo.newName;
				printItem.FileLocation = Path.GetFullPath(returnInfo.fileNameAndPath);
				printItemWrapper = new PrintItemWrapper(printItem, returnInfo.destinationLibraryProvider.GetProviderLocator());
			}

			// we sent the data to the async lists but we will not pull it back out (only use it as a temp holder).
			PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);

			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			try
			{
				// push all the transforms into the meshes
				for (int i = 0; i < asyncMeshGroups.Count; i++)
				{
					asyncMeshGroups[i].Transform(asyncMeshGroupTransforms[i]);

					bool continueProcessing;
					ReportProgressChanged((i + 1) * .4 / asyncMeshGroups.Count, "", out continueProcessing);
				}

				string[] metaData = { "Created By", "MatterControl", "BedPosition", "Absolute" };

				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);

				// If null we are replacing a file from the current print item wrapper
				if (returnInfo == null)
				{
					var fileInfo = new FileInfo(printItemWrapper.FileLocation);

					bool requiresTypeChange = !fileInfo.Extension.Equals(".amf", StringComparison.OrdinalIgnoreCase);
					if (requiresTypeChange && !printItemWrapper.UseIncrementedNameDuringTypeChange)
					{
						// Not using incremented file name, simply change to AMF
						printItemWrapper.FileLocation = Path.ChangeExtension(printItemWrapper.FileLocation, ".amf");
					}
					else if (requiresTypeChange)
					{
						string newFileName;
						string incrementedFileName;

						// Switching from .stl, .obj or similar to AMF. Save the file and update the
						// the filename with an incremented (n) value to reflect the extension change in the UI 
						string fileName = Path.GetFileNameWithoutExtension(fileInfo.Name);

						// Drop bracketed number sections from our source filename to ensure we don't generate something like "file (1) (1).amf"
						if (fileName.Contains("("))
						{
							fileName = fileNameNumberMatch.Replace(fileName, "").Trim();
						}

						// Generate and search for an incremented file name until no match is found at the target directory
						int foundCount = 0;
						do
						{
							newFileName = string.Format("{0} ({1})", fileName, ++foundCount);
							incrementedFileName = Path.Combine(fileInfo.DirectoryName, newFileName + ".amf");

							// Continue incrementing while any matching file exists
						} while (Directory.GetFiles(fileInfo.DirectoryName, newFileName + ".*").Any());

						// Change the FileLocation to the new AMF file
						printItemWrapper.FileLocation = incrementedFileName;
					}

					try
					{
						// get a new location to save to
						string tempFileNameToSaveTo = ApplicationDataStorage.Instance.GetTempFileName("amf");

						// save to the new temp location
						bool savedSuccessfully = MeshFileIo.Save(asyncMeshGroups, tempFileNameToSaveTo, outputInfo, ReportProgressChanged);

						// Swap out the files if the save operation completed successfully 
						if (savedSuccessfully && File.Exists(tempFileNameToSaveTo))
						{
							// Ensure the target path is clear
							if(File.Exists(printItemWrapper.FileLocation))
							{
								File.Delete(printItemWrapper.FileLocation);
							}

							// Move the newly saved file back into place
							File.Move(tempFileNameToSaveTo, printItemWrapper.FileLocation);

							// Once the file is swapped back into place, update the PrintItem to account for extension change
							printItemWrapper.PrintItem.Commit();
						}
					}
					catch(Exception ex)
					{
						Trace.WriteLine("Error saving file: ", ex.Message);
					}
				}
				else // we are saving a new file and it will not exist until we are done
				{
					MeshFileIo.Save(asyncMeshGroups, printItemWrapper.FileLocation, outputInfo, ReportProgressChanged);
				}

				// Wait for a second to report the file changed to give the OS a chance to finish closing it.
				UiThread.RunOnIdle(printItemWrapper.ReportFileChange, 3);

				if (returnInfo != null
					&& returnInfo.destinationLibraryProvider != null)
				{
					// save this part to correct library provider
					LibraryProvider libraryToSaveTo = returnInfo.destinationLibraryProvider;
					if (libraryToSaveTo != null)
					{
						libraryToSaveTo.AddItem(printItemWrapper);
						libraryToSaveTo.Dispose();
					}
				}
				else // we have already saved it and the library should pick it up
				{
				}

				saveSucceded = true;
			}
			catch (System.UnauthorizedAccessException e2)
			{
				Debug.Print(e2.Message);
				GuiWidget.BreakInDebugger();
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					//Do something special when unauthorized?
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}
			catch (Exception e)
			{
				Debug.Print(e.Message);
				GuiWidget.BreakInDebugger();
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}
		}
Example #28
0
		private void mergeAndSavePartsBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			SaveAsWindow.SaveAsReturnInfo returnInfo = e.Argument as SaveAsWindow.SaveAsReturnInfo;

			if (returnInfo != null)
			{
				printItemWrapper = returnInfo.printItemWrapper;
			}

			// we sent the data to the asynch lists but we will not pull it back out (only use it as a temp holder).
			PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);

			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			try
			{
				// push all the transforms into the meshes
				for (int i = 0; i < asynchMeshGroups.Count; i++)
				{
					asynchMeshGroups[i].Transform(asynchMeshGroupTransforms[i].TotalTransform);

					bool continueProcessing;
					ReportProgressChanged((i + 1) * .4 / asynchMeshGroups.Count, "", out continueProcessing);
				}

				saveSucceded = true;

				string[] metaData = { "Created By", "MatterControl", "BedPosition", "Absolute" };

				MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
				MeshFileIo.Save(asynchMeshGroups, printItemWrapper.FileLocation, outputInfo);
				printItemWrapper.OnFileHasChanged();
			}
			catch (System.UnauthorizedAccessException)
			{
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					//Do something special when unauthorized?
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}
			catch
			{
				saveSucceded = false;
				UiThread.RunOnIdle(() =>
				{
					StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
				});
			}

			e.Result = e.Argument;
		}
Example #29
0
        public static bool Save(List <MeshGroup> meshToSave, Stream stream, MeshOutputSettings outputInfo)
        {
            TextWriter amfFile = new StreamWriter(stream);

            amfFile.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            amfFile.WriteLine("<amf unit=\"millimeter\" version=\"1.1\">");
            if (outputInfo != null)
            {
                foreach (KeyValuePair <string, string> metaData in outputInfo.MetaDataKeyValue)
                {
                    amfFile.WriteLine(Indent(1) + "<metadata type=\"{0}\">{1}</metadata>".FormatWith(metaData.Key, metaData.Value));
                }
            }
            {
                int objectId = 1;

                bool continueProcessing;

                int totalMeshes = 0;
                foreach (MeshGroup meshGroup in meshToSave)
                {
                    foreach (Mesh mesh in meshGroup.Meshes)
                    {
                        totalMeshes++;
                    }
                }

                double ratioPerMesh  = 1d / totalMeshes;
                double currentRation = 0;
                for (int meshGroupIndex = 0; meshGroupIndex < meshToSave.Count; meshGroupIndex++)
                {
                    MeshGroup meshGroup = meshToSave[meshGroupIndex];
                    amfFile.WriteLine(Indent(1) + "<object id=\"{0}\">".FormatWith(objectId++));
                    {
                        int        vertexCount     = 0;
                        List <int> meshVertexStart = new List <int>();
                        amfFile.WriteLine(Indent(2) + "<mesh>");
                        {
                            amfFile.WriteLine(Indent(3) + "<vertices>");
                            {
                                for (int meshIndex = 0; meshIndex < meshGroup.Meshes.Count; meshIndex++)
                                {
                                    Mesh   mesh      = meshGroup.Meshes[meshIndex];
                                    double vertCount = (double)mesh.Vertices.Count;

                                    meshVertexStart.Add(vertexCount);
                                    for (int vertexIndex = 0; vertexIndex < mesh.Vertices.Count; vertexIndex++)
                                    {
                                        Vertex vertex = mesh.Vertices[vertexIndex];
                                        if (outputInfo.ReportProgress != null)
                                        {
                                            outputInfo.ReportProgress(currentRation + vertexIndex / vertCount * ratioPerMesh * .5, "", out continueProcessing);
                                        }

                                        Vector3 position = vertex.Position;
                                        amfFile.WriteLine(Indent(4) + "<vertex>");
                                        {
                                            amfFile.WriteLine(Indent(5) + "<coordinates>");
                                            amfFile.WriteLine(Indent(6) + "<x>{0}</x>".FormatWith(position.x));
                                            amfFile.WriteLine(Indent(6) + "<y>{0}</y>".FormatWith(position.y));
                                            amfFile.WriteLine(Indent(6) + "<z>{0}</z>".FormatWith(position.z));
                                            amfFile.WriteLine(Indent(5) + "</coordinates>");
                                        }
                                        amfFile.WriteLine(Indent(4) + "</vertex>");
                                        vertexCount++;
                                    }
                                    currentRation += ratioPerMesh * .5;
                                }
                            }

                            amfFile.WriteLine(Indent(3) + "</vertices>");
                            for (int meshIndex = 0; meshIndex < meshGroup.Meshes.Count; meshIndex++)
                            {
                                Mesh             mesh             = meshGroup.Meshes[meshIndex];
                                int              firstVertexIndex = meshVertexStart[meshIndex];
                                MeshMaterialData material         = MeshMaterialData.Get(mesh);
                                if (material.MaterialIndex == -1)
                                {
                                    amfFile.WriteLine(Indent(3) + "<volume>");
                                }
                                else
                                {
                                    amfFile.WriteLine(Indent(3) + "<volume materialid=\"{0}\">".FormatWith(material.MaterialIndex));
                                }

                                double faceCount = (double)mesh.Faces.Count;
                                for (int faceIndex = 0; faceIndex < mesh.Faces.Count; faceIndex++)
                                {
                                    if (outputInfo.ReportProgress != null)
                                    {
                                        outputInfo.ReportProgress(currentRation + faceIndex / faceCount * ratioPerMesh * .5, "", out continueProcessing);
                                    }

                                    Face          face         = mesh.Faces[faceIndex];
                                    List <Vertex> positionsCCW = new List <Vertex>();
                                    foreach (FaceEdge faceEdge in face.FaceEdges())
                                    {
                                        positionsCCW.Add(faceEdge.firstVertex);
                                    }

                                    int numPolys    = positionsCCW.Count - 2;
                                    int secondIndex = 1;
                                    int thirdIndex  = 2;
                                    for (int polyIndex = 0; polyIndex < numPolys; polyIndex++)
                                    {
                                        amfFile.WriteLine(Indent(4) + "<triangle>");
                                        amfFile.WriteLine(Indent(5) + "<v1>{0}</v1>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[0])));
                                        amfFile.WriteLine(Indent(5) + "<v2>{0}</v2>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[secondIndex])));
                                        amfFile.WriteLine(Indent(5) + "<v3>{0}</v3>".FormatWith(firstVertexIndex + mesh.Vertices.IndexOf(positionsCCW[thirdIndex])));
                                        amfFile.WriteLine(Indent(4) + "</triangle>");

                                        secondIndex = thirdIndex;
                                        thirdIndex++;
                                    }
                                }

                                currentRation += ratioPerMesh * .5;
                                amfFile.WriteLine(Indent(3) + "</volume>");
                            }
                        }
                        amfFile.WriteLine(Indent(2) + "</mesh>");
                    }
                    amfFile.WriteLine(Indent(1) + "</object>");
                }

                HashSet <int> materials = new HashSet <int>();
                foreach (MeshGroup meshGroup in meshToSave)
                {
                    foreach (Mesh mesh in meshGroup.Meshes)
                    {
                        MeshMaterialData material = MeshMaterialData.Get(mesh);
                        if (material.MaterialIndex != -1)
                        {
                            materials.Add(material.MaterialIndex);
                        }
                    }
                }

                foreach (int material in materials)
                {
                    amfFile.WriteLine(Indent(1) + "<material id=\"{0}\">".FormatWith(material));
                    amfFile.WriteLine(Indent(2) + "<metadata type=\"Name\">Material {0}</metadata>".FormatWith(material));
                    amfFile.WriteLine(Indent(1) + "</material>");
                }
            }
            amfFile.WriteLine("</amf>");
            amfFile.Flush();
            return(true);
        }