Ran code maid against this code.

This commit is contained in:
Lars Brubaker 2015-04-08 15:20:10 -07:00
parent 1445945d9c
commit 591528ee91
309 changed files with 139399 additions and 140129 deletions

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,64 +23,64 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.MeshVisualizer;
using MatterHackers.VectorMath;
using System;
using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class Cover : GuiWidget
{
public Cover(HAnchor hAnchor = HAnchor.None, VAnchor vAnchor = VAnchor.None)
: base(hAnchor, vAnchor)
{
}
}
public class Cover : GuiWidget
{
public Cover(HAnchor hAnchor = HAnchor.None, VAnchor vAnchor = VAnchor.None)
: base(hAnchor, vAnchor)
{
}
}
public class PartPreview3DWidget : PartPreviewWidget
{
protected static readonly int DefaultScrollBarWidth = 120;
public class PartPreview3DWidget : PartPreviewWidget
{
protected static readonly int DefaultScrollBarWidth = 120;
protected bool autoRotating = false;
protected bool allowAutoRotate = false;
public MeshViewerWidget meshViewerWidget;
event EventHandler unregisterEvents;
protected bool autoRotating = false;
protected bool allowAutoRotate = false;
public MeshViewerWidget meshViewerWidget;
protected ViewControls3D viewControls3D;
private event EventHandler unregisterEvents;
bool needToRecretaeBed = false;
protected ViewControls3D viewControls3D;
public PartPreview3DWidget()
{
SliceSettingsWidget.RegisterForSettingsChange("bed_size", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("print_center", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("build_height", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("bed_shape", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("center_part_on_bed", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
private bool needToRecretaeBed = false;
public PartPreview3DWidget()
{
SliceSettingsWidget.RegisterForSettingsChange("bed_size", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("print_center", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("build_height", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("bed_shape", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
SliceSettingsWidget.RegisterForSettingsChange("center_part_on_bed", SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
#if false
"extruder_offset",
#endif
ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
}
ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(SetFlagToRecreateBedAndPartPosition, ref unregisterEvents);
}
void SetFlagToRecreateBedAndPartPosition(object sender, EventArgs e)
{
private void SetFlagToRecreateBedAndPartPosition(object sender, EventArgs e)
{
needToRecretaeBed = true;
}
}
void RecreateBed()
private void RecreateBed()
{
double buildHeight = ActiveSliceSettings.Instance.BuildHeight;
@ -96,7 +96,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
public override void OnDraw(Graphics2D graphics2D)
{
if(needToRecretaeBed)
if (needToRecretaeBed)
{
needToRecretaeBed = false;
RecreateBed();
@ -104,52 +104,52 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
base.OnDraw(graphics2D);
}
protected void PutOemImageOnBed()
{
// this is to add an image to the bed
string imagePathAndFile = Path.Combine("OEMSettings", "bedimage.png");
if (allowAutoRotate && StaticData.Instance.FileExists(imagePathAndFile))
{
ImageBuffer wattermarkImage = StaticData.Instance.LoadImage(imagePathAndFile);
protected void PutOemImageOnBed()
{
// this is to add an image to the bed
string imagePathAndFile = Path.Combine("OEMSettings", "bedimage.png");
if (allowAutoRotate && StaticData.Instance.FileExists(imagePathAndFile))
{
ImageBuffer wattermarkImage = StaticData.Instance.LoadImage(imagePathAndFile);
ImageBuffer bedImage = meshViewerWidget.BedImage;
Graphics2D bedGraphics = bedImage.NewGraphics2D();
bedGraphics.Render(wattermarkImage,
new Vector2((bedImage.Width - wattermarkImage.Width) / 2, (bedImage.Height - wattermarkImage.Height) / 2));
}
}
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
ImageBuffer bedImage = meshViewerWidget.BedImage;
Graphics2D bedGraphics = bedImage.NewGraphics2D();
bedGraphics.Render(wattermarkImage,
new Vector2((bedImage.Width - wattermarkImage.Width) / 2, (bedImage.Height - wattermarkImage.Height) / 2));
}
}
protected static SolidSlider InsertUiForSlider(FlowLayoutWidget wordOptionContainer, string header, double min = 0, double max = .5)
{
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
protected static SolidSlider InsertUiForSlider(FlowLayoutWidget wordOptionContainer, string header, double min = 0, double max = .5)
{
double scrollBarWidth = 10;
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
scrollBarWidth = 20;
}
TextWidget spacingText = new TextWidget(header, textColor: ActiveTheme.Instance.PrimaryTextColor);
spacingText.Margin = new BorderDouble(10, 3, 3, 5);
spacingText.HAnchor = HAnchor.ParentLeft;
wordOptionContainer.AddChild(spacingText);
SolidSlider namedSlider = new SolidSlider(new Vector2(), scrollBarWidth, 0, 1);
namedSlider.TotalWidthInPixels = DefaultScrollBarWidth;
namedSlider.Minimum = min;
namedSlider.Maximum = max;
namedSlider.Margin = new BorderDouble(3, 5, 3, 3);
namedSlider.HAnchor = HAnchor.ParentCenter;
namedSlider.View.BackgroundColor = new RGBA_Bytes();
wordOptionContainer.AddChild(namedSlider);
return namedSlider;
}
}
}
TextWidget spacingText = new TextWidget(header, textColor: ActiveTheme.Instance.PrimaryTextColor);
spacingText.Margin = new BorderDouble(10, 3, 3, 5);
spacingText.HAnchor = HAnchor.ParentLeft;
wordOptionContainer.AddChild(spacingText);
SolidSlider namedSlider = new SolidSlider(new Vector2(), scrollBarWidth, 0, 1);
namedSlider.TotalWidthInPixels = DefaultScrollBarWidth;
namedSlider.Minimum = min;
namedSlider.Maximum = max;
namedSlider.Margin = new BorderDouble(3, 5, 3, 3);
namedSlider.HAnchor = HAnchor.ParentCenter;
namedSlider.View.BackgroundColor = new RGBA_Bytes();
wordOptionContainer.AddChild(namedSlider);
return namedSlider;
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,98 +23,85 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.OpenGlGui;
using MatterHackers.PolygonMesh;
using MatterHackers.RenderOpenGl;
using MatterHackers.VectorMath;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintQueue;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class PartPreviewWidget : GuiWidget
{
protected readonly int ShortButtonHeight = 25;
protected int SideBarButtonWidth;
public class PartPreviewWidget : GuiWidget
{
protected readonly int ShortButtonHeight = 25;
protected int SideBarButtonWidth;
protected TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
protected TextImageButtonFactory checkboxButtonFactory = new TextImageButtonFactory();
protected TextImageButtonFactory expandMenuOptionFactory = new TextImageButtonFactory();
protected TextImageButtonFactory whiteButtonFactory = new TextImageButtonFactory();
protected TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
protected TextImageButtonFactory checkboxButtonFactory = new TextImageButtonFactory();
protected TextImageButtonFactory expandMenuOptionFactory = new TextImageButtonFactory();
protected TextImageButtonFactory whiteButtonFactory = new TextImageButtonFactory();
protected ViewControls2D viewControls2D;
protected ViewControls2D viewControls2D;
protected Cover buttonRightPanelDisabledCover;
protected FlowLayoutWidget buttonRightPanel;
protected Cover buttonRightPanelDisabledCover;
protected FlowLayoutWidget buttonRightPanel;
public PartPreviewWidget()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
SideBarButtonWidth = 180;
ShortButtonHeight = 40;
}
else
{
SideBarButtonWidth = 138;
ShortButtonHeight = 30;
}
textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
public PartPreviewWidget()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
SideBarButtonWidth = 180;
ShortButtonHeight = 40;
}
else
{
SideBarButtonWidth = 138;
ShortButtonHeight = 30;
}
whiteButtonFactory.FixedWidth = SideBarButtonWidth;
whiteButtonFactory.FixedHeight = ShortButtonHeight;
whiteButtonFactory.normalFillColor = RGBA_Bytes.White;
whiteButtonFactory.normalTextColor = RGBA_Bytes.Black;
whiteButtonFactory.hoverTextColor = RGBA_Bytes.Black;
whiteButtonFactory.hoverFillColor = new RGBA_Bytes(255, 255, 255, 200);
whiteButtonFactory.borderWidth = 1;
whiteButtonFactory.normalBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);
whiteButtonFactory.hoverBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);
textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.FixedWidth = SideBarButtonWidth;
expandMenuOptionFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.hoverFillColor = new RGBA_Bytes(255, 255, 255, 50);
expandMenuOptionFactory.pressedFillColor = new RGBA_Bytes(255, 255, 255, 50);
expandMenuOptionFactory.disabledFillColor = new RGBA_Bytes(255, 255, 255, 50);
whiteButtonFactory.FixedWidth = SideBarButtonWidth;
whiteButtonFactory.FixedHeight = ShortButtonHeight;
whiteButtonFactory.normalFillColor = RGBA_Bytes.White;
whiteButtonFactory.normalTextColor = RGBA_Bytes.Black;
whiteButtonFactory.hoverTextColor = RGBA_Bytes.Black;
whiteButtonFactory.hoverFillColor = new RGBA_Bytes(255, 255, 255, 200);
whiteButtonFactory.borderWidth = 1;
whiteButtonFactory.normalBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);
whiteButtonFactory.hoverBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);
checkboxButtonFactory.fontSize = 11;
checkboxButtonFactory.FixedWidth = SideBarButtonWidth;
checkboxButtonFactory.borderWidth = 3;
expandMenuOptionFactory.FixedWidth = SideBarButtonWidth;
expandMenuOptionFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
expandMenuOptionFactory.hoverFillColor = new RGBA_Bytes(255, 255, 255, 50);
expandMenuOptionFactory.pressedFillColor = new RGBA_Bytes(255, 255, 255, 50);
expandMenuOptionFactory.disabledFillColor = new RGBA_Bytes(255, 255, 255, 50);
checkboxButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.normalBorderColor = new RGBA_Bytes(0, 0, 0, 0);
checkboxButtonFactory.normalFillColor = ActiveTheme.Instance.PrimaryBackgroundColor;
checkboxButtonFactory.fontSize = 11;
checkboxButtonFactory.FixedWidth = SideBarButtonWidth;
checkboxButtonFactory.borderWidth = 3;
checkboxButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.hoverBorderColor = new RGBA_Bytes(0, 0, 0, 50);
checkboxButtonFactory.hoverFillColor = new RGBA_Bytes(0, 0, 0, 50);
checkboxButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.normalBorderColor = new RGBA_Bytes(0, 0, 0, 0);
checkboxButtonFactory.normalFillColor = ActiveTheme.Instance.PrimaryBackgroundColor;
checkboxButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.pressedBorderColor = new RGBA_Bytes(0, 0, 0, 50);
checkboxButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.hoverBorderColor = new RGBA_Bytes(0, 0, 0, 50);
checkboxButtonFactory.hoverFillColor = new RGBA_Bytes(0, 0, 0, 50);
checkboxButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
checkboxButtonFactory.pressedBorderColor = new RGBA_Bytes(0, 0, 0, 50);
BackgroundColor = RGBA_Bytes.White;
}
}
}
checkboxButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
BackgroundColor = RGBA_Bytes.White;
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,36 +23,35 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.IO;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.Agg;
using MatterHackers.Agg.PlatformAbstract;
using System.IO;
namespace MatterHackers.MatterControl.SettingsManagement
{
public class BedSettings
{
static BedSettings instance = null;
public class BedSettings
{
private static BedSettings instance = null;
public static BedSettings Instance
{
get
{
if (instance == null)
{
instance = new BedSettings();
}
public static BedSettings Instance
{
get
{
if (instance == null)
{
instance = new BedSettings();
}
return instance;
}
}
return instance;
}
}
public static void SetMakeAndModel(string make, string model)
{
public static void SetMakeAndModel(string make, string model)
{
string pathToBedSettings = Path.Combine("PrinterSettings", make, model, "BedSettings.json");
if (StaticData.Instance.FileExists(pathToBedSettings))
{
@ -63,13 +62,13 @@ namespace MatterHackers.MatterControl.SettingsManagement
{
instance = new BedSettings();
}
}
}
public RectangleInt ActualBedInImage;
public RectangleInt ActualBedInImage;
BedSettings()
{
//File.WriteAllText("test.json", Newtonsoft.Json.JsonConvert.SerializeObject(this));
}
}
}
private BedSettings()
{
//File.WriteAllText("test.json", Newtonsoft.Json.JsonConvert.SerializeObject(this));
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,317 +23,314 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using ClipperLib;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.ImageProcessing;
using MatterHackers.Agg.VertexSource;
using MatterHackers.MarchingSquares;
using MatterHackers.PolygonMesh;
using MatterHackers.VectorMath;
using ClipperLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace MatterHackers.MatterControl
{
using Polygon = List<IntPoint>;
using Polygons = List<List<IntPoint>>;
using Polygon = List<IntPoint>;
public static class CreateDiscreteMeshes
{
public static List<Mesh> SplitConnectedIntoMeshes(MeshGroup meshGroupToSplit, ReportProgressRatio reportProgress)
{
List<Mesh> discreteMeshes = new List<Mesh>();
double ratioPerDiscreetMesh = 1.0 / meshGroupToSplit.Meshes.Count;
double currentRatioDone = 0;
foreach (Mesh mesh in meshGroupToSplit.Meshes)
{
List<Mesh> discreteVolumes = SplitVolumesIntoMeshes(mesh, (double progress0To1, string processingState, out bool continueProcessing) =>
{
if (reportProgress != null)
{
double progress = (currentRatioDone + ratioPerDiscreetMesh * progress0To1);
reportProgress(progress, "Split Into Meshes", out continueProcessing);
}
else
{
continueProcessing = true;
}
});
discreteMeshes.AddRange(discreteVolumes);
using Polygons = List<List<IntPoint>>;
currentRatioDone += ratioPerDiscreetMesh;
}
public static class CreateDiscreteMeshes
{
public static List<Mesh> SplitConnectedIntoMeshes(MeshGroup meshGroupToSplit, ReportProgressRatio reportProgress)
{
List<Mesh> discreteMeshes = new List<Mesh>();
double ratioPerDiscreetMesh = 1.0 / meshGroupToSplit.Meshes.Count;
double currentRatioDone = 0;
foreach (Mesh mesh in meshGroupToSplit.Meshes)
{
List<Mesh> discreteVolumes = SplitVolumesIntoMeshes(mesh, (double progress0To1, string processingState, out bool continueProcessing) =>
{
if (reportProgress != null)
{
double progress = (currentRatioDone + ratioPerDiscreetMesh * progress0To1);
reportProgress(progress, "Split Into Meshes", out continueProcessing);
}
else
{
continueProcessing = true;
}
});
discreteMeshes.AddRange(discreteVolumes);
return discreteMeshes;
}
currentRatioDone += ratioPerDiscreetMesh;
}
public static List<Mesh> SplitVolumesIntoMeshes(Mesh meshToSplit, ReportProgressRatio reportProgress)
{
List<Mesh> discreetVolumes = new List<Mesh>();
HashSet<Face> facesThatHaveBeenAdded = new HashSet<Face>();
Mesh meshFromCurrentVolume = null;
Stack<Face> attachedFaces = new Stack<Face>();
for (int faceIndex = 0; faceIndex < meshToSplit.Faces.Count; faceIndex++)
{
Face currentFace = meshToSplit.Faces[faceIndex];
// If this face as not been added to any volume, create a new volume and add all of the attached faces.
if (!facesThatHaveBeenAdded.Contains(currentFace))
{
attachedFaces.Push(currentFace);
meshFromCurrentVolume = new Mesh();
return discreteMeshes;
}
MeshMaterialData materialDataToCopy = MeshMaterialData.Get(meshToSplit);
MeshMaterialData newMaterialData = MeshMaterialData.Get(meshFromCurrentVolume);
newMaterialData.MaterialIndex = materialDataToCopy.MaterialIndex;
public static List<Mesh> SplitVolumesIntoMeshes(Mesh meshToSplit, ReportProgressRatio reportProgress)
{
List<Mesh> discreetVolumes = new List<Mesh>();
HashSet<Face> facesThatHaveBeenAdded = new HashSet<Face>();
Mesh meshFromCurrentVolume = null;
Stack<Face> attachedFaces = new Stack<Face>();
for (int faceIndex = 0; faceIndex < meshToSplit.Faces.Count; faceIndex++)
{
Face currentFace = meshToSplit.Faces[faceIndex];
// If this face as not been added to any volume, create a new volume and add all of the attached faces.
if (!facesThatHaveBeenAdded.Contains(currentFace))
{
attachedFaces.Push(currentFace);
meshFromCurrentVolume = new Mesh();
while (attachedFaces.Count > 0)
{
Face faceToAdd = attachedFaces.Pop();
foreach (Vertex attachedVertex in faceToAdd.Vertices())
{
foreach (Face faceAttachedToVertex in attachedVertex.ConnectedFaces())
{
if (!facesThatHaveBeenAdded.Contains(faceAttachedToVertex))
{
// marke that this face has been taken care of
facesThatHaveBeenAdded.Add(faceAttachedToVertex);
// add it to the list of faces we need to walk
attachedFaces.Push(faceAttachedToVertex);
MeshMaterialData materialDataToCopy = MeshMaterialData.Get(meshToSplit);
MeshMaterialData newMaterialData = MeshMaterialData.Get(meshFromCurrentVolume);
newMaterialData.MaterialIndex = materialDataToCopy.MaterialIndex;
// Add a new face to the new mesh we are creating.
List<Vertex> faceVertices = new List<Vertex>();
foreach (FaceEdge faceEdgeToAdd in faceAttachedToVertex.FaceEdges())
{
Vertex newVertex = meshFromCurrentVolume.CreateVertex(faceEdgeToAdd.firstVertex.Position, CreateOption.CreateNew, SortOption.WillSortLater);
faceVertices.Add(newVertex);
}
while (attachedFaces.Count > 0)
{
Face faceToAdd = attachedFaces.Pop();
foreach (Vertex attachedVertex in faceToAdd.Vertices())
{
foreach (Face faceAttachedToVertex in attachedVertex.ConnectedFaces())
{
if (!facesThatHaveBeenAdded.Contains(faceAttachedToVertex))
{
// marke that this face has been taken care of
facesThatHaveBeenAdded.Add(faceAttachedToVertex);
// add it to the list of faces we need to walk
attachedFaces.Push(faceAttachedToVertex);
meshFromCurrentVolume.CreateFace(faceVertices.ToArray(), CreateOption.CreateNew);
}
}
}
}
// Add a new face to the new mesh we are creating.
List<Vertex> faceVertices = new List<Vertex>();
foreach (FaceEdge faceEdgeToAdd in faceAttachedToVertex.FaceEdges())
{
Vertex newVertex = meshFromCurrentVolume.CreateVertex(faceEdgeToAdd.firstVertex.Position, CreateOption.CreateNew, SortOption.WillSortLater);
faceVertices.Add(newVertex);
}
meshFromCurrentVolume.CleanAndMergMesh();
discreetVolumes.Add(meshFromCurrentVolume);
meshFromCurrentVolume = null;
}
if (reportProgress != null)
{
double progress = faceIndex / (double)meshToSplit.Faces.Count;
bool continueProcessing;
reportProgress(progress, "Split Into Meshes", out continueProcessing);
}
}
meshFromCurrentVolume.CreateFace(faceVertices.ToArray(), CreateOption.CreateNew);
}
}
}
}
return discreetVolumes;
}
meshFromCurrentVolume.CleanAndMergMesh();
discreetVolumes.Add(meshFromCurrentVolume);
meshFromCurrentVolume = null;
}
if (reportProgress != null)
{
double progress = faceIndex / (double)meshToSplit.Faces.Count;
bool continueProcessing;
reportProgress(progress, "Split Into Meshes", out continueProcessing);
}
}
public static Mesh[] SplitIntoMeshesOnOrthographicZ(Mesh meshToSplit, Vector3 buildVolume, BackgroundWorker backgroundWorker, int startPercent, int endPercent)
{
int lengthPercent = endPercent - startPercent;
// check if the part is bigger than the build plate (if it is we need to use that as our size)
AxisAlignedBoundingBox partBounds = meshToSplit.GetAxisAlignedBoundingBox();
return discreetVolumes;
}
buildVolume.x = Math.Max(buildVolume.x, partBounds.XSize + 2);
buildVolume.y = Math.Max(buildVolume.y, partBounds.YSize + 2);
buildVolume.z = Math.Max(buildVolume.z, partBounds.ZSize + 2);
public static Mesh[] SplitIntoMeshesOnOrthographicZ(Mesh meshToSplit, Vector3 buildVolume, BackgroundWorker backgroundWorker, int startPercent, int endPercent)
{
int lengthPercent = endPercent - startPercent;
// check if the part is bigger than the build plate (if it is we need to use that as our size)
AxisAlignedBoundingBox partBounds = meshToSplit.GetAxisAlignedBoundingBox();
// Find all the separate objects that are on the plate
// Create a 2D image the size of the printer bed at some scale with the parts draw on it top down
buildVolume.x = Math.Max(buildVolume.x, partBounds.XSize + 2);
buildVolume.y = Math.Max(buildVolume.y, partBounds.YSize + 2);
buildVolume.z = Math.Max(buildVolume.z, partBounds.ZSize + 2);
double scaleFactor = 5;
ImageBuffer partPlate = new ImageBuffer((int)(buildVolume.x * scaleFactor), (int)(buildVolume.y * scaleFactor), 32, new BlenderBGRA());
Vector2 renderOffset = new Vector2(buildVolume.x / 2, buildVolume.y / 2) - new Vector2(partBounds.Center.x, partBounds.Center.y);
// Find all the separate objects that are on the plate
// Create a 2D image the size of the printer bed at some scale with the parts draw on it top down
PolygonMesh.Rendering.OrthographicZProjection.DrawTo(partPlate.NewGraphics2D(), meshToSplit, renderOffset, scaleFactor, RGBA_Bytes.White);
double scaleFactor = 5;
ImageBuffer partPlate = new ImageBuffer((int)(buildVolume.x * scaleFactor), (int)(buildVolume.y * scaleFactor), 32, new BlenderBGRA());
Vector2 renderOffset = new Vector2(buildVolume.x / 2, buildVolume.y / 2) - new Vector2(partBounds.Center.x, partBounds.Center.y);
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent * .2));
}
PolygonMesh.Rendering.OrthographicZProjection.DrawTo(partPlate.NewGraphics2D(), meshToSplit, renderOffset, scaleFactor, RGBA_Bytes.White);
//ImageIO.SaveImageData("test part plate 0.png", partPlate);
// expand the bounds a bit so that we can collect all the vertices and polygons within each bound
Dilate.DoDilate3x3Binary(partPlate, 1);
//ImageIO.SaveImageData("test part plate 1.png", partPlate);
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent * .2));
}
// trace all the bounds of the objects on the plate
PolyTree polyTreeForPlate = FindDistictObjectBounds(partPlate);
if (polyTreeForPlate == null)
{
Mesh[] singleMesh = new Mesh[1];
singleMesh[0] = meshToSplit;
return singleMesh;
}
//ImageIO.SaveImageData("test part plate 0.png", partPlate);
// expand the bounds a bit so that we can collect all the vertices and polygons within each bound
Dilate.DoDilate3x3Binary(partPlate, 1);
//ImageIO.SaveImageData("test part plate 1.png", partPlate);
// get all the discrete areas that are polygons so we can search them
Polygons discreteAreas = new Polygons();
GetAreasRecursive(polyTreeForPlate, discreteAreas);
if (discreteAreas.Count == 0)
{
return null;
}
else if (discreteAreas.Count == 1)
{
Mesh[] singleMesh = new Mesh[1];
singleMesh[0] = meshToSplit;
return singleMesh;
}
// trace all the bounds of the objects on the plate
PolyTree polyTreeForPlate = FindDistictObjectBounds(partPlate);
if (polyTreeForPlate == null)
{
Mesh[] singleMesh = new Mesh[1];
singleMesh[0] = meshToSplit;
return singleMesh;
}
Graphics2D graphics2D = partPlate.NewGraphics2D();
graphics2D.Clear(RGBA_Bytes.Black);
Random rand = new Random();
foreach (Polygon polygon in discreteAreas)
{
graphics2D.Render(PlatingHelper.PolygonToPathStorage(polygon), new RGBA_Bytes(rand.Next(128, 255), rand.Next(128, 255), rand.Next(128, 255)));
}
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent * .50));
}
//ImageIO.SaveImageData("test part plate 2.png", partPlate);
// get all the discrete areas that are polygons so we can search them
Polygons discreteAreas = new Polygons();
GetAreasRecursive(polyTreeForPlate, discreteAreas);
if (discreteAreas.Count == 0)
{
return null;
}
else if (discreteAreas.Count == 1)
{
Mesh[] singleMesh = new Mesh[1];
singleMesh[0] = meshToSplit;
return singleMesh;
}
// add each of the separate bounds polygons to new meshes
Mesh[] discreteMeshes = new Mesh[discreteAreas.Count];
for (int i = 0; i < discreteAreas.Count; i++)
{
discreteMeshes[i] = new Mesh();
}
Graphics2D graphics2D = partPlate.NewGraphics2D();
graphics2D.Clear(RGBA_Bytes.Black);
Random rand = new Random();
foreach (Polygon polygon in discreteAreas)
{
graphics2D.Render(PlatingHelper.PolygonToPathStorage(polygon), new RGBA_Bytes(rand.Next(128, 255), rand.Next(128, 255), rand.Next(128, 255)));
}
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent * .50));
}
//ImageIO.SaveImageData("test part plate 2.png", partPlate);
foreach (Face face in meshToSplit.Faces)
{
bool faceDone = false;
// figure out which area one or more of the vertices are in add the face to the right new mesh
foreach (FaceEdge faceEdge in face.FaceEdges())
{
Vector2 position = new Vector2(faceEdge.firstVertex.Position.x, faceEdge.firstVertex.Position.y);
position += renderOffset;
position *= scaleFactor;
// add each of the separate bounds polygons to new meshes
Mesh[] discreteMeshes = new Mesh[discreteAreas.Count];
for (int i = 0; i < discreteAreas.Count; i++)
{
discreteMeshes[i] = new Mesh();
}
for (int areaIndex = discreteAreas.Count-1; areaIndex >= 0; areaIndex--)
{
if (PointInPolygon(discreteAreas[areaIndex], new IntPoint((int)position.x, (int)position.y)))
{
List<Vertex> faceVertices = new List<Vertex>();
foreach (FaceEdge faceEdgeToAdd in face.FaceEdges())
{
Vertex newVertex = discreteMeshes[areaIndex].CreateVertex(faceEdgeToAdd.firstVertex.Position);
faceVertices.Add(newVertex);
}
foreach (Face face in meshToSplit.Faces)
{
bool faceDone = false;
// figure out which area one or more of the vertices are in add the face to the right new mesh
foreach (FaceEdge faceEdge in face.FaceEdges())
{
Vector2 position = new Vector2(faceEdge.firstVertex.Position.x, faceEdge.firstVertex.Position.y);
position += renderOffset;
position *= scaleFactor;
discreteMeshes[areaIndex].CreateFace(faceVertices.ToArray());
faceDone = true;
break;
}
}
for (int areaIndex = discreteAreas.Count - 1; areaIndex >= 0; areaIndex--)
{
if (PointInPolygon(discreteAreas[areaIndex], new IntPoint((int)position.x, (int)position.y)))
{
List<Vertex> faceVertices = new List<Vertex>();
foreach (FaceEdge faceEdgeToAdd in face.FaceEdges())
{
Vertex newVertex = discreteMeshes[areaIndex].CreateVertex(faceEdgeToAdd.firstVertex.Position);
faceVertices.Add(newVertex);
}
if (faceDone)
{
break;
}
}
}
discreteMeshes[areaIndex].CreateFace(faceVertices.ToArray());
faceDone = true;
break;
}
}
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent));
}
if (faceDone)
{
break;
}
}
}
for (int i = 0; i < discreteMeshes.Count(); i++)
{
Mesh mesh = discreteMeshes[i];
}
if (backgroundWorker != null)
{
backgroundWorker.ReportProgress(startPercent + (int)(lengthPercent));
}
return discreteMeshes;
}
for (int i = 0; i < discreteMeshes.Count(); i++)
{
Mesh mesh = discreteMeshes[i];
}
public static bool PointInPolygon(Polygon polygon, IntPoint testPosition)
{
int numPoints = polygon.Count;
bool result = false;
for (int i = 0; i < numPoints; i++)
{
int prevIndex = i - 1;
if(prevIndex < 0)
{
prevIndex += numPoints;
}
return discreteMeshes;
}
if ((((polygon[i].Y <= testPosition.Y) && (testPosition.Y < polygon[prevIndex].Y))
|| ((polygon[prevIndex].Y <= testPosition.Y) && (testPosition.Y < polygon[i].Y)))
&& (testPosition.X - polygon[i].X < (polygon[prevIndex].X - polygon[i].X) * (testPosition.Y - polygon[i].Y) / (polygon[prevIndex].Y - polygon[i].Y)))
{
result = !result;
}
}
public static bool PointInPolygon(Polygon polygon, IntPoint testPosition)
{
int numPoints = polygon.Count;
bool result = false;
for (int i = 0; i < numPoints; i++)
{
int prevIndex = i - 1;
if (prevIndex < 0)
{
prevIndex += numPoints;
}
return result;
}
if ((((polygon[i].Y <= testPosition.Y) && (testPosition.Y < polygon[prevIndex].Y))
|| ((polygon[prevIndex].Y <= testPosition.Y) && (testPosition.Y < polygon[i].Y)))
&& (testPosition.X - polygon[i].X < (polygon[prevIndex].X - polygon[i].X) * (testPosition.Y - polygon[i].Y) / (polygon[prevIndex].Y - polygon[i].Y)))
{
result = !result;
}
}
static private void GetAreasRecursive(PolyNode polyTreeForPlate, Polygons discreteAreas)
{
if (!polyTreeForPlate.IsHole)
{
discreteAreas.Add(polyTreeForPlate.Contour);
}
return result;
}
foreach (PolyNode child in polyTreeForPlate.Childs)
{
GetAreasRecursive(child, discreteAreas);
}
}
static private void GetAreasRecursive(PolyNode polyTreeForPlate, Polygons discreteAreas)
{
if (!polyTreeForPlate.IsHole)
{
discreteAreas.Add(polyTreeForPlate.Contour);
}
static public PolyTree FindDistictObjectBounds(ImageBuffer image)
{
MarchingSquaresByte marchingSquaresData = new MarchingSquaresByte(image, 5, 0);
marchingSquaresData.CreateLineSegments();
Polygons lineLoops = marchingSquaresData.CreateLineLoops(1);
foreach (PolyNode child in polyTreeForPlate.Childs)
{
GetAreasRecursive(child, discreteAreas);
}
}
if (lineLoops.Count == 1)
{
return null;
}
static public PolyTree FindDistictObjectBounds(ImageBuffer image)
{
MarchingSquaresByte marchingSquaresData = new MarchingSquaresByte(image, 5, 0);
marchingSquaresData.CreateLineSegments();
Polygons lineLoops = marchingSquaresData.CreateLineLoops(1);
// create a bounding polygon to clip against
IntPoint min = new IntPoint(long.MaxValue, long.MaxValue);
IntPoint max = new IntPoint(long.MinValue, long.MinValue);
foreach (Polygon polygon in lineLoops)
{
foreach (IntPoint point in polygon)
{
min.X = Math.Min(point.X - 10, min.X);
min.Y = Math.Min(point.Y - 10, min.Y);
max.X = Math.Max(point.X + 10, max.X);
max.Y = Math.Max(point.Y + 10, max.Y);
}
}
if (lineLoops.Count == 1)
{
return null;
}
Polygon boundingPoly = new Polygon();
boundingPoly.Add(min);
boundingPoly.Add(new IntPoint(min.X, max.Y));
boundingPoly.Add(max);
boundingPoly.Add(new IntPoint(max.X, min.Y));
// create a bounding polygon to clip against
IntPoint min = new IntPoint(long.MaxValue, long.MaxValue);
IntPoint max = new IntPoint(long.MinValue, long.MinValue);
foreach (Polygon polygon in lineLoops)
{
foreach (IntPoint point in polygon)
{
min.X = Math.Min(point.X - 10, min.X);
min.Y = Math.Min(point.Y - 10, min.Y);
max.X = Math.Max(point.X + 10, max.X);
max.Y = Math.Max(point.Y + 10, max.Y);
}
}
// now clip the polygons to get the inside and outside polys
Clipper clipper = new Clipper();
clipper.AddPaths(lineLoops, PolyType.ptSubject, true);
clipper.AddPath(boundingPoly, PolyType.ptClip, true);
Polygon boundingPoly = new Polygon();
boundingPoly.Add(min);
boundingPoly.Add(new IntPoint(min.X, max.Y));
boundingPoly.Add(max);
boundingPoly.Add(new IntPoint(max.X, min.Y));
PolyTree polyTreeForPlate = new PolyTree();
clipper.Execute(ClipType.ctIntersection, polyTreeForPlate);
// now clip the polygons to get the inside and outside polys
Clipper clipper = new Clipper();
clipper.AddPaths(lineLoops, PolyType.ptSubject, true);
clipper.AddPath(boundingPoly, PolyType.ptClip, true);
return polyTreeForPlate;
}
}
}
PolyTree polyTreeForPlate = new PolyTree();
clipper.Execute(ClipType.ctIntersection, polyTreeForPlate);
return polyTreeForPlate;
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,151 +23,148 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Diagnostics;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.Font;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
using MatterHackers.Agg.PlatformAbstract;
using System;
using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class PartPreviewContent : GuiWidget
{
event EventHandler unregisterEvents;
public class PartPreviewContent : GuiWidget
{
private event EventHandler unregisterEvents;
View3DWidget partPreviewView;
ViewGcodeBasic viewGcodeBasic;
TabControl tabControl;
TabPage layerView;
View3DWidget.AutoRotate autoRotate3DView;
View3DWidget.OpenMode openMode;
View3DWidget.WindowMode windowMode;
private View3DWidget partPreviewView;
private ViewGcodeBasic viewGcodeBasic;
private TabControl tabControl;
private TabPage layerView;
private View3DWidget.AutoRotate autoRotate3DView;
private View3DWidget.OpenMode openMode;
private View3DWidget.WindowMode windowMode;
public PartPreviewContent(PrintItemWrapper printItem, View3DWidget.WindowMode windowMode, View3DWidget.AutoRotate autoRotate3DView, View3DWidget.OpenMode openMode = View3DWidget.OpenMode.Viewing)
{
this.openMode = openMode;
this.autoRotate3DView = autoRotate3DView;
this.windowMode = windowMode;
public PartPreviewContent(PrintItemWrapper printItem, View3DWidget.WindowMode windowMode, View3DWidget.AutoRotate autoRotate3DView, View3DWidget.OpenMode openMode = View3DWidget.OpenMode.Viewing)
{
this.openMode = openMode;
this.autoRotate3DView = autoRotate3DView;
this.windowMode = windowMode;
BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
this.AnchorAll();
this.Load(printItem);
BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
this.AnchorAll();
this.Load(printItem);
// We do this after showing the system window so that when we try and take focus of the parent window (the system window)
// it exists and can give the focus to its child the gcode window.
if (printItem != null
&& Path.GetExtension(printItem.FileLocation).ToUpper() == ".GCODE")
{
SwitchToGcodeView();
}
}
// We do this after showing the system window so that when we try and take focus of the parent window (the system window)
// it exists and can give the focus to its child the gcode window.
if (printItem != null
&& Path.GetExtension(printItem.FileLocation).ToUpper() == ".GCODE")
{
SwitchToGcodeView();
}
}
public void Reload(PrintItemWrapper printItem)
{
this.RemoveAllChildren();
this.Load(printItem);
}
public void Reload(PrintItemWrapper printItem)
{
this.RemoveAllChildren();
this.Load(printItem);
}
void Load(PrintItemWrapper printItem)
{
tabControl = new TabControl();
tabControl.TabBar.BorderColor = new RGBA_Bytes(0, 0, 0, 0);
private void Load(PrintItemWrapper printItem)
{
tabControl = new TabControl();
tabControl.TabBar.BorderColor = new RGBA_Bytes(0, 0, 0, 0);
tabControl.TabBar.Padding = new BorderDouble(top: 6);
tabControl.TabBar.Padding = new BorderDouble(top: 6);
RGBA_Bytes selectedTabColor;
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Responsive)
{
tabControl.TabBar.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
selectedTabColor = ActiveTheme.Instance.TabLabelSelected;
}
else
{
tabControl.TabBar.BackgroundColor = ActiveTheme.Instance.TransparentLightOverlay;
selectedTabColor = ActiveTheme.Instance.SecondaryAccentColor;
}
RGBA_Bytes selectedTabColor;
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Responsive)
{
tabControl.TabBar.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
selectedTabColor = ActiveTheme.Instance.TabLabelSelected;
}
else
{
tabControl.TabBar.BackgroundColor = ActiveTheme.Instance.TransparentLightOverlay;
selectedTabColor = ActiveTheme.Instance.SecondaryAccentColor;
}
double buildHeight = ActiveSliceSettings.Instance.BuildHeight;
double buildHeight = ActiveSliceSettings.Instance.BuildHeight;
// put in the 3D view
string part3DViewLabelFull = string.Format("{0} {1} ", "3D", "View".Localize()).ToUpper();
// put in the 3D view
string part3DViewLabelFull = string.Format("{0} {1} ", "3D", "View".Localize()).ToUpper();
partPreviewView = new View3DWidget(printItem,
new Vector3(ActiveSliceSettings.Instance.BedSize, buildHeight),
ActiveSliceSettings.Instance.BedCenter,
ActiveSliceSettings.Instance.BedShape,
windowMode,
autoRotate3DView,
openMode);
partPreviewView = new View3DWidget(printItem,
new Vector3(ActiveSliceSettings.Instance.BedSize, buildHeight),
ActiveSliceSettings.Instance.BedCenter,
ActiveSliceSettings.Instance.BedShape,
windowMode,
autoRotate3DView,
openMode);
partPreviewView.Closed += (sender, e) =>
{
Close();
};
partPreviewView.Closed += (sender, e) =>
{
Close();
};
TabPage partPreview3DView = new TabPage(partPreviewView, part3DViewLabelFull);
TabPage partPreview3DView = new TabPage(partPreviewView, part3DViewLabelFull);
// put in the gcode view
ViewGcodeBasic.WindowMode gcodeWindowMode = ViewGcodeBasic.WindowMode.Embeded;
if (windowMode == View3DWidget.WindowMode.StandAlone)
{
gcodeWindowMode = ViewGcodeBasic.WindowMode.StandAlone;
}
// put in the gcode view
ViewGcodeBasic.WindowMode gcodeWindowMode = ViewGcodeBasic.WindowMode.Embeded;
if (windowMode == View3DWidget.WindowMode.StandAlone)
{
gcodeWindowMode = ViewGcodeBasic.WindowMode.StandAlone;
}
viewGcodeBasic = new ViewGcodeBasic(printItem,
new Vector3(ActiveSliceSettings.Instance.BedSize, buildHeight),
ActiveSliceSettings.Instance.BedCenter,
ActiveSliceSettings.Instance.BedShape, gcodeWindowMode);
viewGcodeBasic = new ViewGcodeBasic(printItem,
new Vector3(ActiveSliceSettings.Instance.BedSize, buildHeight),
ActiveSliceSettings.Instance.BedCenter,
ActiveSliceSettings.Instance.BedShape, gcodeWindowMode);
viewGcodeBasic.Closed += (sender, e) =>
{
Close();
};
viewGcodeBasic.Closed += (sender, e) =>
{
Close();
};
layerView = new TabPage(viewGcodeBasic, LocalizedString.Get("Layer View").ToUpper());
layerView = new TabPage(viewGcodeBasic, LocalizedString.Get("Layer View").ToUpper());
int tabPointSize = 16;
// add the correct tabs based on wether we are stand alone or embeded
if (windowMode == View3DWidget.WindowMode.StandAlone || OsInformation.OperatingSystem == OSType.Android)
{
tabControl.AddTab(new SimpleTextTabWidget(partPreview3DView, "3D View Tab", tabPointSize,
selectedTabColor, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes()));
tabControl.AddTab(new SimpleTextTabWidget(layerView, "Layer View Tab", tabPointSize,
selectedTabColor, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes()));
}
else
{
tabControl.AddTab(new PopOutTextTabWidget(partPreview3DView, "3D View Tab", new Vector2(590, 400), tabPointSize));
tabControl.AddTab(new PopOutTextTabWidget(layerView, "Layer View Tab", new Vector2(590, 400), tabPointSize));
}
int tabPointSize = 16;
// add the correct tabs based on wether we are stand alone or embeded
if (windowMode == View3DWidget.WindowMode.StandAlone || OsInformation.OperatingSystem == OSType.Android)
{
tabControl.AddTab(new SimpleTextTabWidget(partPreview3DView, "3D View Tab", tabPointSize,
selectedTabColor, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes()));
tabControl.AddTab(new SimpleTextTabWidget(layerView, "Layer View Tab", tabPointSize,
selectedTabColor, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes()));
}
else
{
tabControl.AddTab(new PopOutTextTabWidget(partPreview3DView, "3D View Tab", new Vector2(590, 400), tabPointSize));
tabControl.AddTab(new PopOutTextTabWidget(layerView, "Layer View Tab", new Vector2(590, 400), tabPointSize));
}
this.AddChild(tabControl);
}
this.AddChild(tabControl);
}
public void SwitchToGcodeView()
{
tabControl.TabBar.SwitchToPage(layerView);
viewGcodeBasic.Focus();
}
public void SwitchToGcodeView()
{
tabControl.TabBar.SwitchToPage(layerView);
viewGcodeBasic.Focus();
}
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
}
}
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,41 +23,37 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Diagnostics;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.Font;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
using System;
using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class PartPreviewMainWindow : SystemWindow
{
event EventHandler unregisterEvents;
PartPreviewContent partPreviewWidget;
public class PartPreviewMainWindow : SystemWindow
{
private event EventHandler unregisterEvents;
public PartPreviewMainWindow(PrintItemWrapper printItem, View3DWidget.AutoRotate autoRotate3DView, View3DWidget.OpenMode openMode = View3DWidget.OpenMode.Viewing)
: base(690, 340)
{
UseOpenGL = true;
string partPreviewTitle = LocalizedString.Get("MatterControl");
Title = string.Format("{0}: ", partPreviewTitle) + Path.GetFileName(printItem.Name);
private PartPreviewContent partPreviewWidget;
partPreviewWidget = new PartPreviewContent(printItem, View3DWidget.WindowMode.StandAlone, autoRotate3DView, openMode);
partPreviewWidget.Closed += (sender, e) =>
{
Close();
};
public PartPreviewMainWindow(PrintItemWrapper printItem, View3DWidget.AutoRotate autoRotate3DView, View3DWidget.OpenMode openMode = View3DWidget.OpenMode.Viewing)
: base(690, 340)
{
UseOpenGL = true;
string partPreviewTitle = LocalizedString.Get("MatterControl");
Title = string.Format("{0}: ", partPreviewTitle) + Path.GetFileName(printItem.Name);
partPreviewWidget = new PartPreviewContent(printItem, View3DWidget.WindowMode.StandAlone, autoRotate3DView, openMode);
partPreviewWidget.Closed += (sender, e) =>
{
Close();
};
#if __ANDROID__
TerminalWidget terminalWidget = new TerminalWidget(true);
@ -69,30 +65,30 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
AddHandlers();
Width = 640;
Height = 480;
Width = 640;
Height = 480;
MinimumSize = new Vector2(400, 300);
ShowAsSystemWindow();
}
MinimumSize = new Vector2(400, 300);
ShowAsSystemWindow();
}
private void AddHandlers()
{
ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
}
private void AddHandlers()
{
ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
}
public void ThemeChanged(object sender, EventArgs e)
{
this.Invalidate();
}
public void ThemeChanged(object sender, EventArgs e)
{
this.Invalidate();
}
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
}
}
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,105 +23,99 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using ClipperLib;
using MatterHackers.Agg;
using MatterHackers.Agg.VertexSource;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
using MatterHackers.RayTracer;
using MatterHackers.VectorMath;
using MatterHackers.MeshVisualizer;
using System;
using System.Collections.Generic;
namespace MatterHackers.MatterControl
{
using Polygon = List<IntPoint>;
using Polygons = List<List<IntPoint>>;
using Polygon = List<IntPoint>;
public class PlatingMeshGroupData
{
public Vector3 currentScale = new Vector3(1,1,1);
public double xSpacing;
public List<IPrimitive> meshTraceableData = new List<IPrimitive>();
}
using Polygons = List<List<IntPoint>>;
public static class PlatingHelper
{
public static PathStorage PolygonToPathStorage(Polygon polygon)
{
PathStorage output = new PathStorage();
public class PlatingMeshGroupData
{
public Vector3 currentScale = new Vector3(1, 1, 1);
public double xSpacing;
public List<IPrimitive> meshTraceableData = new List<IPrimitive>();
}
bool first = true;
foreach (IntPoint point in polygon)
{
if (first)
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandMoveTo);
first = false;
}
else
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandLineTo);
}
}
public static class PlatingHelper
{
public static PathStorage PolygonToPathStorage(Polygon polygon)
{
PathStorage output = new PathStorage();
output.ClosePolygon();
bool first = true;
foreach (IntPoint point in polygon)
{
if (first)
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandMoveTo);
first = false;
}
else
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandLineTo);
}
}
output.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop);
output.ClosePolygon();
return output;
}
output.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop);
public static PathStorage PolygonToPathStorage(Polygons polygons)
{
PathStorage output = new PathStorage();
return output;
}
foreach (Polygon polygon in polygons)
{
bool first = true;
foreach (IntPoint point in polygon)
{
if (first)
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandMoveTo);
first = false;
}
else
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandLineTo);
}
}
public static PathStorage PolygonToPathStorage(Polygons polygons)
{
PathStorage output = new PathStorage();
output.ClosePolygon();
}
output.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop);
foreach (Polygon polygon in polygons)
{
bool first = true;
foreach (IntPoint point in polygon)
{
if (first)
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandMoveTo);
first = false;
}
else
{
output.Add(point.X, point.Y, ShapePath.FlagsAndCommand.CommandLineTo);
}
}
return output;
}
output.ClosePolygon();
}
output.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop);
public static void PlaceMeshGroupOnBed(List<MeshGroup> meshesGroupList, List<ScaleRotateTranslate> meshTransforms, int index)
{
AxisAlignedBoundingBox bounds = meshesGroupList[index].GetAxisAlignedBoundingBox(meshTransforms[index].TotalTransform);
Vector3 boundsCenter = (bounds.maxXYZ + bounds.minXYZ) / 2;
return output;
}
ScaleRotateTranslate moved = meshTransforms[index];
moved.translation *= Matrix4X4.CreateTranslation(new Vector3(0, 0, -boundsCenter.z + bounds.ZSize / 2));
meshTransforms[index] = moved;
}
public static void PlaceMeshGroupOnBed(List<MeshGroup> meshesGroupList, List<ScaleRotateTranslate> meshTransforms, int index)
{
AxisAlignedBoundingBox bounds = meshesGroupList[index].GetAxisAlignedBoundingBox(meshTransforms[index].TotalTransform);
Vector3 boundsCenter = (bounds.maxXYZ + bounds.minXYZ) / 2;
ScaleRotateTranslate moved = meshTransforms[index];
moved.translation *= Matrix4X4.CreateTranslation(new Vector3(0, 0, -boundsCenter.z + bounds.ZSize / 2));
meshTransforms[index] = moved;
}
public static void CenterMeshGroupXY(List<MeshGroup> meshesGroupList, List<ScaleRotateTranslate> meshTransforms, int index)
{
{
AxisAlignedBoundingBox bounds = meshesGroupList[index].GetAxisAlignedBoundingBox(meshTransforms[index].TotalTransform);
Vector3 boundsCenter = (bounds.maxXYZ + bounds.minXYZ) / 2;
@ -130,160 +124,160 @@ namespace MatterHackers.MatterControl
meshTransforms[index] = moved;
}
public static void FindPositionForGroupAndAddToPlate(MeshGroup meshGroupToAdd, ScaleRotateTranslate meshTransform, List<PlatingMeshGroupData> perMeshInfo, List<MeshGroup> meshesGroupsToAvoid, List<ScaleRotateTranslate> meshTransforms)
{
if (meshGroupToAdd == null || meshGroupToAdd.Meshes.Count < 1)
{
return;
}
public static void FindPositionForGroupAndAddToPlate(MeshGroup meshGroupToAdd, ScaleRotateTranslate meshTransform, List<PlatingMeshGroupData> perMeshInfo, List<MeshGroup> meshesGroupsToAvoid, List<ScaleRotateTranslate> meshTransforms)
{
if (meshGroupToAdd == null || meshGroupToAdd.Meshes.Count < 1)
{
return;
}
meshesGroupsToAvoid.Add(meshGroupToAdd);
meshesGroupsToAvoid.Add(meshGroupToAdd);
PlatingMeshGroupData newMeshInfo = new PlatingMeshGroupData();
perMeshInfo.Add(newMeshInfo);
meshTransform.SetCenteringForMeshGroup(meshGroupToAdd);
meshTransforms.Add(meshTransform);
PlatingMeshGroupData newMeshInfo = new PlatingMeshGroupData();
perMeshInfo.Add(newMeshInfo);
meshTransform.SetCenteringForMeshGroup(meshGroupToAdd);
meshTransforms.Add(meshTransform);
int meshGroupIndex = meshesGroupsToAvoid.Count - 1;
// now actually center the part we are going to finde a position for
CenterMeshGroupXY(meshesGroupsToAvoid, meshTransforms, meshGroupIndex);
MoveMeshGroupToOpenPosition(meshGroupIndex, perMeshInfo, meshesGroupsToAvoid, meshTransforms);
MoveMeshGroupToOpenPosition(meshGroupIndex, perMeshInfo, meshesGroupsToAvoid, meshTransforms);
PlaceMeshGroupOnBed(meshesGroupsToAvoid, meshTransforms, meshGroupIndex);
}
PlaceMeshGroupOnBed(meshesGroupsToAvoid, meshTransforms, meshGroupIndex);
}
public static void MoveMeshGroupToOpenPosition(int meshGroupToMoveIndex, List<PlatingMeshGroupData> perMeshInfo, List<MeshGroup> allMeshGroups, List<ScaleRotateTranslate> meshTransforms)
{
MeshGroup meshGroupToMove = allMeshGroups[meshGroupToMoveIndex];
// find a place to put it that doesn't hit anything
AxisAlignedBoundingBox meshToMoveBounds = meshGroupToMove.GetAxisAlignedBoundingBox(meshTransforms[meshGroupToMoveIndex].TotalTransform);
// add in a few mm so that it will not be touching
meshToMoveBounds.minXYZ -= new Vector3(2, 2, 0);
meshToMoveBounds.maxXYZ += new Vector3(2, 2, 0);
double ringDist = Math.Min(meshToMoveBounds.XSize, meshToMoveBounds.YSize);
double currentDist = 0;
double angle = 0;
double angleIncrement = MathHelper.Tau / 64;
Matrix4X4 transform;
while (true)
{
Matrix4X4 positionTransform = Matrix4X4.CreateTranslation(currentDist, 0, 0);
positionTransform *= Matrix4X4.CreateRotationZ(angle);
Vector3 newPosition = Vector3.Transform(Vector3.Zero, positionTransform);
transform = Matrix4X4.CreateTranslation(newPosition);
AxisAlignedBoundingBox testBounds = meshToMoveBounds.NewTransformed(transform);
bool foundHit = false;
for(int i=0; i<allMeshGroups.Count; i++)
{
MeshGroup meshToTest = allMeshGroups[i];
if (meshToTest != meshGroupToMove)
{
AxisAlignedBoundingBox existingMeshBounds = meshToTest.GetAxisAlignedBoundingBox(meshTransforms[i].TotalTransform);
AxisAlignedBoundingBox intersection = AxisAlignedBoundingBox.Intersection(testBounds, existingMeshBounds);
if (intersection.XSize > 0 && intersection.YSize > 0)
{
foundHit = true;
break;
}
}
}
public static void MoveMeshGroupToOpenPosition(int meshGroupToMoveIndex, List<PlatingMeshGroupData> perMeshInfo, List<MeshGroup> allMeshGroups, List<ScaleRotateTranslate> meshTransforms)
{
MeshGroup meshGroupToMove = allMeshGroups[meshGroupToMoveIndex];
// find a place to put it that doesn't hit anything
AxisAlignedBoundingBox meshToMoveBounds = meshGroupToMove.GetAxisAlignedBoundingBox(meshTransforms[meshGroupToMoveIndex].TotalTransform);
// add in a few mm so that it will not be touching
meshToMoveBounds.minXYZ -= new Vector3(2, 2, 0);
meshToMoveBounds.maxXYZ += new Vector3(2, 2, 0);
double ringDist = Math.Min(meshToMoveBounds.XSize, meshToMoveBounds.YSize);
double currentDist = 0;
double angle = 0;
double angleIncrement = MathHelper.Tau / 64;
Matrix4X4 transform;
while (true)
{
Matrix4X4 positionTransform = Matrix4X4.CreateTranslation(currentDist, 0, 0);
positionTransform *= Matrix4X4.CreateRotationZ(angle);
Vector3 newPosition = Vector3.Transform(Vector3.Zero, positionTransform);
transform = Matrix4X4.CreateTranslation(newPosition);
AxisAlignedBoundingBox testBounds = meshToMoveBounds.NewTransformed(transform);
bool foundHit = false;
for (int i = 0; i < allMeshGroups.Count; i++)
{
MeshGroup meshToTest = allMeshGroups[i];
if (meshToTest != meshGroupToMove)
{
AxisAlignedBoundingBox existingMeshBounds = meshToTest.GetAxisAlignedBoundingBox(meshTransforms[i].TotalTransform);
AxisAlignedBoundingBox intersection = AxisAlignedBoundingBox.Intersection(testBounds, existingMeshBounds);
if (intersection.XSize > 0 && intersection.YSize > 0)
{
foundHit = true;
break;
}
}
}
if (!foundHit)
{
break;
}
if (!foundHit)
{
break;
}
angle += angleIncrement;
if (angle >= MathHelper.Tau)
{
angle = 0;
currentDist += ringDist;
}
}
angle += angleIncrement;
if (angle >= MathHelper.Tau)
{
angle = 0;
currentDist += ringDist;
}
}
ScaleRotateTranslate moved = meshTransforms[meshGroupToMoveIndex];
moved.translation *= transform;
meshTransforms[meshGroupToMoveIndex] = moved;
}
ScaleRotateTranslate moved = meshTransforms[meshGroupToMoveIndex];
moved.translation *= transform;
meshTransforms[meshGroupToMoveIndex] = moved;
}
public static void CreateITraceableForMeshGroup(List<PlatingMeshGroupData> perMeshGroupInfo, List<MeshGroup> meshGroups, int meshGroupIndex, ReportProgressRatio reportProgress)
{
if (meshGroups != null)
{
MeshGroup meshGroup = meshGroups[meshGroupIndex];
perMeshGroupInfo[meshGroupIndex].meshTraceableData.Clear();
int totalActionCount = 0;
foreach(Mesh mesh in meshGroup.Meshes)
{
totalActionCount += mesh.Faces.Count;
}
int currentAction = 0;
bool needUpdateTitle = true;
for(int i=0; i<meshGroup.Meshes.Count; i++)
{
Mesh mesh = meshGroup.Meshes[i];
List<IPrimitive> allPolys = AddTraceDataForMesh(mesh, totalActionCount, ref currentAction, ref needUpdateTitle, reportProgress);
public static void CreateITraceableForMeshGroup(List<PlatingMeshGroupData> perMeshGroupInfo, List<MeshGroup> meshGroups, int meshGroupIndex, ReportProgressRatio reportProgress)
{
if (meshGroups != null)
{
MeshGroup meshGroup = meshGroups[meshGroupIndex];
perMeshGroupInfo[meshGroupIndex].meshTraceableData.Clear();
int totalActionCount = 0;
foreach (Mesh mesh in meshGroup.Meshes)
{
totalActionCount += mesh.Faces.Count;
}
int currentAction = 0;
bool needUpdateTitle = true;
for (int i = 0; i < meshGroup.Meshes.Count; i++)
{
Mesh mesh = meshGroup.Meshes[i];
List<IPrimitive> allPolys = AddTraceDataForMesh(mesh, totalActionCount, ref currentAction, ref needUpdateTitle, reportProgress);
needUpdateTitle = true;
if (reportProgress != null)
{
bool continueProcessing;
reportProgress(currentAction / (double)totalActionCount, "Creating Trace Group", out continueProcessing);
}
needUpdateTitle = true;
if (reportProgress != null)
{
bool continueProcessing;
reportProgress(currentAction / (double)totalActionCount, "Creating Trace Group", out continueProcessing);
}
// only allow limited recusion to speed this up building this data
IPrimitive traceData = BoundingVolumeHierarchy.CreateNewHierachy(allPolys, 0);
perMeshGroupInfo[meshGroupIndex].meshTraceableData.Add(traceData);
}
}
}
// only allow limited recusion to speed this up building this data
IPrimitive traceData = BoundingVolumeHierarchy.CreateNewHierachy(allPolys, 0);
perMeshGroupInfo[meshGroupIndex].meshTraceableData.Add(traceData);
}
}
}
public static IPrimitive CreateTraceDataForMesh(Mesh mesh)
{
int unusedInt = 0;
bool unusedBool = false;
List<IPrimitive> allPolys = AddTraceDataForMesh(mesh, 0, ref unusedInt, ref unusedBool, null);
return BoundingVolumeHierarchy.CreateNewHierachy(allPolys);
}
public static IPrimitive CreateTraceDataForMesh(Mesh mesh)
{
int unusedInt = 0;
bool unusedBool = false;
List<IPrimitive> allPolys = AddTraceDataForMesh(mesh, 0, ref unusedInt, ref unusedBool, null);
return BoundingVolumeHierarchy.CreateNewHierachy(allPolys);
}
private static List<IPrimitive> AddTraceDataForMesh(Mesh mesh, int totalActionCount, ref int currentAction, ref bool needToUpdateProgressReport, ReportProgressRatio reportProgress)
{
bool continueProcessing;
private static List<IPrimitive> AddTraceDataForMesh(Mesh mesh, int totalActionCount, ref int currentAction, ref bool needToUpdateProgressReport, ReportProgressRatio reportProgress)
{
bool continueProcessing;
List<IPrimitive> allPolys = new List<IPrimitive>();
List<Vector3> positions = new List<Vector3>();
List<IPrimitive> allPolys = new List<IPrimitive>();
List<Vector3> positions = new List<Vector3>();
foreach (Face face in mesh.Faces)
{
positions.Clear();
foreach (Vertex vertex in face.Vertices())
{
positions.Add(vertex.Position);
}
foreach (Face face in mesh.Faces)
{
positions.Clear();
foreach (Vertex vertex in face.Vertices())
{
positions.Add(vertex.Position);
}
// We should use the teselator for this if it is greater than 3.
Vector3 next = positions[1];
for (int positionIndex = 2; positionIndex < positions.Count; positionIndex++)
{
TriangleShape triangel = new TriangleShape(positions[0], next, positions[positionIndex], null);
allPolys.Add(triangel);
next = positions[positionIndex];
}
// We should use the teselator for this if it is greater than 3.
Vector3 next = positions[1];
for (int positionIndex = 2; positionIndex < positions.Count; positionIndex++)
{
TriangleShape triangel = new TriangleShape(positions[0], next, positions[positionIndex], null);
allPolys.Add(triangel);
next = positions[positionIndex];
}
if (reportProgress != null)
{
if ((currentAction % 256) == 0 || needToUpdateProgressReport)
{
reportProgress(currentAction / (double)totalActionCount, "Creating Trace Polygons", out continueProcessing);
needToUpdateProgressReport = false;
}
currentAction++;
}
}
if (reportProgress != null)
{
if ((currentAction % 256) == 0 || needToUpdateProgressReport)
{
reportProgress(currentAction / (double)totalActionCount, "Creating Trace Polygons", out continueProcessing);
needToUpdateProgressReport = false;
}
currentAction++;
}
}
return allPolys;
}
}
}
return allPolys;
}
}
}

View file

@ -1,37 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using MatterHackers.Agg;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
using MatterHackers.Agg.Image;
using MatterHackers.PolygonMesh.Processors;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintLibrary;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.CustomWidgets;
using System;
using System.IO;
namespace MatterHackers.MatterControl
namespace MatterHackers.MatterControl
{
public class SaveAsWindow : SystemWindow
{
TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory ();
MHTextEditWidget textToAddWidget;
CheckBox addToLibraryOption;
private TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
private MHTextEditWidget textToAddWidget;
private CheckBox addToLibraryOption;
public delegate void SetPrintItemWrapperAndSave(SaveAsReturnInfo returnInfo);
SetPrintItemWrapperAndSave functionToCallOnSaveAs;
public delegate void SetPrintItemWrapperAndSave(SaveAsReturnInfo returnInfo);
public SaveAsWindow(SetPrintItemWrapperAndSave functionToCallOnSaveAs)
: base (480, 250)
private SetPrintItemWrapperAndSave functionToCallOnSaveAs;
public SaveAsWindow(SetPrintItemWrapperAndSave functionToCallOnSaveAs)
: base(480, 250)
{
Title = "MatterControl - Save As";
this.functionToCallOnSaveAs = functionToCallOnSaveAs;
this.functionToCallOnSaveAs = functionToCallOnSaveAs;
FlowLayoutWidget topToBottom = new FlowLayoutWidget(FlowDirection.TopToBottom);
topToBottom.AnchorAll();
@ -44,17 +38,17 @@ namespace MatterHackers.MatterControl
headerRow.Padding = new BorderDouble(0, 3, 0, 3);
BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
//Creates Text and adds into header
//Creates Text and adds into header
{
string saveAsLabel = "Save New Design to Queue:";
TextWidget elementHeader = new TextWidget (saveAsLabel, pointSize: 14);
TextWidget elementHeader = new TextWidget(saveAsLabel, pointSize: 14);
elementHeader.TextColor = ActiveTheme.Instance.PrimaryTextColor;
elementHeader.HAnchor = HAnchor.ParentLeftRight;
elementHeader.VAnchor = Agg.UI.VAnchor.ParentBottom;
headerRow.AddChild (elementHeader);
topToBottom.AddChild (headerRow);
this.AddChild (topToBottom);
headerRow.AddChild(elementHeader);
topToBottom.AddChild(headerRow);
this.AddChild(topToBottom);
}
//Creates container in the middle of window
@ -69,13 +63,13 @@ namespace MatterHackers.MatterControl
string fileNameLabel = "Design Name";
TextWidget textBoxHeader = new TextWidget(fileNameLabel, pointSize: 12);
textBoxHeader.TextColor = ActiveTheme.Instance.PrimaryTextColor;
textBoxHeader.Margin = new BorderDouble (5);
textBoxHeader.Margin = new BorderDouble(5);
textBoxHeader.HAnchor = HAnchor.ParentLeft;
string fileNameLabelFull = "Enter the name of your design.";
TextWidget textBoxHeaderFull = new TextWidget(fileNameLabelFull, pointSize: 9);
textBoxHeaderFull.TextColor = ActiveTheme.Instance.PrimaryTextColor;
textBoxHeaderFull.Margin = new BorderDouble (5);
textBoxHeaderFull.Margin = new BorderDouble(5);
textBoxHeaderFull.HAnchor = HAnchor.ParentLeftRight;
//Adds text box and check box to the above container
@ -83,96 +77,95 @@ namespace MatterHackers.MatterControl
textToAddWidget.HAnchor = HAnchor.ParentLeftRight;
textToAddWidget.Margin = new BorderDouble(5);
addToLibraryOption = new CheckBox("Also save to Library", ActiveTheme.Instance.PrimaryTextColor);
addToLibraryOption.Margin = new BorderDouble (5);
addToLibraryOption = new CheckBox("Also save to Library", ActiveTheme.Instance.PrimaryTextColor);
addToLibraryOption.Margin = new BorderDouble(5);
addToLibraryOption.HAnchor = HAnchor.ParentLeftRight;
middleRowContainer.AddChild(textBoxHeader);
middleRowContainer.AddChild (textBoxHeaderFull);
middleRowContainer.AddChild(textBoxHeaderFull);
middleRowContainer.AddChild(textToAddWidget);
middleRowContainer.AddChild(new HorizontalSpacer());
middleRowContainer.AddChild(addToLibraryOption);
topToBottom.AddChild(middleRowContainer);
//Creates button container on the bottom of window
//Creates button container on the bottom of window
FlowLayoutWidget buttonRow = new FlowLayoutWidget(FlowDirection.LeftToRight);
{
BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
buttonRow.HAnchor = HAnchor.ParentLeftRight;
buttonRow.Padding = new BorderDouble(0,3);
buttonRow.Padding = new BorderDouble(0, 3);
}
Button saveAsButton = textImageButtonFactory.Generate("Save As".Localize(), centerText: true);
saveAsButton.Visible = true;
saveAsButton.Cursor = Cursors.Hand;
buttonRow.AddChild(saveAsButton);
buttonRow.AddChild(saveAsButton);
saveAsButton.Click += new EventHandler(saveAsButton_Click);
textToAddWidget.ActualTextEditWidget.EnterPressed += new KeyEventHandler(ActualTextEditWidget_EnterPressed);
saveAsButton.Click += new EventHandler(saveAsButton_Click);
textToAddWidget.ActualTextEditWidget.EnterPressed += new KeyEventHandler(ActualTextEditWidget_EnterPressed);
//Adds SaveAs and Close Button to button container
buttonRow.AddChild(new HorizontalSpacer());
buttonRow.AddChild(new HorizontalSpacer());
Button cancelButton = textImageButtonFactory.Generate ("Cancel", centerText: true);
Button cancelButton = textImageButtonFactory.Generate("Cancel", centerText: true);
cancelButton.Visible = true;
cancelButton.Cursor = Cursors.Hand;
buttonRow.AddChild(cancelButton);
cancelButton.Click += (sender, e) =>
{
CloseOnIdle();
};
buttonRow.AddChild(cancelButton);
cancelButton.Click += (sender, e) =>
{
CloseOnIdle();
};
topToBottom.AddChild(buttonRow);
ShowAsSystemWindow ();
ShowAsSystemWindow();
}
void ActualTextEditWidget_EnterPressed(object sender, KeyEventArgs keyEvent)
{
SubmitForm();
}
private void ActualTextEditWidget_EnterPressed(object sender, KeyEventArgs keyEvent)
{
SubmitForm();
}
void saveAsButton_Click(object sender, EventArgs mouseEvent)
{
SubmitForm();
}
private void saveAsButton_Click(object sender, EventArgs mouseEvent)
{
SubmitForm();
}
public class SaveAsReturnInfo
{
public string fileNameAndPath;
public bool placeInLibrary;
public string newName;
public PrintItemWrapper printItemWrapper;
public class SaveAsReturnInfo
{
public string fileNameAndPath;
public bool placeInLibrary;
public string newName;
public PrintItemWrapper printItemWrapper;
public SaveAsReturnInfo(string newName, string fileNameAndPath, bool placeInLibrary)
{
this.newName = newName;
this.fileNameAndPath = fileNameAndPath;
this.placeInLibrary = placeInLibrary;
public SaveAsReturnInfo(string newName, string fileNameAndPath, bool placeInLibrary)
{
this.newName = newName;
this.fileNameAndPath = fileNameAndPath;
this.placeInLibrary = placeInLibrary;
PrintItem printItem = new PrintItem();
printItem.Name = newName;
printItem.FileLocation = Path.GetFullPath(fileNameAndPath);
printItem.PrintItemCollectionID = LibraryData.Instance.LibraryCollection.Id;
printItem.Commit();
PrintItem printItem = new PrintItem();
printItem.Name = newName;
printItem.FileLocation = Path.GetFullPath(fileNameAndPath);
printItem.PrintItemCollectionID = LibraryData.Instance.LibraryCollection.Id;
printItem.Commit();
printItemWrapper = new PrintItemWrapper(printItem);
}
}
printItemWrapper = new PrintItemWrapper(printItem);
}
}
private void SubmitForm()
{
string newName = textToAddWidget.ActualTextEditWidget.Text;
if (newName != "")
{
string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".amf");
string fileNameAndPath = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, fileName);
private void SubmitForm()
{
string newName = textToAddWidget.ActualTextEditWidget.Text;
if (newName != "")
{
string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".amf");
string fileNameAndPath = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, fileName);
SaveAsReturnInfo returnInfo = new SaveAsReturnInfo(newName, fileNameAndPath, addToLibraryOption.Checked);
functionToCallOnSaveAs(returnInfo);
CloseOnIdle();
}
}
SaveAsReturnInfo returnInfo = new SaveAsReturnInfo(newName, fileNameAndPath, addToLibraryOption.Checked);
functionToCallOnSaveAs(returnInfo);
CloseOnIdle();
}
}
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,7 +23,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
@ -37,128 +37,127 @@ using System;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class HeightValueDisplay : GuiWidget
{
View3DWidget view3DWidget;
TextWidget numberDisplay;
public class HeightValueDisplay : GuiWidget
{
private View3DWidget view3DWidget;
private TextWidget numberDisplay;
static readonly int HorizontalLineLength = 30;
private static readonly int HorizontalLineLength = 30;
public HeightValueDisplay(View3DWidget view3DWidget)
{
BackgroundColor = new RGBA_Bytes(RGBA_Bytes.White, 150);
this.view3DWidget = view3DWidget;
view3DWidget.meshViewerWidget.AddChild(this);
numberDisplay = new TextWidget("00.00", pointSize:8);
numberDisplay.Margin = new BorderDouble(3, 2);
numberDisplay.AutoExpandBoundsToText = true;
AddChild(numberDisplay);
VAnchor = VAnchor.FitToChildren;
HAnchor = HAnchor.FitToChildren;
public HeightValueDisplay(View3DWidget view3DWidget)
{
BackgroundColor = new RGBA_Bytes(RGBA_Bytes.White, 150);
this.view3DWidget = view3DWidget;
view3DWidget.meshViewerWidget.AddChild(this);
numberDisplay = new TextWidget("00.00", pointSize: 8);
numberDisplay.Margin = new BorderDouble(3, 2);
numberDisplay.AutoExpandBoundsToText = true;
AddChild(numberDisplay);
VAnchor = VAnchor.FitToChildren;
HAnchor = HAnchor.FitToChildren;
MeshViewerToDrawWith.TrackballTumbleWidget.DrawGlContent += TrackballTumbleWidget_DrawGlContent;
MeshViewerToDrawWith.DrawAfter += new DrawEventHandler(MeshViewerToDrawWith_Draw);
}
MeshViewerToDrawWith.TrackballTumbleWidget.DrawGlContent += TrackballTumbleWidget_DrawGlContent;
MeshViewerToDrawWith.DrawAfter += new DrawEventHandler(MeshViewerToDrawWith_Draw);
}
MeshViewerWidget MeshViewerToDrawWith { get { return view3DWidget.meshViewerWidget; } }
private MeshViewerWidget MeshViewerToDrawWith { get { return view3DWidget.meshViewerWidget; } }
public void SetPosition()
{
if (MeshViewerToDrawWith.HaveSelection)
{
// draw the hight from the bottom to the bed
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
public void SetPosition()
{
if (MeshViewerToDrawWith.HaveSelection)
{
// draw the hight from the bottom to the bed
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
Vector2 screenPosition = new Vector2(-100, 0);
if (view3DWidget.DisplayAllValueData)
{
screenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(new Vector3(selectedBounds.maxXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z));
numberDisplay.Text = "{0:0.00}".FormatWith(selectedBounds.minXYZ.z);
}
else
{
Vector3[] bottomPoints = new Vector3[4];
bottomPoints[0] = new Vector3(selectedBounds.minXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[1] = new Vector3(selectedBounds.minXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[2] = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[3] = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
for (int i = 0; i < 4; i++)
{
Vector2 testScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomPoints[i]);
if (testScreenPosition.x > screenPosition.x)
{
startLineSelectionPos = testScreenPosition;
startLineGroundPos = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomPoints[i] + new Vector3(0, 0, -bottomPoints[i].z));
screenPosition = testScreenPosition + new Vector2(HorizontalLineLength, 0);
}
}
numberDisplay.Text = "{0:0.00mm}".FormatWith(selectedBounds.minXYZ.z);
}
Vector2 screenPosition = new Vector2(-100, 0);
if (view3DWidget.DisplayAllValueData)
{
screenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(new Vector3(selectedBounds.maxXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z));
numberDisplay.Text = "{0:0.00}".FormatWith(selectedBounds.minXYZ.z);
}
else
{
Vector3[] bottomPoints = new Vector3[4];
bottomPoints[0] = new Vector3(selectedBounds.minXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[1] = new Vector3(selectedBounds.minXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[2] = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.minXYZ.y, selectedBounds.minXYZ.z);
bottomPoints[3] = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
OriginRelativeParent = screenPosition;
for (int i = 0; i < 4; i++)
{
Vector2 testScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomPoints[i]);
if (testScreenPosition.x > screenPosition.x)
{
startLineSelectionPos = testScreenPosition;
startLineGroundPos = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomPoints[i] + new Vector3(0, 0, -bottomPoints[i].z));
screenPosition = testScreenPosition + new Vector2(HorizontalLineLength, 0);
}
}
numberDisplay.Text = "{0:0.00mm}".FormatWith(selectedBounds.minXYZ.z);
}
}
}
OriginRelativeParent = screenPosition;
}
}
Vector2 startLineGroundPos;
Vector2 startLineSelectionPos;
private Vector2 startLineGroundPos;
private Vector2 startLineSelectionPos;
void MeshViewerToDrawWith_Draw(GuiWidget drawingWidget, DrawEventArgs drawEvent)
{
if (Visible)
{
if (drawEvent != null)
{
// draw the line that is on the ground
double yGround = (int)(startLineGroundPos.y + .5) + .5;
drawEvent.graphics2D.Line(startLineGroundPos.x, yGround, startLineGroundPos.x + HorizontalLineLength - 5, yGround, RGBA_Bytes.Black);
// and the line that is at the base of the selection
double ySelection = (int)(startLineSelectionPos.y + .5) + .5;
drawEvent.graphics2D.Line(startLineSelectionPos.x, ySelection, startLineSelectionPos.x + HorizontalLineLength - 5, ySelection, RGBA_Bytes.Black);
private void MeshViewerToDrawWith_Draw(GuiWidget drawingWidget, DrawEventArgs drawEvent)
{
if (Visible)
{
if (drawEvent != null)
{
// draw the line that is on the ground
double yGround = (int)(startLineGroundPos.y + .5) + .5;
drawEvent.graphics2D.Line(startLineGroundPos.x, yGround, startLineGroundPos.x + HorizontalLineLength - 5, yGround, RGBA_Bytes.Black);
// and the line that is at the base of the selection
double ySelection = (int)(startLineSelectionPos.y + .5) + .5;
drawEvent.graphics2D.Line(startLineSelectionPos.x, ySelection, startLineSelectionPos.x + HorizontalLineLength - 5, ySelection, RGBA_Bytes.Black);
// draw the verticle line that shows the measurment
Vector2 pointerBottom = new Vector2(startLineGroundPos.x + HorizontalLineLength / 2, yGround);
Vector2 pointerTop = new Vector2(startLineSelectionPos.x + HorizontalLineLength / 2, ySelection);
drawEvent.graphics2D.Line(pointerBottom, pointerTop, RGBA_Bytes.Black);
// draw the verticle line that shows the measurment
Vector2 pointerBottom = new Vector2(startLineGroundPos.x + HorizontalLineLength / 2, yGround);
Vector2 pointerTop = new Vector2(startLineSelectionPos.x + HorizontalLineLength / 2, ySelection);
drawEvent.graphics2D.Line(pointerBottom, pointerTop, RGBA_Bytes.Black);
Vector2 direction = pointerTop - pointerBottom;
if (direction.LengthSquared > 0)
{
PathStorage arrow = new PathStorage();
arrow.MoveTo(-3, -5);
arrow.LineTo(0, 0);
arrow.LineTo(3, -5);
double rotation = Math.Atan2(direction.y, direction.x);
IVertexSource correctRotation = new VertexSourceApplyTransform(arrow, Affine.NewRotation(rotation - MathHelper.Tau / 4));
IVertexSource inPosition = new VertexSourceApplyTransform(correctRotation, Affine.NewTranslation(pointerTop));
drawEvent.graphics2D.Render(inPosition, RGBA_Bytes.Black);
}
}
}
}
Vector2 direction = pointerTop - pointerBottom;
if (direction.LengthSquared > 0)
{
PathStorage arrow = new PathStorage();
arrow.MoveTo(-3, -5);
arrow.LineTo(0, 0);
arrow.LineTo(3, -5);
double rotation = Math.Atan2(direction.y, direction.x);
IVertexSource correctRotation = new VertexSourceApplyTransform(arrow, Affine.NewRotation(rotation - MathHelper.Tau / 4));
IVertexSource inPosition = new VertexSourceApplyTransform(correctRotation, Affine.NewTranslation(pointerTop));
drawEvent.graphics2D.Render(inPosition, RGBA_Bytes.Black);
}
}
}
}
void TrackballTumbleWidget_DrawGlContent(object sender, EventArgs e)
{
if (Visible)
{
if (view3DWidget.DisplayAllValueData)
{
}
else
{
}
}
}
private void TrackballTumbleWidget_DrawGlContent(object sender, EventArgs e)
{
if (Visible)
{
if (view3DWidget.DisplayAllValueData)
{
}
else
{
}
}
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
base.OnMouseDown(mouseEvent);
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
base.OnMouseDown(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
base.OnMouseMove(mouseEvent);
}
}
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
base.OnMouseMove(mouseEvent);
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,7 +23,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
@ -41,23 +41,23 @@ using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class UpArrow3D : InteractionVolume
{
Mesh upArrow;
double zHitHeight;
Vector3 lastMoveDelta;
PlaneShape hitPlane;
View3DWidget view3DWidget;
public class UpArrow3D : InteractionVolume
{
private Mesh upArrow;
private double zHitHeight;
private Vector3 lastMoveDelta;
private PlaneShape hitPlane;
private View3DWidget view3DWidget;
public UpArrow3D(View3DWidget view3DWidget)
: base(null, view3DWidget.meshViewerWidget)
{
this.view3DWidget = view3DWidget;
string arrowFile = Path.Combine("Icons", "3D Icons", "up_pointer.stl");
if (StaticData.Instance.FileExists(arrowFile))
{
using(Stream staticDataStream = StaticData.Instance.OpenSteam(arrowFile))
{
public UpArrow3D(View3DWidget view3DWidget)
: base(null, view3DWidget.meshViewerWidget)
{
this.view3DWidget = view3DWidget;
string arrowFile = Path.Combine("Icons", "3D Icons", "up_pointer.stl");
if (StaticData.Instance.FileExists(arrowFile))
{
using (Stream staticDataStream = StaticData.Instance.OpenSteam(arrowFile))
{
using (MemoryStream arrowStream = new MemoryStream())
{
staticDataStream.CopyTo(arrowStream, 1 << 16);
@ -69,106 +69,105 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
//CollisionVolume = new CylinderShape(arrowBounds.XSize / 2, arrowBounds.ZSize, new SolidMaterial(RGBA_Floats.Red, .5, 0, .4));
//CollisionVolume = new CylinderShape(arrowBounds.XSize / 2 * 4, arrowBounds.ZSize * 4, new SolidMaterial(RGBA_Floats.Red, .5, 0, .4));
}
}
}
}
}
}
}
public override void OnMouseDown(MouseEvent3DArgs mouseEvent3D)
{
zHitHeight = mouseEvent3D.info.hitPosition.z;
lastMoveDelta= new Vector3();
double distanceToHit = Vector3.Dot(mouseEvent3D.info.hitPosition, mouseEvent3D.MouseRay.directionNormal);
hitPlane = new PlaneShape(mouseEvent3D.MouseRay.directionNormal, distanceToHit, null);
public override void OnMouseDown(MouseEvent3DArgs mouseEvent3D)
{
zHitHeight = mouseEvent3D.info.hitPosition.z;
lastMoveDelta = new Vector3();
double distanceToHit = Vector3.Dot(mouseEvent3D.info.hitPosition, mouseEvent3D.MouseRay.directionNormal);
hitPlane = new PlaneShape(mouseEvent3D.MouseRay.directionNormal, distanceToHit, null);
IntersectInfo info = hitPlane.GetClosestIntersection(mouseEvent3D.MouseRay);
zHitHeight = info.hitPosition.z;
IntersectInfo info = hitPlane.GetClosestIntersection(mouseEvent3D.MouseRay);
zHitHeight = info.hitPosition.z;
base.OnMouseDown(mouseEvent3D);
}
base.OnMouseDown(mouseEvent3D);
}
public override void OnMouseMove(MouseEvent3DArgs mouseEvent3D)
{
IntersectInfo info = hitPlane.GetClosestIntersection(mouseEvent3D.MouseRay);
public override void OnMouseMove(MouseEvent3DArgs mouseEvent3D)
{
IntersectInfo info = hitPlane.GetClosestIntersection(mouseEvent3D.MouseRay);
if (info != null && MeshViewerToDrawWith.SelectedMeshGroupIndex != -1)
{
Vector3 delta = new Vector3(0, 0, info.hitPosition.z - zHitHeight);
if (info != null && MeshViewerToDrawWith.SelectedMeshGroupIndex != -1)
{
Vector3 delta = new Vector3(0, 0, info.hitPosition.z - zHitHeight);
// move it back to where it started
ScaleRotateTranslate translated = MeshViewerToDrawWith.SelectedMeshGroupTransform;
translated.translation *= Matrix4X4.CreateTranslation(new Vector3(-lastMoveDelta));;
MeshViewerToDrawWith.SelectedMeshGroupTransform = translated;
// move it back to where it started
ScaleRotateTranslate translated = MeshViewerToDrawWith.SelectedMeshGroupTransform;
translated.translation *= Matrix4X4.CreateTranslation(new Vector3(-lastMoveDelta)); ;
MeshViewerToDrawWith.SelectedMeshGroupTransform = translated;
// now snap this position to the grid
{
double snapGridDistance = MeshViewerToDrawWith.SnapGridDistance;
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
double bottom = selectedBounds.minXYZ.z + delta.z;
// now snap this position to the grid
{
double snapGridDistance = MeshViewerToDrawWith.SnapGridDistance;
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
double bottom = selectedBounds.minXYZ.z + delta.z;
double snappedBottom = ((int)((bottom / snapGridDistance) + .5)) * snapGridDistance;
delta.z = snappedBottom - selectedBounds.minXYZ.z;
}
double snappedBottom = ((int)((bottom / snapGridDistance) + .5)) * snapGridDistance;
delta.z = snappedBottom - selectedBounds.minXYZ.z;
}
// and move it from there to where we are now
translated.translation *= Matrix4X4.CreateTranslation(new Vector3(delta));
MeshViewerToDrawWith.SelectedMeshGroupTransform = translated;
// and move it from there to where we are now
translated.translation *= Matrix4X4.CreateTranslation(new Vector3(delta));
MeshViewerToDrawWith.SelectedMeshGroupTransform = translated;
lastMoveDelta = delta;
lastMoveDelta = delta;
view3DWidget.PartHasBeenChanged();
Invalidate();
}
view3DWidget.PartHasBeenChanged();
Invalidate();
}
base.OnMouseMove(mouseEvent3D);
}
base.OnMouseMove(mouseEvent3D);
}
public void SetPosition()
{
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
Vector3 boundsCenter = selectedBounds.Center;
Vector3 centerTop = new Vector3(boundsCenter.x, boundsCenter.y, selectedBounds.maxXYZ.z);
public void SetPosition()
{
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
Vector3 boundsCenter = selectedBounds.Center;
Vector3 centerTop = new Vector3(boundsCenter.x, boundsCenter.y, selectedBounds.maxXYZ.z);
Vector2 centerTopScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(centerTop);
Vector2 centerTopScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(centerTop);
double distBetweenPixelsWorldSpace = MeshViewerToDrawWith.TrackballTumbleWidget.GetWorldUnitsPerScreenPixelAtPosition(centerTop);
double distBetweenPixelsWorldSpace = MeshViewerToDrawWith.TrackballTumbleWidget.GetWorldUnitsPerScreenPixelAtPosition(centerTop);
Matrix4X4 arrowTransform = Matrix4X4.CreateTranslation(new Vector3(centerTop.x, centerTop.y, centerTop.z + 20 * distBetweenPixelsWorldSpace));
arrowTransform = Matrix4X4.CreateScale(distBetweenPixelsWorldSpace) * arrowTransform;
Matrix4X4 arrowTransform = Matrix4X4.CreateTranslation(new Vector3(centerTop.x, centerTop.y, centerTop.z + 20 * distBetweenPixelsWorldSpace));
arrowTransform = Matrix4X4.CreateScale(distBetweenPixelsWorldSpace) * arrowTransform;
TotalTransform = arrowTransform;
TotalTransform = arrowTransform;
if (MouseOver || MouseDownOnControl)
{
view3DWidget.heightDisplay.Visible = true;
}
else if (!view3DWidget.DisplayAllValueData)
{
view3DWidget.heightDisplay.Visible = false;
}
if (MouseOver || MouseDownOnControl)
{
view3DWidget.heightDisplay.Visible = true;
}
else if (!view3DWidget.DisplayAllValueData)
{
view3DWidget.heightDisplay.Visible = false;
}
}
}
public override void DrawGlContent(EventArgs e)
{
if (MeshViewerToDrawWith.SelectedMeshGroup != null)
{
if (MouseOver)
{
RenderMeshToGl.Render(upArrow, RGBA_Bytes.Red, TotalTransform, RenderTypes.Shaded);
public override void DrawGlContent(EventArgs e)
{
if (MeshViewerToDrawWith.SelectedMeshGroup != null)
{
if (MouseOver)
{
RenderMeshToGl.Render(upArrow, RGBA_Bytes.Red, TotalTransform, RenderTypes.Shaded);
// draw the hight from the bottom to the bed
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
// draw the hight from the bottom to the bed
AxisAlignedBoundingBox selectedBounds = MeshViewerToDrawWith.GetBoundsForSelection();
Vector3 bottomRight = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
Vector2 bottomRightScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomRight);
}
else
{
RenderMeshToGl.Render(upArrow, RGBA_Bytes.Black, TotalTransform, RenderTypes.Shaded);
}
}
Vector3 bottomRight = new Vector3(selectedBounds.maxXYZ.x, selectedBounds.maxXYZ.y, selectedBounds.minXYZ.z);
Vector2 bottomRightScreenPosition = MeshViewerToDrawWith.TrackballTumbleWidget.GetScreenPosition(bottomRight);
}
else
{
RenderMeshToGl.Render(upArrow, RGBA_Bytes.Black, TotalTransform, RenderTypes.Shaded);
}
}
base.DrawGlContent(e);
}
}
}
base.DrawGlContent(e);
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,145 +23,144 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
using MatterHackers.VectorMath;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.VectorMath;
using MatterHackers.PolygonMesh;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
void AlignToSelectedMeshGroup()
{
if (MeshGroups.Count > 0)
{
// set the progress lable text
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
string makingCopyLabel = LocalizedString.Get("Aligning");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
LockEditControls();
viewIsInEditModePreLock = true;
public partial class View3DWidget
{
private void AlignToSelectedMeshGroup()
{
if (MeshGroups.Count > 0)
{
// set the progress lable text
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
string makingCopyLabel = LocalizedString.Get("Aligning");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
LockEditControls();
viewIsInEditModePreLock = true;
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(alignSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(alignSelectedBackgroundWorker_DoWork);
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(alignSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(alignSelectedBackgroundWorker_DoWork);
void alignSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
// make sure our thread traslates numbmers correctly (always do this in a thread)
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
// save our data so we don't mess up the display while doing work
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
private void alignSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
// make sure our thread traslates numbmers correctly (always do this in a thread)
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
// try to move all the not selected meshes relative to the selected mesh
AxisAlignedBoundingBox selectedOriginalBounds = asynchMeshGroups[SelectedMeshGroupIndex].GetAxisAlignedBoundingBox();
Vector3 selectedOriginalCenter = selectedOriginalBounds.Center;
AxisAlignedBoundingBox selectedCurrentBounds = asynchMeshGroups[SelectedMeshGroupIndex].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[SelectedMeshGroupIndex].TotalTransform);
Vector3 selctedCurrentCenter = selectedCurrentBounds.Center;
for(int meshGroupToMoveIndex = 0; meshGroupToMoveIndex < asynchMeshGroups.Count; meshGroupToMoveIndex++)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != asynchMeshGroups[SelectedMeshGroupIndex])
{
AxisAlignedBoundingBox groupToMoveOriginalBounds = meshGroupToMove.GetAxisAlignedBoundingBox();
Vector3 groupToMoveOriginalCenter = groupToMoveOriginalBounds.Center;
AxisAlignedBoundingBox groupToMoveBounds = meshGroupToMove.GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[meshGroupToMoveIndex].TotalTransform);
Vector3 groupToMoveCenter = groupToMoveBounds.Center;
// save our data so we don't mess up the display while doing work
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
Vector3 originalCoordinatesDelta = groupToMoveOriginalCenter - selectedOriginalCenter;
Vector3 currentCoordinatesDelta = groupToMoveCenter - selctedCurrentCenter;
// try to move all the not selected meshes relative to the selected mesh
AxisAlignedBoundingBox selectedOriginalBounds = asynchMeshGroups[SelectedMeshGroupIndex].GetAxisAlignedBoundingBox();
Vector3 selectedOriginalCenter = selectedOriginalBounds.Center;
AxisAlignedBoundingBox selectedCurrentBounds = asynchMeshGroups[SelectedMeshGroupIndex].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[SelectedMeshGroupIndex].TotalTransform);
Vector3 selctedCurrentCenter = selectedCurrentBounds.Center;
for (int meshGroupToMoveIndex = 0; meshGroupToMoveIndex < asynchMeshGroups.Count; meshGroupToMoveIndex++)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != asynchMeshGroups[SelectedMeshGroupIndex])
{
AxisAlignedBoundingBox groupToMoveOriginalBounds = meshGroupToMove.GetAxisAlignedBoundingBox();
Vector3 groupToMoveOriginalCenter = groupToMoveOriginalBounds.Center;
AxisAlignedBoundingBox groupToMoveBounds = meshGroupToMove.GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[meshGroupToMoveIndex].TotalTransform);
Vector3 groupToMoveCenter = groupToMoveBounds.Center;
Vector3 deltaRequired = originalCoordinatesDelta - currentCoordinatesDelta;
Vector3 originalCoordinatesDelta = groupToMoveOriginalCenter - selectedOriginalCenter;
Vector3 currentCoordinatesDelta = groupToMoveCenter - selctedCurrentCenter;
if (deltaRequired.Length > .0001)
{
ScaleRotateTranslate translated = asynchMeshGroupTransforms[meshGroupToMoveIndex];
translated.translation *= Matrix4X4.CreateTranslation(deltaRequired);
asynchMeshGroupTransforms[meshGroupToMoveIndex] = translated;
PartHasBeenChanged();
}
}
}
Vector3 deltaRequired = originalCoordinatesDelta - currentCoordinatesDelta;
// now put all the meshes into just one group
MeshGroup meshGroupWeAreKeeping = asynchMeshGroups[SelectedMeshGroupIndex];
for (int meshGroupToMoveIndex = asynchMeshGroups.Count - 1; meshGroupToMoveIndex >= 0; meshGroupToMoveIndex--)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != meshGroupWeAreKeeping)
{
// move all the meshes into the new aligned mesh group
for(int moveIndex = 0; moveIndex < meshGroupToMove.Meshes.Count; moveIndex++)
{
Mesh mesh = meshGroupToMove.Meshes[moveIndex];
meshGroupWeAreKeeping.Meshes.Add(mesh);
}
if (deltaRequired.Length > .0001)
{
ScaleRotateTranslate translated = asynchMeshGroupTransforms[meshGroupToMoveIndex];
translated.translation *= Matrix4X4.CreateTranslation(deltaRequired);
asynchMeshGroupTransforms[meshGroupToMoveIndex] = translated;
PartHasBeenChanged();
}
}
}
asynchMeshGroups.RemoveAt(meshGroupToMoveIndex);
asynchMeshGroupTransforms.RemoveAt(meshGroupToMoveIndex);
}
}
// now put all the meshes into just one group
MeshGroup meshGroupWeAreKeeping = asynchMeshGroups[SelectedMeshGroupIndex];
for (int meshGroupToMoveIndex = asynchMeshGroups.Count - 1; meshGroupToMoveIndex >= 0; meshGroupToMoveIndex--)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != meshGroupWeAreKeeping)
{
// move all the meshes into the new aligned mesh group
for (int moveIndex = 0; moveIndex < meshGroupToMove.Meshes.Count; moveIndex++)
{
Mesh mesh = meshGroupToMove.Meshes[moveIndex];
meshGroupWeAreKeeping.Meshes.Add(mesh);
}
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
asynchMeshGroups.RemoveAt(meshGroupToMoveIndex);
asynchMeshGroupTransforms.RemoveAt(meshGroupToMoveIndex);
}
}
MeshGroup meshGroup = asynchMeshGroups[i];
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
MeshGroup meshGroup = asynchMeshGroups[i];
currentRatioDone += ratioPerMeshGroup;
}
}
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
void alignSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
currentRatioDone += ratioPerMeshGroup;
}
}
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
private void alignSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
UnlockEditControls();
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
Invalidate();
}
}
}
UnlockEditControls();
Invalidate();
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,141 +23,141 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
using MatterHackers.VectorMath;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
private void AutoArrangePartsInBackground()
{
if (MeshGroups.Count > 0)
{
string progressArrangeParts = LocalizedString.Get("Arranging Parts");
string progressArrangePartsFull = string.Format("{0}:", progressArrangeParts);
processingProgressControl.ProcessType = progressArrangePartsFull;
processingProgressControl.Visible = true;
processingProgressControl.PercentComplete = 0;
LockEditControls();
public partial class View3DWidget
{
private void AutoArrangePartsInBackground()
{
if (MeshGroups.Count > 0)
{
string progressArrangeParts = LocalizedString.Get("Arranging Parts");
string progressArrangePartsFull = string.Format("{0}:", progressArrangeParts);
processingProgressControl.ProcessType = progressArrangePartsFull;
processingProgressControl.Visible = true;
processingProgressControl.PercentComplete = 0;
LockEditControls();
BackgroundWorker arrangeMeshGroupsBackgroundWorker = new BackgroundWorker();
BackgroundWorker arrangeMeshGroupsBackgroundWorker = new BackgroundWorker();
arrangeMeshGroupsBackgroundWorker.DoWork += new DoWorkEventHandler(arrangeMeshGroupsBackgroundWorker_DoWork);
arrangeMeshGroupsBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(arrangeMeshGroupsBackgroundWorker_RunWorkerCompleted);
arrangeMeshGroupsBackgroundWorker.DoWork += new DoWorkEventHandler(arrangeMeshGroupsBackgroundWorker_DoWork);
arrangeMeshGroupsBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(arrangeMeshGroupsBackgroundWorker_RunWorkerCompleted);
arrangeMeshGroupsBackgroundWorker.RunWorkerAsync();
}
}
arrangeMeshGroupsBackgroundWorker.RunWorkerAsync();
}
}
void arrangeMeshGroupsBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DONT_COPY);
private void arrangeMeshGroupsBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DONT_COPY);
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
// move them all out of the way
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
ScaleRotateTranslate translate = asynchMeshGroupTransforms[i];
translate.translation *= Matrix4X4.CreateTranslation(1000, 1000, 0);
asynchMeshGroupTransforms[i] = translate;
}
// move them all out of the way
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
ScaleRotateTranslate translate = asynchMeshGroupTransforms[i];
translate.translation *= Matrix4X4.CreateTranslation(1000, 1000, 0);
asynchMeshGroupTransforms[i] = translate;
}
// sort them by size
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
AxisAlignedBoundingBox iAABB = asynchMeshGroups[i].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[i].TotalTransform);
for (int j = i + 1; j < asynchMeshGroups.Count; j++)
{
AxisAlignedBoundingBox jAABB = asynchMeshGroups[j].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[j].TotalTransform);
if (Math.Max(iAABB.XSize, iAABB.YSize) < Math.Max(jAABB.XSize, jAABB.YSize))
{
PlatingMeshGroupData tempData = asynchPlatingDatas[i];
asynchPlatingDatas[i] = asynchPlatingDatas[j];
asynchPlatingDatas[j] = tempData;
// sort them by size
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
AxisAlignedBoundingBox iAABB = asynchMeshGroups[i].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[i].TotalTransform);
for (int j = i + 1; j < asynchMeshGroups.Count; j++)
{
AxisAlignedBoundingBox jAABB = asynchMeshGroups[j].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[j].TotalTransform);
if (Math.Max(iAABB.XSize, iAABB.YSize) < Math.Max(jAABB.XSize, jAABB.YSize))
{
PlatingMeshGroupData tempData = asynchPlatingDatas[i];
asynchPlatingDatas[i] = asynchPlatingDatas[j];
asynchPlatingDatas[j] = tempData;
MeshGroup tempMeshGroup = asynchMeshGroups[i];
asynchMeshGroups[i] = asynchMeshGroups[j];
asynchMeshGroups[j] = tempMeshGroup;
MeshGroup tempMeshGroup = asynchMeshGroups[i];
asynchMeshGroups[i] = asynchMeshGroups[j];
asynchMeshGroups[j] = tempMeshGroup;
ScaleRotateTranslate iTransform = asynchMeshGroupTransforms[i];
ScaleRotateTranslate jTransform = asynchMeshGroupTransforms[j];
Matrix4X4 tempTransform = iTransform.translation;
iTransform.translation = jTransform.translation;
jTransform.translation = tempTransform;
ScaleRotateTranslate iTransform = asynchMeshGroupTransforms[i];
ScaleRotateTranslate jTransform = asynchMeshGroupTransforms[j];
Matrix4X4 tempTransform = iTransform.translation;
iTransform.translation = jTransform.translation;
jTransform.translation = tempTransform;
asynchMeshGroupTransforms[i] = jTransform;
asynchMeshGroupTransforms[j] = iTransform;
asynchMeshGroupTransforms[i] = jTransform;
asynchMeshGroupTransforms[j] = iTransform;
iAABB = jAABB;
}
}
}
iAABB = jAABB;
}
}
}
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
// put them onto the plate (try the center) starting with the biggest and moving down
for (int meshGroupIndex = 0; meshGroupIndex < asynchMeshGroups.Count; meshGroupIndex++)
{
MeshGroup meshGroup = asynchMeshGroups[meshGroupIndex];
Vector3 meshCenter = meshGroup.GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[meshGroupIndex].translation).Center;
ScaleRotateTranslate atZero = asynchMeshGroupTransforms[meshGroupIndex];
atZero.translation = Matrix4X4.Identity;
asynchMeshGroupTransforms[meshGroupIndex] = atZero;
PlatingHelper.MoveMeshGroupToOpenPosition(meshGroupIndex, asynchPlatingDatas, asynchMeshGroups, asynchMeshGroupTransforms);
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
// put them onto the plate (try the center) starting with the biggest and moving down
for (int meshGroupIndex = 0; meshGroupIndex < asynchMeshGroups.Count; meshGroupIndex++)
{
MeshGroup meshGroup = asynchMeshGroups[meshGroupIndex];
Vector3 meshCenter = meshGroup.GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[meshGroupIndex].translation).Center;
ScaleRotateTranslate atZero = asynchMeshGroupTransforms[meshGroupIndex];
atZero.translation = Matrix4X4.Identity;
asynchMeshGroupTransforms[meshGroupIndex] = atZero;
PlatingHelper.MoveMeshGroupToOpenPosition(meshGroupIndex, asynchPlatingDatas, asynchMeshGroups, asynchMeshGroupTransforms);
// and create the trace info so we can select it
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, meshGroupIndex, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
// and create the trace info so we can select it
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, meshGroupIndex, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
currentRatioDone += ratioPerMeshGroup;
currentRatioDone += ratioPerMeshGroup;
// and put it on the bed
PlatingHelper.PlaceMeshGroupOnBed(asynchMeshGroups, asynchMeshGroupTransforms, meshGroupIndex);
}
// and put it on the bed
PlatingHelper.PlaceMeshGroupOnBed(asynchMeshGroups, asynchMeshGroupTransforms, meshGroupIndex);
}
// and finally center whatever we have as a group
{
AxisAlignedBoundingBox bounds = asynchMeshGroups[0].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[0].TotalTransform);
for (int i = 1; i < asynchMeshGroups.Count; i++)
{
bounds = AxisAlignedBoundingBox.Union(bounds, asynchMeshGroups[i].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[i].TotalTransform));
}
// and finally center whatever we have as a group
{
AxisAlignedBoundingBox bounds = asynchMeshGroups[0].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[0].TotalTransform);
for (int i = 1; i < asynchMeshGroups.Count; i++)
{
bounds = AxisAlignedBoundingBox.Union(bounds, asynchMeshGroups[i].GetAxisAlignedBoundingBox(asynchMeshGroupTransforms[i].TotalTransform));
}
Vector3 boundsCenter = (bounds.maxXYZ + bounds.minXYZ) / 2;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
ScaleRotateTranslate translate = asynchMeshGroupTransforms[i];
translate.translation *= Matrix4X4.CreateTranslation(-boundsCenter + new Vector3(0, 0, bounds.ZSize / 2));
asynchMeshGroupTransforms[i] = translate;
}
}
}
Vector3 boundsCenter = (bounds.maxXYZ + bounds.minXYZ) / 2;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
ScaleRotateTranslate translate = asynchMeshGroupTransforms[i];
translate.translation *= Matrix4X4.CreateTranslation(-boundsCenter + new Vector3(0, 0, bounds.ZSize / 2));
asynchMeshGroupTransforms[i] = translate;
}
}
}
void arrangeMeshGroupsBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
UnlockEditControls();
PartHasBeenChanged();
private void arrangeMeshGroupsBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
UnlockEditControls();
PartHasBeenChanged();
PullMeshGroupDataFromAsynchLists();
}
}
}
PullMeshGroupDataFromAsynchLists();
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,82 +23,82 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Localizations;
using MatterHackers.PolygonMesh;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Localizations;
using MatterHackers.PolygonMesh;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
private void MakeCopyOfGroup()
{
if (MeshGroups.Count > 0
&& SelectedMeshGroupIndex != -1)
{
string makingCopyLabel = LocalizedString.Get("Making Copy");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
processingProgressControl.Visible = true;
processingProgressControl.PercentComplete = 0;
LockEditControls();
public partial class View3DWidget
{
private void MakeCopyOfGroup()
{
if (MeshGroups.Count > 0
&& SelectedMeshGroupIndex != -1)
{
string makingCopyLabel = LocalizedString.Get("Making Copy");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
processingProgressControl.Visible = true;
processingProgressControl.PercentComplete = 0;
LockEditControls();
BackgroundWorker copyGroupBackgroundWorker = null;
copyGroupBackgroundWorker = new BackgroundWorker();
BackgroundWorker copyGroupBackgroundWorker = null;
copyGroupBackgroundWorker = new BackgroundWorker();
copyGroupBackgroundWorker.DoWork += new DoWorkEventHandler(copyGroupBackgroundWorker_DoWork);
copyGroupBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(copyGroupBackgroundWorker_RunWorkerCompleted);
copyGroupBackgroundWorker.DoWork += new DoWorkEventHandler(copyGroupBackgroundWorker_DoWork);
copyGroupBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(copyGroupBackgroundWorker_RunWorkerCompleted);
copyGroupBackgroundWorker.RunWorkerAsync();
}
}
copyGroupBackgroundWorker.RunWorkerAsync();
}
}
void copyGroupBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
private void copyGroupBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
MeshGroup meshGroupToCopy = asynchMeshGroups[SelectedMeshGroupIndex];
MeshGroup copyMeshGroup = new MeshGroup();
double meshCount = meshGroupToCopy.Meshes.Count;
for (int i = 0; i < meshCount; i++)
{
Mesh mesh = asynchMeshGroups[SelectedMeshGroupIndex].Meshes[i];
copyMeshGroup.Meshes.Add(Mesh.Copy(mesh, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
}));
}
MeshGroup meshGroupToCopy = asynchMeshGroups[SelectedMeshGroupIndex];
MeshGroup copyMeshGroup = new MeshGroup();
double meshCount = meshGroupToCopy.Meshes.Count;
for (int i = 0; i < meshCount; i++)
{
Mesh mesh = asynchMeshGroups[SelectedMeshGroupIndex].Meshes[i];
copyMeshGroup.Meshes.Add(Mesh.Copy(mesh, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
}));
}
PlatingHelper.FindPositionForGroupAndAddToPlate(copyMeshGroup, SelectedMeshGroupTransform, asynchPlatingDatas, asynchMeshGroups, asynchMeshGroupTransforms);
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, asynchMeshGroups.Count - 1, null);
PlatingHelper.FindPositionForGroupAndAddToPlate(copyMeshGroup, SelectedMeshGroupTransform, asynchPlatingDatas, asynchMeshGroups, asynchMeshGroupTransforms);
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, asynchMeshGroups.Count - 1, null);
bool continueProcessing2;
BackgroundWorker_ProgressChanged(.95, "", out continueProcessing2);
}
bool continueProcessing2;
BackgroundWorker_ProgressChanged(.95, "", out continueProcessing2);
}
void copyGroupBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
private void copyGroupBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
UnlockEditControls();
PullMeshGroupDataFromAsynchLists();
PartHasBeenChanged();
UnlockEditControls();
PullMeshGroupDataFromAsynchLists();
PartHasBeenChanged();
// now set the selection to the new copy
MeshGroupExtraData[MeshGroups.Count - 1].currentScale = MeshGroupExtraData[SelectedMeshGroupIndex].currentScale;
SelectedMeshGroupIndex = MeshGroups.Count - 1;
}
}
}
// now set the selection to the new copy
MeshGroupExtraData[MeshGroups.Count - 1].currentScale = MeshGroupExtraData[SelectedMeshGroupIndex].currentScale;
SelectedMeshGroupIndex = MeshGroups.Count - 1;
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,114 +23,111 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.PolygonMesh;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Agg.UI;
using MatterHackers.Agg;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
void EnterEditAndCreateSelectionData()
{
if (enterEditButtonsContainer.Visible == true)
{
enterEditButtonsContainer.Visible = false;
}
public partial class View3DWidget
{
private void EnterEditAndCreateSelectionData()
{
if (enterEditButtonsContainer.Visible == true)
{
enterEditButtonsContainer.Visible = false;
}
autoArrangeButton.Visible = true;
autoArrangeButton.Visible = true;
if (MeshGroups.Count > 0)
{
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
if (MeshGroups.Count > 0)
{
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
BackgroundWorker createSelectionDataBackgroundWorker = null;
createSelectionDataBackgroundWorker = new BackgroundWorker();
BackgroundWorker createSelectionDataBackgroundWorker = null;
createSelectionDataBackgroundWorker = new BackgroundWorker();
createSelectionDataBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(createSelectionDataBackgroundWorker_RunWorkerCompleted);
createSelectionDataBackgroundWorker.DoWork += new DoWorkEventHandler(createSelectionDataBackgroundWorker_DoWork);
createSelectionDataBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(createSelectionDataBackgroundWorker_RunWorkerCompleted);
createSelectionDataBackgroundWorker.DoWork += new DoWorkEventHandler(createSelectionDataBackgroundWorker_DoWork);
createSelectionDataBackgroundWorker.RunWorkerAsync();
}
}
createSelectionDataBackgroundWorker.RunWorkerAsync();
}
}
void createSelectionDataBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string makingCopyLabel = LocalizedString.Get("Preparing Meshes");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
private void createSelectionDataBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string makingCopyLabel = LocalizedString.Get("Preparing Meshes");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DONT_COPY);
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DONT_COPY);
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
MeshGroup meshGroup = asynchMeshGroups[i];
MeshGroup meshGroup = asynchMeshGroups[i];
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
currentRatioDone += ratioPerMeshGroup;
}
currentRatioDone += ratioPerMeshGroup;
}
bool continueProcessing2;
BackgroundWorker_ProgressChanged(1, "Creating GL Data", out continueProcessing2);
meshViewerWidget.CreateGlDataForMeshes(asynchMeshGroups);
}
bool continueProcessing2;
BackgroundWorker_ProgressChanged(1, "Creating GL Data", out continueProcessing2);
meshViewerWidget.CreateGlDataForMeshes(asynchMeshGroups);
}
void createSelectionDataBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
private void createSelectionDataBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
SelectedMeshGroupIndex = 0;
buttonRightPanel.Visible = true;
UnlockEditControls();
viewControls3D.partSelectButton.ClickButton(null);
SelectedMeshGroupIndex = 0;
buttonRightPanel.Visible = true;
UnlockEditControls();
viewControls3D.partSelectButton.ClickButton(null);
Invalidate();
Invalidate();
if (DoAddFileAfterCreatingEditData)
{
FileDialog.OpenFileDialog(
if (DoAddFileAfterCreatingEditData)
{
FileDialog.OpenFileDialog(
new OpenFileDialogParams(ApplicationSettings.OpenDesignFileParams, multiSelect: true),
(openParams) =>
{
LoadAndAddPartsToPlate(openParams.FileNames);
});
DoAddFileAfterCreatingEditData = false;
}
else if (pendingPartsToLoad.Count > 0)
{
LoadAndAddPartsToPlate(pendingPartsToLoad.ToArray());
}
}
}
}
}
else if (pendingPartsToLoad.Count > 0)
{
LoadAndAddPartsToPlate(pendingPartsToLoad.ToArray());
}
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,129 +23,127 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
void GroupSelectedMeshs()
{
if (MeshGroups.Count > 0)
{
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
public partial class View3DWidget
{
private void GroupSelectedMeshs()
{
if (MeshGroups.Count > 0)
{
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(groupSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(groupSelectedBackgroundWorker_DoWork);
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(groupSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(groupSelectedBackgroundWorker_DoWork);
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
void groupSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string makingCopyLabel = LocalizedString.Get("Grouping");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
private void groupSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string makingCopyLabel = LocalizedString.Get("Grouping");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
asynchMeshGroups[i].Transform(asynchMeshGroupTransforms[i].TotalTransform);
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
asynchMeshGroups[i].Transform(asynchMeshGroupTransforms[i].TotalTransform);
bool continueProcessing;
BackgroundWorker_ProgressChanged((i+1) * .4 / asynchMeshGroups.Count, "", out continueProcessing);
}
bool continueProcessing;
BackgroundWorker_ProgressChanged((i + 1) * .4 / asynchMeshGroups.Count, "", out continueProcessing);
}
DoGroup(backgroundWorker);
}
DoGroup(backgroundWorker);
}
private void DoGroup(BackgroundWorker backgroundWorker)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
MeshGroup meshGroupWeAreKeeping = asynchMeshGroups[SelectedMeshGroupIndex];
for (int meshGroupToMoveIndex = asynchMeshGroups.Count - 1; meshGroupToMoveIndex >= 0; meshGroupToMoveIndex--)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != meshGroupWeAreKeeping)
{
for (int moveIndex = 0; moveIndex < meshGroupToMove.Meshes.Count; moveIndex++)
{
Mesh mesh = meshGroupToMove.Meshes[moveIndex];
meshGroupWeAreKeeping.Meshes.Add(mesh);
}
private void DoGroup(BackgroundWorker backgroundWorker)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
MeshGroup meshGroupWeAreKeeping = asynchMeshGroups[SelectedMeshGroupIndex];
for (int meshGroupToMoveIndex = asynchMeshGroups.Count - 1; meshGroupToMoveIndex >= 0; meshGroupToMoveIndex--)
{
MeshGroup meshGroupToMove = asynchMeshGroups[meshGroupToMoveIndex];
if (meshGroupToMove != meshGroupWeAreKeeping)
{
for (int moveIndex = 0; moveIndex < meshGroupToMove.Meshes.Count; moveIndex++)
{
Mesh mesh = meshGroupToMove.Meshes[moveIndex];
meshGroupWeAreKeeping.Meshes.Add(mesh);
}
asynchMeshGroups.RemoveAt(meshGroupToMoveIndex);
asynchMeshGroupTransforms.RemoveAt(meshGroupToMoveIndex);
}
else
{
asynchMeshGroupTransforms[meshGroupToMoveIndex] = ScaleRotateTranslate.Identity();
}
}
asynchMeshGroups.RemoveAt(meshGroupToMoveIndex);
asynchMeshGroupTransforms.RemoveAt(meshGroupToMoveIndex);
}
else
{
asynchMeshGroupTransforms[meshGroupToMoveIndex] = ScaleRotateTranslate.Identity();
}
}
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
asynchPlatingDatas.Clear();
double ratioPerMeshGroup = 1.0 / asynchMeshGroups.Count;
double currentRatioDone = 0;
for (int i = 0; i < asynchMeshGroups.Count; i++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
MeshGroup meshGroup = asynchMeshGroups[i];
MeshGroup meshGroup = asynchMeshGroups[i];
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
// create the selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, i, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
});
currentRatioDone += ratioPerMeshGroup;
}
}
currentRatioDone += ratioPerMeshGroup;
}
}
private void groupSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
void groupSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
UnlockEditControls();
UnlockEditControls();
PartHasBeenChanged();
PartHasBeenChanged();
Invalidate();
}
}
}
Invalidate();
}
}
}

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,121 +23,121 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using MatterHackers.Localizations;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public partial class View3DWidget
{
void UngroupSelectedMeshGroup()
{
if (MeshGroups.Count > 0)
{
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
public partial class View3DWidget
{
private void UngroupSelectedMeshGroup()
{
if (MeshGroups.Count > 0)
{
processingProgressControl.PercentComplete = 0;
processingProgressControl.Visible = true;
LockEditControls();
viewIsInEditModePreLock = true;
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
BackgroundWorker createDiscreteMeshesBackgroundWorker = null;
createDiscreteMeshesBackgroundWorker = new BackgroundWorker();
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ungroupSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(ungroupSelectedBackgroundWorker_DoWork);
createDiscreteMeshesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ungroupSelectedBackgroundWorker_RunWorkerCompleted);
createDiscreteMeshesBackgroundWorker.DoWork += new DoWorkEventHandler(ungroupSelectedBackgroundWorker_DoWork);
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
createDiscreteMeshesBackgroundWorker.RunWorkerAsync();
}
}
void ungroupSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
string makingCopyLabel = LocalizedString.Get("Ungrouping");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
private void ungroupSelectedBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (SelectedMeshGroupIndex == -1)
{
SelectedMeshGroupIndex = 0;
}
string makingCopyLabel = LocalizedString.Get("Ungrouping");
string makingCopyLabelFull = string.Format("{0}:", makingCopyLabel);
processingProgressControl.ProcessType = makingCopyLabelFull;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);
int indexBeingReplaced = SelectedMeshGroupIndex;
List<Mesh> discreetMeshes = new List<Mesh>();
asynchMeshGroups[indexBeingReplaced].Transform(asynchMeshGroupTransforms[indexBeingReplaced].TotalTransform);
// if there are multiple meshes than just make them separate groups
if (asynchMeshGroups[indexBeingReplaced].Meshes.Count > 1)
{
foreach(Mesh mesh in asynchMeshGroups[indexBeingReplaced].Meshes)
{
discreetMeshes.Add(mesh);
}
}
else // actually try and cut up the mesh into separate parts
{
discreetMeshes = CreateDiscreteMeshes.SplitConnectedIntoMeshes(asynchMeshGroups[indexBeingReplaced], (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1 * .5, processingState, out continueProcessing);
});
}
int indexBeingReplaced = SelectedMeshGroupIndex;
List<Mesh> discreetMeshes = new List<Mesh>();
asynchMeshGroups[indexBeingReplaced].Transform(asynchMeshGroupTransforms[indexBeingReplaced].TotalTransform);
// if there are multiple meshes than just make them separate groups
if (asynchMeshGroups[indexBeingReplaced].Meshes.Count > 1)
{
foreach (Mesh mesh in asynchMeshGroups[indexBeingReplaced].Meshes)
{
discreetMeshes.Add(mesh);
}
}
else // actually try and cut up the mesh into separate parts
{
discreetMeshes = CreateDiscreteMeshes.SplitConnectedIntoMeshes(asynchMeshGroups[indexBeingReplaced], (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(progress0To1 * .5, processingState, out continueProcessing);
});
}
asynchMeshGroups.RemoveAt(indexBeingReplaced);
asynchPlatingDatas.RemoveAt(indexBeingReplaced);
asynchMeshGroupTransforms.RemoveAt(indexBeingReplaced);
double ratioPerDiscreetMesh = 1.0 / discreetMeshes.Count;
double currentRatioDone = 0;
for (int discreetMeshIndex = 0; discreetMeshIndex < discreetMeshes.Count; discreetMeshIndex++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
asynchMeshGroups.Add(new MeshGroup(discreetMeshes[discreetMeshIndex]));
int addedMeshIndex = asynchMeshGroups.Count - 1;
MeshGroup addedMeshGroup = asynchMeshGroups[addedMeshIndex];
asynchMeshGroups.RemoveAt(indexBeingReplaced);
asynchPlatingDatas.RemoveAt(indexBeingReplaced);
asynchMeshGroupTransforms.RemoveAt(indexBeingReplaced);
double ratioPerDiscreetMesh = 1.0 / discreetMeshes.Count;
double currentRatioDone = 0;
for (int discreetMeshIndex = 0; discreetMeshIndex < discreetMeshes.Count; discreetMeshIndex++)
{
PlatingMeshGroupData newInfo = new PlatingMeshGroupData();
asynchPlatingDatas.Add(newInfo);
asynchMeshGroups.Add(new MeshGroup(discreetMeshes[discreetMeshIndex]));
int addedMeshIndex = asynchMeshGroups.Count - 1;
MeshGroup addedMeshGroup = asynchMeshGroups[addedMeshIndex];
ScaleRotateTranslate transform = ScaleRotateTranslate.Identity();
transform.SetCenteringForMeshGroup(addedMeshGroup);
asynchMeshGroupTransforms.Add(transform);
ScaleRotateTranslate transform = ScaleRotateTranslate.Identity();
transform.SetCenteringForMeshGroup(addedMeshGroup);
asynchMeshGroupTransforms.Add(transform);
//PlatingHelper.PlaceMeshGroupOnBed(asynchMeshGroups, asynchMeshGroupTransforms, addedMeshIndex, false);
//PlatingHelper.PlaceMeshGroupOnBed(asynchMeshGroups, asynchMeshGroupTransforms, addedMeshIndex, false);
// and create selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, addedMeshIndex, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(.5 + progress0To1 * .5 * currentRatioDone, processingState, out continueProcessing);
});
currentRatioDone += ratioPerDiscreetMesh;
}
}
// and create selection info
PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, addedMeshIndex, (double progress0To1, string processingState, out bool continueProcessing) =>
{
BackgroundWorker_ProgressChanged(.5 + progress0To1 * .5 * currentRatioDone, processingState, out continueProcessing);
});
currentRatioDone += ratioPerDiscreetMesh;
}
}
void ungroupSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
private void ungroupSelectedBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WidgetHasBeenClosed)
{
return;
}
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
// remove the original mesh and replace it with these new meshes
PullMeshGroupDataFromAsynchLists();
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
// our selection changed to the mesh we just added which is at the end
SelectedMeshGroupIndex = MeshGroups.Count - 1;
UnlockEditControls();
UnlockEditControls();
PartHasBeenChanged();
PartHasBeenChanged();
Invalidate();
}
}
}
Invalidate();
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,89 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl;
using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class ViewControlsBase : FlowLayoutWidget
{
protected int buttonHeight;
public ViewControlsBase()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
}
}
public class ViewControlsBase : FlowLayoutWidget
{
protected int buttonHeight;
public class ViewControls2D : ViewControlsBase
{
public RadioButton translateButton;
public RadioButton scaleButton;
public ViewControls2D()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
TextImageButtonFactory iconTextImageButtonFactory = new TextImageButtonFactory();
iconTextImageButtonFactory.AllowThemeToAdjustImage = false;
iconTextImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
public ViewControlsBase()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
}
}
BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);
iconTextImageButtonFactory.FixedHeight = buttonHeight;
iconTextImageButtonFactory.FixedWidth = buttonHeight;
public class ViewControls2D : ViewControlsBase
{
public RadioButton translateButton;
public RadioButton scaleButton;
string translateIconPath = Path.Combine("ViewTransformControls", "translate.png");
translateButton = iconTextImageButtonFactory.GenerateRadioButton("", translateIconPath);
translateButton.Margin = new BorderDouble(3);
AddChild(translateButton);
public ViewControls2D()
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
string scaleIconPath = Path.Combine("ViewTransformControls", "scale.png");
scaleButton = iconTextImageButtonFactory.GenerateRadioButton("", scaleIconPath);
scaleButton.Margin = new BorderDouble(3);
AddChild(scaleButton);
TextImageButtonFactory iconTextImageButtonFactory = new TextImageButtonFactory();
iconTextImageButtonFactory.AllowThemeToAdjustImage = false;
iconTextImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
Margin = new BorderDouble(5);
HAnchor |= Agg.UI.HAnchor.ParentLeft;
VAnchor = Agg.UI.VAnchor.ParentTop;
translateButton.Checked = true;
}
}
BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);
iconTextImageButtonFactory.FixedHeight = buttonHeight;
iconTextImageButtonFactory.FixedWidth = buttonHeight;
public class ViewControlsToggle : ViewControlsBase
string translateIconPath = Path.Combine("ViewTransformControls", "translate.png");
translateButton = iconTextImageButtonFactory.GenerateRadioButton("", translateIconPath);
translateButton.Margin = new BorderDouble(3);
AddChild(translateButton);
string scaleIconPath = Path.Combine("ViewTransformControls", "scale.png");
scaleButton = iconTextImageButtonFactory.GenerateRadioButton("", scaleIconPath);
scaleButton.Margin = new BorderDouble(3);
AddChild(scaleButton);
Margin = new BorderDouble(5);
HAnchor |= Agg.UI.HAnchor.ParentLeft;
VAnchor = Agg.UI.VAnchor.ParentTop;
translateButton.Checked = true;
}
}
public class ViewControlsToggle : ViewControlsBase
{
public RadioButton twoDimensionButton;
public RadioButton threeDimensionButton;
static bool userChangedTo3DThisRun = false;
private static bool userChangedTo3DThisRun = false;
public ViewControlsToggle()
{
TextImageButtonFactory iconTextImageButtonFactory = new TextImageButtonFactory();
iconTextImageButtonFactory.AllowThemeToAdjustImage = false;
iconTextImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
iconTextImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);
iconTextImageButtonFactory.FixedHeight = buttonHeight;
iconTextImageButtonFactory.FixedWidth = buttonHeight;
iconTextImageButtonFactory.FixedHeight = buttonHeight;
iconTextImageButtonFactory.FixedWidth = buttonHeight;
string translateIconPath = Path.Combine("ViewTransformControls", "2d.png");
twoDimensionButton = iconTextImageButtonFactory.GenerateRadioButton("", translateIconPath);
@ -96,14 +91,13 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
if (ActiveTheme.Instance.DisplayMode != ActiveTheme.ApplicationDisplayType.Touchscreen)
{
AddChild(threeDimensionButton);
if (UserSettings.Instance.get("LayerViewDefault") == "3D Layer"
&&
(UserSettings.Instance.Fields.StartCountDurringExit == UserSettings.Instance.Fields.StartCount - 1
|| userChangedTo3DThisRun)
)
&&
(UserSettings.Instance.Fields.StartCountDurringExit == UserSettings.Instance.Fields.StartCount - 1
|| userChangedTo3DThisRun)
)
{
threeDimensionButton.Checked = true;
}
@ -117,13 +111,13 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
twoDimensionButton.Checked = true;
}
threeDimensionButton.Click += (sender, e) =>
{
userChangedTo3DThisRun = true;
};
Margin = new BorderDouble(5,5,200,5);
threeDimensionButton.Click += (sender, e) =>
{
userChangedTo3DThisRun = true;
};
Margin = new BorderDouble(5, 5, 200, 5);
HAnchor |= Agg.UI.HAnchor.ParentRight;
VAnchor = Agg.UI.VAnchor.ParentTop;
}
}
}
}

View file

@ -1,138 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl;
using MatterHackers.MeshVisualizer;
using MatterHackers.VectorMath;
using System;
using System.IO;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class ViewControls3D : FlowLayoutWidget
{
GuiWidget partSelectSeparator;
MeshViewerWidget meshViewerWidget;
public class ViewControls3D : FlowLayoutWidget
{
private GuiWidget partSelectSeparator;
private MeshViewerWidget meshViewerWidget;
public RadioButton translateButton;
public RadioButton rotateButton;
public RadioButton scaleButton;
public RadioButton partSelectButton;
int buttonHeight;
public RadioButton translateButton;
public RadioButton rotateButton;
public RadioButton scaleButton;
public RadioButton partSelectButton;
private int buttonHeight;
public bool PartSelectVisible
{
get { return partSelectSeparator.Visible; }
set
{
partSelectSeparator.Visible = value;
partSelectButton.Visible = value;
}
}
public ViewControls3D(MeshViewerWidget meshViewerWidget)
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
this.meshViewerWidget = meshViewerWidget;
TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
public bool PartSelectVisible
{
get { return partSelectSeparator.Visible; }
set
{
partSelectSeparator.Visible = value;
partSelectButton.Visible = value;
}
}
textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
public ViewControls3D(MeshViewerWidget meshViewerWidget)
{
if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
{
buttonHeight = 40;
}
else
{
buttonHeight = 20;
}
BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);
textImageButtonFactory.FixedHeight = buttonHeight;
textImageButtonFactory.FixedWidth = buttonHeight;
textImageButtonFactory.AllowThemeToAdjustImage = false;
textImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
this.meshViewerWidget = meshViewerWidget;
TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
string rotateIconPath = Path.Combine("ViewTransformControls", "rotate.png");
rotateButton = textImageButtonFactory.GenerateRadioButton("", rotateIconPath);
rotateButton.Margin = new BorderDouble(3);
AddChild(rotateButton);
rotateButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Rotation;
};
textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
string translateIconPath = Path.Combine("ViewTransformControls", "translate.png");
translateButton = textImageButtonFactory.GenerateRadioButton("", translateIconPath);
translateButton.Margin = new BorderDouble(3);
AddChild(translateButton);
translateButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Translation;
};
BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);
textImageButtonFactory.FixedHeight = buttonHeight;
textImageButtonFactory.FixedWidth = buttonHeight;
textImageButtonFactory.AllowThemeToAdjustImage = false;
textImageButtonFactory.checkedBorderColor = RGBA_Bytes.White;
string scaleIconPath = Path.Combine("ViewTransformControls", "scale.png");
scaleButton = textImageButtonFactory.GenerateRadioButton("", scaleIconPath);
scaleButton.Margin = new BorderDouble(3);
AddChild(scaleButton);
scaleButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Scale;
};
string rotateIconPath = Path.Combine("ViewTransformControls", "rotate.png");
rotateButton = textImageButtonFactory.GenerateRadioButton("", rotateIconPath);
rotateButton.Margin = new BorderDouble(3);
AddChild(rotateButton);
rotateButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Rotation;
};
partSelectSeparator = new GuiWidget(2, 32);
partSelectSeparator.BackgroundColor = RGBA_Bytes.White;
partSelectSeparator.Margin = new BorderDouble(3);
AddChild(partSelectSeparator);
string translateIconPath = Path.Combine("ViewTransformControls", "translate.png");
translateButton = textImageButtonFactory.GenerateRadioButton("", translateIconPath);
translateButton.Margin = new BorderDouble(3);
AddChild(translateButton);
translateButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Translation;
};
string partSelectIconPath = Path.Combine("ViewTransformControls", "partSelect.png");
partSelectButton = textImageButtonFactory.GenerateRadioButton("", partSelectIconPath);
partSelectButton.Margin = new BorderDouble(3);
AddChild(partSelectButton);
partSelectButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.None;
};
string scaleIconPath = Path.Combine("ViewTransformControls", "scale.png");
scaleButton = textImageButtonFactory.GenerateRadioButton("", scaleIconPath);
scaleButton.Margin = new BorderDouble(3);
AddChild(scaleButton);
scaleButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Scale;
};
Margin = new BorderDouble(5);
HAnchor |= Agg.UI.HAnchor.ParentLeft;
VAnchor = Agg.UI.VAnchor.ParentTop;
rotateButton.Checked = true;
partSelectSeparator = new GuiWidget(2, 32);
partSelectSeparator.BackgroundColor = RGBA_Bytes.White;
partSelectSeparator.Margin = new BorderDouble(3);
AddChild(partSelectSeparator);
SetMeshViewerDisplayTheme();
partSelectButton.CheckedStateChanged += SetMeshViewerDisplayTheme;
string partSelectIconPath = Path.Combine("ViewTransformControls", "partSelect.png");
partSelectButton = textImageButtonFactory.GenerateRadioButton("", partSelectIconPath);
partSelectButton.Margin = new BorderDouble(3);
AddChild(partSelectButton);
partSelectButton.Click += (sender, e) =>
{
meshViewerWidget.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.None;
};
ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
}
Margin = new BorderDouble(5);
HAnchor |= Agg.UI.HAnchor.ParentLeft;
VAnchor = Agg.UI.VAnchor.ParentTop;
rotateButton.Checked = true;
event EventHandler unregisterEvents;
SetMeshViewerDisplayTheme();
partSelectButton.CheckedStateChanged += SetMeshViewerDisplayTheme;
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
}
public void ThemeChanged(object sender, EventArgs e)
{
SetMeshViewerDisplayTheme(null, null);
}
private event EventHandler unregisterEvents;
protected void SetMeshViewerDisplayTheme(object sender = null, EventArgs e = null)
{
meshViewerWidget.TrackballTumbleWidget.RotationHelperCircleColor = ActiveTheme.Instance.PrimaryBackgroundColor;
public override void OnClosed(EventArgs e)
{
if (unregisterEvents != null)
{
unregisterEvents(this, null);
}
base.OnClosed(e);
}
//meshViewerWidget.MaterialColor = RGBA_Bytes.White;
//meshViewerWidget.SelectedMaterialColor = ActiveTheme.Instance.PrimaryAccentColor;
meshViewerWidget.BuildVolumeColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryAccentColor.Red0To255, ActiveTheme.Instance.PrimaryAccentColor.Green0To255, ActiveTheme.Instance.PrimaryAccentColor.Blue0To255, 50);
}
}
}
public void ThemeChanged(object sender, EventArgs e)
{
SetMeshViewerDisplayTheme(null, null);
}
protected void SetMeshViewerDisplayTheme(object sender = null, EventArgs e = null)
{
meshViewerWidget.TrackballTumbleWidget.RotationHelperCircleColor = ActiveTheme.Instance.PrimaryBackgroundColor;
//meshViewerWidget.MaterialColor = RGBA_Bytes.White;
//meshViewerWidget.SelectedMaterialColor = ActiveTheme.Instance.PrimaryAccentColor;
meshViewerWidget.BuildVolumeColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryAccentColor.Red0To255, ActiveTheme.Instance.PrimaryAccentColor.Green0To255, ActiveTheme.Instance.PrimaryAccentColor.Blue0To255, 50);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -3,13 +3,13 @@ Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -23,27 +23,19 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
using MatterHackers.GCodeVisualizer;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.RasterizerScanline;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.GCodeVisualizer;
using System;
using System.ComponentModel;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
@ -53,18 +45,18 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
public ProgressChangedEventHandler LoadingProgressChanged;
public bool RenderGrid
public bool RenderGrid
{
get
{
string value = UserSettings.Instance.get("GcodeViewerRenderGrid");
if (value == null)
{
RenderGrid = true;
return true;
}
return (value == "True");
}
get
{
string value = UserSettings.Instance.get("GcodeViewerRenderGrid");
if (value == null)
{
RenderGrid = true;
return true;
}
return (value == "True");
}
set
{
UserSettings.Instance.set("GcodeViewerRenderGrid", value.ToString());
@ -74,6 +66,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
public double FeatureToStartOnRatio0To1 = 0;
public double FeatureToEndOnRatio0To1 = 1;
public enum ETransformState { Move, Scale };
public ETransformState TransformState { get; set; }
@ -83,68 +76,69 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
get { return (UserSettings.Instance.get("GcodeViewerRenderMoves") == "True"); }
set
{
UserSettings.Instance.set ("GcodeViewerRenderMoves", value.ToString ());
UserSettings.Instance.set("GcodeViewerRenderMoves", value.ToString());
Invalidate();
}
}
public bool RenderRetractions
{
get { return (UserSettings.Instance.get("GcodeViewerRenderRetractions") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerRenderRetractions", value.ToString());
Invalidate();
}
}
public bool RenderRetractions
{
get { return (UserSettings.Instance.get("GcodeViewerRenderRetractions") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerRenderRetractions", value.ToString());
Invalidate();
}
}
public bool RenderSpeeds
{
get { return (UserSettings.Instance.get("GcodeViewerRenderSpeeds") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerRenderSpeeds", value.ToString());
Invalidate();
}
}
public bool RenderSpeeds
{
get { return (UserSettings.Instance.get("GcodeViewerRenderSpeeds") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerRenderSpeeds", value.ToString());
Invalidate();
}
}
public bool SimulateExtrusion
{
get { return (UserSettings.Instance.get("GcodeViewerSimulateExtrusion") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerSimulateExtrusion", value.ToString());
Invalidate();
}
}
public bool SimulateExtrusion
{
get { return (UserSettings.Instance.get("GcodeViewerSimulateExtrusion") == "True"); }
set
{
UserSettings.Instance.set("GcodeViewerSimulateExtrusion", value.ToString());
Invalidate();
}
}
public bool HideExtruderOffsets
{
get
{
string value = UserSettings.Instance.get("GcodeViewerHideExtruderOffsets");
if (value == null)
{
return true;
}
return (value == "True");
}
set
{
UserSettings.Instance.set("GcodeViewerHideExtruderOffsets", value.ToString());
Invalidate();
}
}
public bool HideExtruderOffsets
{
get
{
string value = UserSettings.Instance.get("GcodeViewerHideExtruderOffsets");
if (value == null)
{
return true;
}
return (value == "True");
}
set
{
UserSettings.Instance.set("GcodeViewerHideExtruderOffsets", value.ToString());
Invalidate();
}
}
BackgroundWorker backgroundWorker = null;
Vector2 lastMousePosition = new Vector2(0, 0);
Vector2 mouseDownPosition = new Vector2(0, 0);
private BackgroundWorker backgroundWorker = null;
private Vector2 lastMousePosition = new Vector2(0, 0);
private Vector2 mouseDownPosition = new Vector2(0, 0);
double layerScale = 1;
int activeLayerIndex;
Vector2 gridSizeMm;
Vector2 gridCenterMm;
Affine ScallingTransform
private double layerScale = 1;
private int activeLayerIndex;
private Vector2 gridSizeMm;
private Vector2 gridCenterMm;
private Affine ScallingTransform
{
get
{
@ -159,7 +153,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
Affine transform = Affine.NewIdentity();
transform *= Affine.NewTranslation(unscaledRenderOffset);
// scale to view
// scale to view
transform *= ScallingTransform;
transform *= Affine.NewTranslation(Width / 2, Height / 2);
@ -167,7 +161,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
}
}
Vector2 unscaledRenderOffset = new Vector2(0, 0);
private Vector2 unscaledRenderOffset = new Vector2(0, 0);
public string FileNameAndPath;
public GCodeFile loadedGCode;
@ -241,7 +235,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
}
}
void SetInitalLayer()
private void SetInitalLayer()
{
activeLayerIndex = 0;
if (loadedGCode.LineCount > 0)
@ -268,7 +262,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
{
if (firstExtrusionIndex < loadedGCode.GetInstructionIndexAtLayer(layerIndex))
{
activeLayerIndex = Math.Max(0, layerIndex-1);
activeLayerIndex = Math.Max(0, layerIndex - 1);
break;
}
}
@ -276,7 +270,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
}
}
void initialLoading_ProgressChanged(object sender, ProgressChangedEventArgs e)
private void initialLoading_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (LoadingProgressChanged != null)
{
@ -284,26 +278,26 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
}
}
void initialLoading_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SetGCodeAfterLoad((GCodeFile)e.Result);
private void initialLoading_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SetGCodeAfterLoad((GCodeFile)e.Result);
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(postLoadInitialization_ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(postLoadInitialization_RunWorkerCompleted);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(postLoadInitialization_ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(postLoadInitialization_RunWorkerCompleted);
backgroundWorker.DoWork += new DoWorkEventHandler(DoPostLoadInitialization);
backgroundWorker.DoWork += new DoWorkEventHandler(DoPostLoadInitialization);
gCodeRenderer = new GCodeRenderer(loadedGCode);
backgroundWorker.RunWorkerAsync(gCodeRenderer);
}
gCodeRenderer = new GCodeRenderer(loadedGCode);
backgroundWorker.RunWorkerAsync(gCodeRenderer);
}
public static void DoPostLoadInitialization(object sender, DoWorkEventArgs doWorkEventArgs)
{
GCodeRenderer gCodeRenderer = (GCodeRenderer)doWorkEventArgs.Argument;
public static void DoPostLoadInitialization(object sender, DoWorkEventArgs doWorkEventArgs)
{
GCodeRenderer gCodeRenderer = (GCodeRenderer)doWorkEventArgs.Argument;
try
{
gCodeRenderer.GCodeFileToDraw.GetFilamentUsedMm(ActiveSliceSettings.Instance.NozzleDiameter);
@ -312,26 +306,26 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
{
}
gCodeRenderer.CreateFeaturesForLayerIfRequired(0);
}
}
void postLoadInitialization_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (LoadingProgressChanged != null)
{
LoadingProgressChanged(this, e);
}
}
private void postLoadInitialization_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (LoadingProgressChanged != null)
{
LoadingProgressChanged(this, e);
}
}
void postLoadInitialization_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (DoneLoading != null)
{
DoneLoading(this, null);
}
}
private void postLoadInitialization_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (DoneLoading != null)
{
DoneLoading(this, null);
}
}
private PathStorage grid = new PathStorage();
PathStorage grid = new PathStorage();
public override void OnDraw(Graphics2D graphics2D)
{
if (loadedGCode != null)
@ -345,7 +339,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
if (RenderGrid)
{
graphics2D.Render(stroke, new RGBA_Bytes(190, 190, 190, 255));
graphics2D.Render(stroke, new RGBA_Bytes(190, 190, 190, 255));
}
RenderType renderType = RenderType.Extrusions;
@ -357,23 +351,23 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
{
renderType |= RenderType.Retractions;
}
if (RenderSpeeds)
{
renderType |= RenderType.SpeedColors;
}
if (SimulateExtrusion)
{
renderType |= RenderType.SimulateExtrusion;
}
if (HideExtruderOffsets)
{
renderType |= RenderType.HideExtruderOffsets;
}
if (RenderSpeeds)
{
renderType |= RenderType.SpeedColors;
}
if (SimulateExtrusion)
{
renderType |= RenderType.SimulateExtrusion;
}
if (HideExtruderOffsets)
{
renderType |= RenderType.HideExtruderOffsets;
}
GCodeRenderInfo renderInfo = new GCodeRenderInfo(activeLayerIndex, activeLayerIndex, transform, layerScale, renderType,
FeatureToStartOnRatio0To1, FeatureToEndOnRatio0To1,
new Vector2[] { ActiveSliceSettings.Instance.GetOffset(0), ActiveSliceSettings.Instance.GetOffset(1) });
gCodeRenderer.Render(graphics2D, renderInfo);
GCodeRenderInfo renderInfo = new GCodeRenderInfo(activeLayerIndex, activeLayerIndex, transform, layerScale, renderType,
FeatureToStartOnRatio0To1, FeatureToEndOnRatio0To1,
new Vector2[] { ActiveSliceSettings.Instance.GetOffset(0), ActiveSliceSettings.Instance.GetOffset(1) });
gCodeRenderer.Render(graphics2D, renderInfo);
}
base.OnDraw(graphics2D);
@ -448,37 +442,36 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
Vector2 mouseDelta = mousePos - lastMousePosition;
switch (TransformState)
{
case ETransformState.Move:
ScallingTransform.inverse_transform(ref mouseDelta);
case ETransformState.Move:
ScallingTransform.inverse_transform(ref mouseDelta);
unscaledRenderOffset += mouseDelta;
break;
unscaledRenderOffset += mouseDelta;
break;
case ETransformState.Scale:
double zoomDelta = 1;
if (mouseDelta.y < 0)
{
zoomDelta = 1 - (-1 * mouseDelta.y / 100);
}
else if(mouseDelta.y > 0)
{
zoomDelta = 1 + (1 * mouseDelta.y / 100);
}
case ETransformState.Scale:
double zoomDelta = 1;
if (mouseDelta.y < 0)
{
zoomDelta = 1 - (-1 * mouseDelta.y / 100);
}
else if (mouseDelta.y > 0)
{
zoomDelta = 1 + (1 * mouseDelta.y / 100);
}
Vector2 mousePreScale = mouseDownPosition;
TotalTransform.inverse_transform(ref mousePreScale);
Vector2 mousePreScale = mouseDownPosition;
TotalTransform.inverse_transform(ref mousePreScale);
layerScale *= zoomDelta;
layerScale *= zoomDelta;
Vector2 mousePostScale = mouseDownPosition;
TotalTransform.inverse_transform(ref mousePostScale);
Vector2 mousePostScale = mouseDownPosition;
TotalTransform.inverse_transform(ref mousePostScale);
unscaledRenderOffset += (mousePostScale - mousePreScale);
break;
unscaledRenderOffset += (mousePostScale - mousePreScale);
break;
default:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
Invalidate();
@ -531,7 +524,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
{
layerScale = layerScale * (Width / oldWidth);
}
else if(gCodeRenderer != null)
else if (gCodeRenderer != null)
{
CenterPartInView();
}
@ -549,4 +542,4 @@ namespace MatterHackers.MatterControl.PartPreviewWindow
Invalidate();
}
}
}
}