mattercontrol/PartPreviewWindow/View3D/View3DWidget.cs

1448 lines
42 KiB
C#
Raw Normal View History

2014-01-29 19:09:30 -08:00
/*
Copyright (c) 2017, Lars Brubaker, John Lewin
2014-01-29 19:09:30 -08:00
All rights reserved.
Redistribution and use in source and binary forms, with or without
2015-04-08 15:20:10 -07:00
modification, are permitted provided that the following conditions are met:
2014-01-29 19:09:30 -08:00
1. Redistributions of source code must retain the above copyright notice, this
2015-04-08 15:20:10 -07:00
list of conditions and the following disclaimer.
2014-01-29 19:09:30 -08:00
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
2015-04-08 15:20:10 -07:00
and/or other materials provided with the distribution.
2014-01-29 19:09:30 -08:00
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
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
2015-04-08 15:20:10 -07:00
of the authors and should not be interpreted as representing official policies,
2014-01-29 19:09:30 -08:00
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
2014-01-29 19:09:30 -08:00
using MatterHackers.Agg;
2017-07-10 14:00:27 -07:00
using MatterHackers.Agg.OpenGlGui;
using MatterHackers.Agg.Platform;
2014-01-29 19:09:30 -08:00
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
2017-03-15 16:17:06 -07:00
using MatterHackers.DataConverters3D;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.Library;
using MatterHackers.MatterControl.PrintLibrary;
2014-01-29 19:09:30 -08:00
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
2014-01-29 19:09:30 -08:00
using MatterHackers.RayTracer;
using MatterHackers.RenderOpenGl;
using MatterHackers.VectorMath;
2014-01-29 19:09:30 -08:00
namespace MatterHackers.MatterControl.PartPreviewWindow
{
2018-01-18 09:38:57 -08:00
public class View3DWidget : GuiWidget
2015-04-08 15:20:10 -07:00
{
2017-03-15 16:17:06 -07:00
private bool DoBooleanTest = false;
2017-04-05 19:03:04 -07:00
private bool deferEditorTillMouseUp = false;
public readonly int EditButtonHeight = 44;
2017-03-15 16:17:06 -07:00
2015-05-30 12:48:16 -07:00
private bool hasDrawn = false;
2017-03-15 16:17:06 -07:00
2017-10-31 11:43:25 -07:00
private Color[] SelectionColors = new Color[] { new Color(131, 4, 66), new Color(227, 31, 61), new Color(255, 148, 1), new Color(247, 224, 23), new Color(143, 212, 1) };
2015-05-30 12:48:16 -07:00
private Stopwatch timeSinceLastSpin = new Stopwatch();
private Stopwatch timeSinceReported = new Stopwatch();
private Matrix4X4 transformOnMouseDown = Matrix4X4.Identity;
2015-04-08 15:20:10 -07:00
private ThemeConfig theme;
2017-09-05 18:02:19 -07:00
public Vector3 BedCenter
{
get
{
return new Vector3(sceneContext.BedCenter);
2017-09-05 18:02:19 -07:00
}
}
private WorldView World => sceneContext.World;
2017-07-10 14:00:27 -07:00
public TrackballTumbleWidget TrackballTumbleWidget { get; }
public InteractionLayer InteractionLayer { get; }
private BedConfig sceneContext;
private PrinterConfig printer;
2017-10-30 08:53:53 -07:00
private PrinterTabPage printerTabPage;
2017-11-07 14:55:45 -08:00
public View3DWidget(PrinterConfig printer, BedConfig sceneContext, AutoRotate autoRotate, ViewControls3D viewControls3D, ThemeConfig theme, PartTabPage printerTabBase, MeshViewerWidget.EditorType editorType = MeshViewerWidget.EditorType.Part)
2015-05-30 12:48:16 -07:00
{
2017-08-18 08:34:05 -07:00
var smallMarginButtonFactory = theme.SmallMarginButtonFactory;
this.sceneContext = sceneContext;
2017-10-30 08:53:53 -07:00
this.printerTabPage = printerTabBase as PrinterTabPage;
this.Scene = sceneContext.Scene;
this.printer = printer;
2017-07-10 14:00:27 -07:00
2017-09-16 01:19:35 -07:00
this.TrackballTumbleWidget = new TrackballTumbleWidget(sceneContext.World)
2017-07-10 14:00:27 -07:00
{
TransformState = TrackBallController.MouseDownType.Rotation
};
this.TrackballTumbleWidget.AnchorAll();
this.InteractionLayer = new InteractionLayer(this.World, this.Scene.UndoBuffer, this.Scene)
{
Name = "InteractionLayer",
};
this.InteractionLayer.AnchorAll();
this.viewControls3D = viewControls3D;
this.theme = theme;
this.Name = "View3DWidget";
2018-01-16 22:55:28 -08:00
this.BackgroundColor = theme.ActiveTabColor;
2018-01-16 21:48:20 -08:00
this.Border = new BorderDouble(top: 1);
this.BorderColor = theme.MinimalShade;
2017-08-18 08:34:05 -07:00
autoRotating = allowAutoRotate;
allowAutoRotate = (autoRotate == AutoRotate.Enabled);
viewControls3D.TransformStateChanged += ViewControls3D_TransformStateChanged;
var mainContainerTopToBottom = new FlowLayoutWidget(FlowDirection.TopToBottom)
{
HAnchor = HAnchor.MaxFitOrStretch,
VAnchor = VAnchor.MaxFitOrStretch
};
2015-04-08 15:20:10 -07:00
2017-08-18 08:34:05 -07:00
// MeshViewer
meshViewerWidget = new MeshViewerWidget(sceneContext, this.InteractionLayer, editorType: editorType);
meshViewerWidget.RenderBed = sceneContext.RendererOptions.RenderBed;
2017-07-05 15:37:32 -07:00
meshViewerWidget.AnchorAll();
this.InteractionLayer.AddChild(meshViewerWidget);
2015-04-08 15:20:10 -07:00
2017-08-18 08:34:05 -07:00
// TumbleWidget
this.InteractionLayer.AddChild(this.TrackballTumbleWidget);
2017-08-18 12:40:49 -07:00
this.InteractionLayer.SetRenderTarget(this.meshViewerWidget);
2017-07-10 14:00:27 -07:00
mainContainerTopToBottom.AddChild(this.InteractionLayer);
2015-04-08 15:20:10 -07:00
2017-03-15 16:17:06 -07:00
Scene.SelectionChanged += Scene_SelectionChanged;
2015-04-08 15:20:10 -07:00
// if the scene is invalidated invalidate the widget
Scene.Invalidated += (s, e) => Invalidate();
2017-06-27 18:41:34 -07:00
this.AddChild(mainContainerTopToBottom);
2015-04-08 15:20:10 -07:00
this.AnchorAll();
2014-01-29 19:09:30 -08:00
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Rotation;
selectedObjectPanel = new SelectedObjectPanel(this, this.Scene, theme, printer)
2017-03-15 16:17:06 -07:00
{
BackgroundColor = theme.InteractionLayerOverlayColor,
2018-01-05 11:45:11 -08:00
VAnchor = VAnchor.Stretch,
2017-03-15 16:17:06 -07:00
};
selectedObjectContainer = new ResizeContainer(selectedObjectPanel)
{
2018-01-08 23:53:39 -08:00
Width = printer?.ViewState.SelectedObjectPanelWidth ?? 200,
2018-01-05 11:45:11 -08:00
VAnchor = VAnchor.Stretch,
HAnchor = HAnchor.Right,
SpliterBarColor = theme.SplitterBackground,
SplitterWidth = theme.SplitterWidth,
Visible = false,
};
this.InteractionLayer.AddChild(selectedObjectContainer);
selectedObjectContainer.AddChild(selectedObjectPanel);
2017-03-15 16:17:06 -07:00
this.InteractionLayer.AddChild(new TumbleCubeControl(this.InteractionLayer)
{
Margin = new BorderDouble(50, 0, 0, 50),
VAnchor = VAnchor.Top,
HAnchor = HAnchor.Left,
});
2015-04-08 15:20:10 -07:00
UiThread.RunOnIdle(AutoSpin);
2014-05-27 09:16:35 -07:00
var interactionVolumes = this.InteractionLayer.InteractionVolumes;
interactionVolumes.Add(new MoveInZControl(this.InteractionLayer));
interactionVolumes.Add(new SelectionShadow(this.InteractionLayer));
interactionVolumes.Add(new SnappingIndicators(this.InteractionLayer, this.CurrentSelectInfo));
2015-04-08 15:20:10 -07:00
var interactionVolumePlugins = PluginFinder.CreateInstancesOf<InteractionVolumePlugin>();
foreach (InteractionVolumePlugin plugin in interactionVolumePlugins)
{
interactionVolumes.Add(plugin.CreateInteractionVolume(this.InteractionLayer));
}
2017-03-15 16:17:06 -07:00
if (DoBooleanTest)
{
BeforeDraw += CreateBooleanTestGeometry;
AfterDraw += RemoveBooleanTestGeometry;
}
meshViewerWidget.AfterDraw += AfterDraw3DContent;
sceneContext.LoadedGCodeChanged += SceneContext_LoadedGCodeChanged;
2017-09-15 23:17:03 -07:00
this.SwitchStateToEditing();
// Make sure the render mode is set correctly
string renderTypeString = UserSettings.Instance.get(UserSettingsKey.defaultRenderSetting);
if (renderTypeString == null)
{
renderTypeString = (UserSettings.Instance.IsTouchScreen) ? "Shaded" : "Outlines";
UserSettings.Instance.set(UserSettingsKey.defaultRenderSetting, renderTypeString);
}
RenderTypes renderType;
bool canParse = Enum.TryParse(renderTypeString, out renderType);
if (canParse)
{
meshViewerWidget.RenderType = renderType;
}
this.InteractionLayer.DrawGlOpaqueContent += Draw_GlOpaqueContent;
this.sceneContext.SceneLoaded += SceneContext_SceneLoaded;
this.viewControls3D.modelViewButton.Enabled = sceneContext.EditableScene;
}
private void SceneContext_SceneLoaded(object sender, EventArgs e)
{
2017-11-29 17:47:22 -08:00
if (this.printerTabPage?.printerActionsBar?.sliceButton is GuiWidget sliceButton)
{
sliceButton.Enabled = sceneContext.EditableScene;
}
this.viewControls3D.modelViewButton.Enabled = sceneContext.EditableScene;
this.Invalidate();
2017-03-15 16:17:06 -07:00
}
private void SceneContext_LoadedGCodeChanged(object sender, EventArgs e)
{
2017-10-30 08:53:53 -07:00
if (printerTabPage != null)
{
2017-12-18 12:25:23 -08:00
if (printerTabPage.gcode3DWidget != null)
{
// HACK: directly fire method which previously ran on SlicingDone event on PrintItemWrapper
UiThread.RunOnIdle(() => printerTabPage.gcode3DWidget.CreateAndAddChildren(printer));
}
}
}
private GuiWidget CreateActionSeparator()
{
return new VerticalLine(60)
{
Margin = new BorderDouble(3, 2, 0, 2),
};
}
private void ViewControls3D_TransformStateChanged(object sender, TransformStateChangedEventArgs e)
{
switch (e.TransformMode)
{
case ViewControls3DButtons.Rotate:
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Rotation;
break;
case ViewControls3DButtons.Translate:
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Translation;
break;
case ViewControls3DButtons.Scale:
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.Scale;
break;
case ViewControls3DButtons.PartSelect:
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState = TrackBallController.MouseDownType.None;
break;
}
}
2017-03-15 16:17:06 -07:00
public void SelectAll()
{
Scene.ClearSelection();
2017-08-28 09:14:55 -07:00
foreach (var child in Scene.Children.ToList())
2017-03-15 16:17:06 -07:00
{
Scene.AddToSelection(child);
}
}
2017-07-01 08:21:29 -07:00
private void Draw_GlOpaqueContent(object sender, DrawEventArgs e)
{
if (CurrentSelectInfo.DownOnPart
&& TrackballTumbleWidget.TransformState == TrackBallController.MouseDownType.None
&& Keyboard.IsKeyDown(Keys.ShiftKey))
{
// draw marks on the bed to show that the part is constrained to x and y
AxisAlignedBoundingBox selectedBounds = this.Scene.SelectedItem.GetAxisAlignedBoundingBox(Matrix4X4.Identity);
var drawCenter = CurrentSelectInfo.PlaneDownHitPos;
2017-10-31 11:43:25 -07:00
var drawColor = new Color(Color.Red, 20);
bool zBuffer = false;
for (int i = 0; i < 2; i++)
{
GLHelper.Render3DLine(World,
drawCenter - new Vector3(-50, 0, 0),
drawCenter - new Vector3(50, 0, 0), drawColor, zBuffer, 2);
GLHelper.Render3DLine(World,
drawCenter - new Vector3(0, -50, 0),
drawCenter - new Vector3(0, 50, 0), drawColor, zBuffer, 2);
2017-10-31 11:43:25 -07:00
drawColor = Color.Black;
drawCenter.Z = 0;
zBuffer = true;
}
}
// This shows the BVH as rects around the scene items
//Scene?.TraceData().RenderBvhRecursive(0, 3);
2017-07-10 14:00:27 -07:00
2017-10-30 08:53:53 -07:00
if (sceneContext.LoadedGCode == null || sceneContext.GCodeRenderer == null || printerTabPage?.gcode3DWidget.Visible == false)
2017-07-10 14:00:27 -07:00
{
return;
}
sceneContext.Render3DLayerFeatures(e);
}
public override void OnKeyDown(KeyEventArgs keyEvent)
{
// this must be called first to ensure we get the correct Handled state
base.OnKeyDown(keyEvent);
if (!keyEvent.Handled)
2017-06-07 15:56:02 -07:00
{
switch (keyEvent.KeyCode)
{
case Keys.A:
if (keyEvent.Control)
{
SelectAll();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.Z:
if (keyEvent.Control)
{
this.Scene.UndoBuffer.Undo();
2017-06-07 15:56:02 -07:00
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.Y:
if (keyEvent.Control)
{
this.Scene.UndoBuffer.Redo();
2017-06-07 15:56:02 -07:00
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.Delete:
case Keys.Back:
this.Scene.DeleteSelection();
2017-06-07 15:56:02 -07:00
break;
2017-06-07 15:56:02 -07:00
case Keys.Escape:
if (CurrentSelectInfo.DownOnPart)
{
CurrentSelectInfo.DownOnPart = false;
2017-06-07 15:56:02 -07:00
Scene.SelectedItem.Matrix = transformOnMouseDown;
Scene.Invalidate();
2017-06-07 15:56:02 -07:00
}
break;
case Keys.Space:
this.Scene.ClearSelection();
break;
2017-06-07 15:56:02 -07:00
}
}
}
2016-02-17 18:06:32 -08:00
public bool DragingPart
{
2016-02-19 08:29:49 -08:00
get { return CurrentSelectInfo.DownOnPart; }
2016-02-17 18:06:32 -08:00
}
2017-03-15 16:17:06 -07:00
public void AddUndoOperation(IUndoRedoCommand operation)
2016-02-14 17:53:44 -08:00
{
this.Scene.UndoBuffer.Add(operation);
2016-02-14 17:53:44 -08:00
}
#region DoBooleanTest
Object3D booleanGroup;
2016-03-12 14:16:34 -08:00
Vector3 offset = new Vector3();
Vector3 direction = new Vector3(.11, .12, .13);
Vector3 rotCurrent = new Vector3();
Vector3 rotChange = new Vector3(.011, .012, .013);
Vector3 scaleChange = new Vector3(.0011, .0012, .0013);
Vector3 scaleCurrent = new Vector3(1, 1, 1);
2017-03-15 16:17:06 -07:00
private void CreateBooleanTestGeometry(object sender, DrawEventArgs e)
2016-03-07 14:23:22 -08:00
{
try
{
booleanGroup = new Object3D();
2017-03-15 16:17:06 -07:00
booleanGroup.Children.Add(new Object3D()
{
Mesh = ApplyBoolean(PolygonMesh.Csg.CsgOperations.Union, AxisAlignedBoundingBox.Union, new Vector3(100, 0, 20), "U")
});
2016-03-07 14:23:22 -08:00
2017-03-15 16:17:06 -07:00
booleanGroup.Children.Add(new Object3D()
{
Mesh = ApplyBoolean(PolygonMesh.Csg.CsgOperations.Subtract, null, new Vector3(100, 100, 20), "S")
});
booleanGroup.Children.Add(new Object3D()
{
Mesh = ApplyBoolean(PolygonMesh.Csg.CsgOperations.Intersect, AxisAlignedBoundingBox.Intersection, new Vector3(100, 200, 20), "I")
});
2016-03-07 14:23:22 -08:00
offset += direction;
2016-03-12 14:16:34 -08:00
rotCurrent += rotChange;
scaleCurrent += scaleChange;
2016-03-07 14:23:22 -08:00
2017-09-26 12:52:54 -07:00
this.Scene.Children.Modify(list =>
2017-03-15 16:17:06 -07:00
{
2017-09-26 12:52:54 -07:00
list.Add(booleanGroup);
2017-03-15 16:17:06 -07:00
});
2016-03-07 14:23:22 -08:00
}
catch (Exception e2)
2016-03-07 14:23:22 -08:00
{
string text = e2.Message;
2017-03-15 16:17:06 -07:00
int a = 0;
2016-03-07 14:23:22 -08:00
}
}
2018-01-12 17:39:54 -08:00
private Mesh ApplyBoolean(Func<Mesh, Mesh, Mesh> meshOperation, Func<AxisAlignedBoundingBox, AxisAlignedBoundingBox, AxisAlignedBoundingBox> aabbOperation, Vector3 centering, string opp)
2016-03-07 14:23:22 -08:00
{
Mesh boxA = PlatonicSolids.CreateCube(40, 40, 40);
2017-03-15 16:17:06 -07:00
//boxA = PlatonicSolids.CreateIcosahedron(35);
2016-03-07 14:23:22 -08:00
boxA.Translate(centering);
Mesh boxB = PlatonicSolids.CreateCube(40, 40, 40);
2017-03-15 16:17:06 -07:00
//boxB = PlatonicSolids.CreateIcosahedron(35);
2016-03-07 14:23:22 -08:00
for (int i = 0; i < 3; i++)
{
if (Math.Abs(direction[i] + offset[i]) > 10)
{
2016-03-12 14:16:34 -08:00
direction[i] = direction[i] * -1.00073112;
2016-03-07 14:23:22 -08:00
}
}
2016-03-12 14:16:34 -08:00
for (int i = 0; i < 3; i++)
{
if (Math.Abs(rotChange[i] + rotCurrent[i]) > 6)
{
rotChange[i] = rotChange[i] * -1.000073112;
}
}
for (int i = 0; i < 3; i++)
{
if (scaleChange[i] + scaleCurrent[i] > 1.1 || scaleChange[i] + scaleCurrent[i] < .9)
{
scaleChange[i] = scaleChange[i] * -1.000073112;
}
}
Vector3 offsetB = offset + centering;
// switch to the failing offset
//offsetB = new Vector3(105.240172225344, 92.9716306394062, 18.4619570261172);
//rotCurrent = new Vector3(4.56890223673623, -2.67874102322035, 1.02768848238523);
//scaleCurrent = new Vector3(1.07853517569753, 0.964980885267323, 1.09290934544604);
Debug.WriteLine("t" + offsetB.ToString() + " r" + rotCurrent.ToString() + " s" + scaleCurrent.ToString() + " " + opp);
2016-03-12 14:16:34 -08:00
Matrix4X4 transformB = Matrix4X4.CreateScale(scaleCurrent) * Matrix4X4.CreateRotation(rotCurrent) * Matrix4X4.CreateTranslation(offsetB);
boxB.Transform(transformB);
2018-01-12 17:39:54 -08:00
Mesh meshToAdd = meshOperation(boxA, boxB);
meshToAdd.CleanAndMergMesh(CancellationToken.None);
2018-01-12 17:39:54 -08:00
if (aabbOperation != null)
{
AxisAlignedBoundingBox boundsA = boxA.GetAxisAlignedBoundingBox();
AxisAlignedBoundingBox boundsB = boxB.GetAxisAlignedBoundingBox();
AxisAlignedBoundingBox boundsAdd = meshToAdd.GetAxisAlignedBoundingBox();
2018-01-12 17:39:54 -08:00
AxisAlignedBoundingBox boundsResult = aabbOperation(boundsA, boundsB);
}
2016-03-07 14:23:22 -08:00
return meshToAdd;
}
2017-03-15 16:17:06 -07:00
private void RemoveBooleanTestGeometry(object sender, DrawEventArgs e)
{
if (this.Scene.Children.Contains(booleanGroup))
2016-03-07 14:23:22 -08:00
{
this.Scene.Children.Remove(booleanGroup);
2016-03-07 14:23:22 -08:00
UiThread.RunOnIdle(() => Invalidate(), 1.0 / 30.0);
}
}
2017-03-15 16:17:06 -07:00
#endregion DoBooleanTest
2015-04-08 15:20:10 -07:00
public enum AutoRotate { Enabled, Disabled };
2015-05-30 12:48:16 -07:00
public bool DisplayAllValueData { get; set; }
2017-03-15 16:17:06 -07:00
public override void OnClosed(ClosedEventArgs e)
2015-05-30 12:48:16 -07:00
{
2018-01-08 23:53:39 -08:00
if (printer != null)
{
printer.ViewState.SelectedObjectPanelWidth = selectedObjectPanel.Width;
}
viewControls3D.TransformStateChanged -= ViewControls3D_TransformStateChanged;
sceneContext.LoadedGCodeChanged -= SceneContext_LoadedGCodeChanged;
this.Scene.SelectionChanged -= Scene_SelectionChanged;
this.InteractionLayer.DrawGlOpaqueContent -= Draw_GlOpaqueContent;
this.sceneContext.SceneLoaded -= SceneContext_SceneLoaded;
if (meshViewerWidget != null)
{
meshViewerWidget.AfterDraw -= AfterDraw3DContent;
}
2017-03-15 16:17:06 -07:00
base.OnClosed(e);
2015-05-30 12:48:16 -07:00
}
2017-03-15 16:17:06 -07:00
private GuiWidget topMostParent;
private PlaneShape bedPlane = new PlaneShape(Vector3.UnitZ, 0, null);
public bool DragOperationActive { get; private set; }
public InsertionGroup DragDropObject { get; private set; }
public ILibraryContentStream SceneReplacement { get; private set; }
2017-03-15 16:17:06 -07:00
/// <summary>
/// Provides a View3DWidget specific drag implementation
/// </summary>
/// <param name="screenSpaceMousePosition">The screen space mouse position.</param>
public void ExternalDragOver(Vector2 screenSpaceMousePosition)
2015-04-08 15:20:10 -07:00
{
if (this.HasBeenClosed)
2017-03-15 16:17:06 -07:00
{
return;
2017-03-15 16:17:06 -07:00
}
// If the mouse is within the MeshViewer process the Drag move
2017-03-15 16:17:06 -07:00
var meshViewerPosition = this.meshViewerWidget.TransformToScreenSpace(meshViewerWidget.LocalBounds);
if (meshViewerPosition.Contains(screenSpaceMousePosition))
2015-05-30 12:48:16 -07:00
{
// If already started, process drag move
if (this.DragOperationActive)
2015-05-30 12:48:16 -07:00
{
this.DragOver(screenSpaceMousePosition);
2017-03-15 16:17:06 -07:00
}
else
2017-03-15 16:17:06 -07:00
{
// Otherwise begin an externally started DragDropOperation hard-coded to use LibraryView->SelectedItems
this.StartDragDrop(
// Project from ListViewItem to ILibraryItem
ApplicationController.Instance.Library.ActiveViewWidget.SelectedItems.Select(l => l.Model),
screenSpaceMousePosition);
2015-05-30 12:48:16 -07:00
}
2017-03-15 16:17:06 -07:00
2015-05-30 12:48:16 -07:00
}
}
2017-03-15 16:17:06 -07:00
private void DragOver(Vector2 screenSpaceMousePosition)
{
// Move the object being dragged
if (this.DragOperationActive
&& this.DragDropObject != null)
{
// Move the DropDropObject the target item
DragSelectedObject(localMousePostion: this.TransformFromParentSpace(topMostParent, screenSpaceMousePosition));
}
2015-04-08 15:20:10 -07:00
}
private void StartDragDrop(IEnumerable<ILibraryItem> items, Vector2 screenSpaceMousePosition, bool trackSourceFiles = false)
{
this.DragOperationActive = true;
var firstItem = items.FirstOrDefault();
if ((firstItem is ILibraryContentStream contentStream
&& contentStream.ContentType == "gcode")
|| firstItem is SceneReplacementFileItem)
{
DragDropObject = null;
this.SceneReplacement = firstItem as ILibraryContentStream;
// TODO: Figure out a mechanism to disable View3DWidget with dark overlay, displaying something like "Switch to xxx.gcode", make disappear on mouseLeaveBounds and dragfinish
this.InteractionLayer.BackgroundColor = new Color(Color.Black, 200);
return;
}
// Set the hitplane to the bed plane
CurrentSelectInfo.HitPlane = bedPlane;
var insertionGroup = new InsertionGroup(
2017-09-28 15:51:31 -07:00
items,
this,
this.Scene,
sceneContext.BedCenter,
() => this.DragOperationActive,
trackSourceFiles);
// Find intersection position of the mouse with the bed plane
var intersectInfo = GetIntersectPosition(screenSpaceMousePosition);
if (intersectInfo != null)
{
// Set the initial transform on the inject part to the current transform mouse position
var sourceItemBounds = insertionGroup.GetAxisAlignedBoundingBox(Matrix4X4.Identity);
var center = sourceItemBounds.Center;
insertionGroup.Matrix *= Matrix4X4.CreateTranslation(-center.X, -center.Y, -sourceItemBounds.minXYZ.Z);
insertionGroup.Matrix *= Matrix4X4.CreateTranslation(new Vector3(intersectInfo.HitPosition));
2017-09-16 01:11:44 -07:00
CurrentSelectInfo.PlaneDownHitPos = intersectInfo.HitPosition;
CurrentSelectInfo.LastMoveDelta = Vector3.Zero;
}
2017-09-16 01:11:44 -07:00
this.deferEditorTillMouseUp = true;
2015-04-08 15:20:10 -07:00
// Add item to scene and select it
2017-09-26 12:52:54 -07:00
this.Scene.Children.Modify(list =>
2017-03-15 16:17:06 -07:00
{
list.Add(insertionGroup);
});
Scene.SelectedItem = insertionGroup;
2017-03-15 16:17:06 -07:00
this.DragDropObject = insertionGroup;
}
internal void FinishDrop(bool mouseUpInBounds)
{
if (this.DragOperationActive)
2017-03-15 16:17:06 -07:00
{
this.InteractionLayer.BackgroundColor = Color.Transparent;
this.DragOperationActive = false;
if (mouseUpInBounds)
{
if (this.DragDropObject == null
&& this.SceneReplacement != null)
{
// Drop handler for special case of GCode or similar (change loaded scene to new context)
sceneContext.LoadContent(
new EditContext()
{
SourceItem = this.SceneReplacement,
// No content store for GCode, otherwise PlatingHistory
ContentStore = (this.SceneReplacement.ContentType == "gcode") ? null : ApplicationController.Instance.Library.PlatingHistory
}).ConfigureAwait(false);
this.SceneReplacement = null;
}
else if (this.DragDropObject.ContentAcquired)
{
// Drop handler for InsertionGroup - all normal content
this.viewControls3D.modelViewButton.Enabled = true;
this.DragDropObject.Collapse();
}
2017-04-05 19:03:04 -07:00
}
else
2017-04-05 19:03:04 -07:00
{
2017-09-26 12:54:40 -07:00
this.Scene.Children.Modify(list => list.Remove(this.DragDropObject));
this.Scene.ClearSelection();
}
this.DragDropObject = null;
this.deferEditorTillMouseUp = false;
Scene_SelectionChanged(null, null);
Scene.Invalidate();
// Set focus to View3DWidget after drag-drop
UiThread.RunOnIdle(this.Focus);
2017-03-15 16:17:06 -07:00
}
}
public override void OnLoad(EventArgs args)
{
topMostParent = this.TopmostParent();
// Set reference on show
var dragDropData = ApplicationController.Instance.DragDropData;
dragDropData.View3DWidget = this;
2017-10-05 22:32:23 -07:00
dragDropData.SceneContext = sceneContext;
base.OnLoad(args);
2017-03-15 16:17:06 -07:00
}
public override void OnDraw(Graphics2D graphics2D)
{
var selectedItem = Scene.SelectedItem;
if (Scene.HasSelection
&& selectedItem != null)
2015-05-30 12:48:16 -07:00
{
2017-03-15 16:17:06 -07:00
foreach (InteractionVolume volume in this.InteractionLayer.InteractionVolumes)
{
2017-03-15 16:17:06 -07:00
volume.SetPosition(selectedItem);
}
2015-04-08 15:20:10 -07:00
}
2014-03-20 18:20:52 -07:00
2015-05-30 12:48:16 -07:00
hasDrawn = true;
2015-05-30 12:48:16 -07:00
base.OnDraw(graphics2D);
}
2015-04-08 15:20:10 -07:00
private void AfterDraw3DContent(object sender, DrawEventArgs e)
{
if (DragSelectionInProgress)
{
var selectionRectangle = new RectangleDouble(DragSelectionStartPosition, DragSelectionEndPosition);
2017-10-31 11:43:25 -07:00
e.graphics2D.Rectangle(selectionRectangle, Color.Red);
}
}
bool foundTriangleInSelectionBounds;
2017-06-06 10:57:13 -07:00
private void DoRectangleSelection(DrawEventArgs e)
{
var allResults = new List<BvhIterator>();
2017-06-06 10:57:13 -07:00
var matchingSceneChildren = Scene.Children.Where(item =>
{
foundTriangleInSelectionBounds = false;
2017-06-06 10:57:13 -07:00
// Filter the IPrimitive trace data finding matches as defined in InSelectionBounds
var filteredResults = item.TraceData().Filter(InSelectionBounds);
2017-06-06 10:57:13 -07:00
// Accumulate all matching BvhIterator results for debug rendering
allResults.AddRange(filteredResults);
return foundTriangleInSelectionBounds;
});
2017-06-06 10:57:13 -07:00
// Apply selection
if (matchingSceneChildren.Any())
{
2017-06-21 15:56:25 -07:00
// If we are actually doing the selection rather than debugging the data
if (e == null)
{
Scene.ClearSelection();
2017-08-22 15:55:52 -07:00
foreach (var sceneItem in matchingSceneChildren.ToList())
2017-06-21 15:56:25 -07:00
{
Scene.AddToSelection(sceneItem);
}
}
else
{
InteractionLayer.RenderBounds(e, World, allResults);
}
}
}
private bool InSelectionBounds(BvhIterator x)
{
var selectionRectangle = new RectangleDouble(DragSelectionStartPosition, DragSelectionEndPosition);
Vector2[] traceBottoms = new Vector2[4];
Vector2[] traceTops = new Vector2[4];
if (foundTriangleInSelectionBounds)
{
return false;
}
if (x.Bvh is TriangleShape tri)
{
// check if any vertex in screen rect
// calculate all the top and bottom screen positions
for (int i = 0; i < 3; i++)
{
Vector3 bottomStartPosition = Vector3.Transform(tri.GetVertex(i), x.TransformToWorld);
2017-07-10 14:00:27 -07:00
traceBottoms[i] = this.World.GetScreenPosition(bottomStartPosition);
}
for (int i = 0; i < 3; i++)
{
if (selectionRectangle.ClipLine(traceBottoms[i], traceBottoms[(i + 1) % 3]))
{
foundTriangleInSelectionBounds = true;
return true;
}
}
}
else
{
// calculate all the top and bottom screen positions
for (int i = 0; i < 4; i++)
{
Vector3 bottomStartPosition = Vector3.Transform(x.Bvh.GetAxisAlignedBoundingBox().GetBottomCorner(i), x.TransformToWorld);
2017-07-10 14:00:27 -07:00
traceBottoms[i] = this.World.GetScreenPosition(bottomStartPosition);
Vector3 topStartPosition = Vector3.Transform(x.Bvh.GetAxisAlignedBoundingBox().GetTopCorner(i), x.TransformToWorld);
2017-07-10 14:00:27 -07:00
traceTops[i] = this.World.GetScreenPosition(topStartPosition);
}
RectangleDouble.OutCode allPoints = RectangleDouble.OutCode.Inside;
// check if we are inside all the points
for (int i = 0; i < 4; i++)
{
allPoints |= selectionRectangle.ComputeOutCode(traceBottoms[i]);
allPoints |= selectionRectangle.ComputeOutCode(traceTops[i]);
}
if (allPoints == RectangleDouble.OutCode.Surrounded)
{
return true;
}
for (int i = 0; i < 4; i++)
{
if (selectionRectangle.ClipLine(traceBottoms[i], traceBottoms[(i + 1) % 4])
|| selectionRectangle.ClipLine(traceTops[i], traceTops[(i + 1) % 4])
|| selectionRectangle.ClipLine(traceTops[i], traceBottoms[i]))
{
return true;
}
}
}
return false;
}
private ViewControls3DButtons? activeButtonBeforeMouseOverride = null;
2015-05-30 12:48:16 -07:00
public override void OnMouseDown(MouseEventArgs mouseEvent)
2015-04-08 15:20:10 -07:00
{
// Show transform override
2018-01-18 09:38:57 -08:00
if (activeButtonBeforeMouseOverride == null
&& (mouseEvent.Button == MouseButtons.Right || Keyboard.IsKeyDown(Keys.Control)))
{
2018-01-18 09:38:57 -08:00
if (Keyboard.IsKeyDown(Keys.Shift))
{
activeButtonBeforeMouseOverride = viewControls3D.ActiveButton;
viewControls3D.ActiveButton = ViewControls3DButtons.Translate;
}
else if(Keyboard.IsKeyDown(Keys.Alt))
{
activeButtonBeforeMouseOverride = viewControls3D.ActiveButton;
viewControls3D.ActiveButton = ViewControls3DButtons.Scale;
}
2018-01-18 09:38:57 -08:00
else
{
activeButtonBeforeMouseOverride = viewControls3D.ActiveButton;
viewControls3D.ActiveButton = ViewControls3DButtons.Rotate;
}
}
else if (activeButtonBeforeMouseOverride == null && mouseEvent.Button == MouseButtons.Middle)
{
activeButtonBeforeMouseOverride = viewControls3D.ActiveButton;
viewControls3D.ActiveButton = ViewControls3DButtons.Translate;
}
2017-03-15 16:17:06 -07:00
if(mouseEvent.Button == MouseButtons.Right ||
mouseEvent.Button == MouseButtons.Middle)
{
meshViewerWidget.SuppressUiVolumes = true;
}
2015-05-30 12:48:16 -07:00
autoRotating = false;
base.OnMouseDown(mouseEvent);
2017-03-15 16:17:06 -07:00
2017-07-10 14:00:27 -07:00
if (this.TrackballTumbleWidget.UnderMouseState == UnderMouseState.FirstUnderMouse)
2015-04-08 15:20:10 -07:00
{
2017-03-15 16:17:06 -07:00
if (mouseEvent.Button == MouseButtons.Left
2018-01-18 09:38:57 -08:00
&& viewControls3D.ActiveButton == ViewControls3DButtons.PartSelect
2017-03-15 16:17:06 -07:00
&&
(ModifierKeys == Keys.Shift || ModifierKeys == Keys.Control)
|| (
2017-07-10 14:00:27 -07:00
this.TrackballTumbleWidget.TransformState == TrackBallController.MouseDownType.None
&& ModifierKeys != Keys.Control
&& ModifierKeys != Keys.Alt))
2015-04-08 15:20:10 -07:00
{
if (!this.InteractionLayer.MouseDownOnInteractionVolume)
2015-05-30 12:48:16 -07:00
{
2017-03-15 16:17:06 -07:00
meshViewerWidget.SuppressUiVolumes = true;
2016-02-19 08:29:49 -08:00
IntersectInfo info = new IntersectInfo();
2017-03-15 16:17:06 -07:00
IObject3D hitObject = FindHitObject3D(mouseEvent.Position, ref info);
if (hitObject == null)
{
if (Scene.HasSelection)
{
2017-08-22 15:55:52 -07:00
Scene.ClearSelection();
}
// start a selection rect
DragSelectionStartPosition = mouseEvent.Position - OffsetToMeshViewerWidget();
DragSelectionEndPosition = DragSelectionStartPosition;
DragSelectionInProgress = true;
}
else
2015-05-30 12:48:16 -07:00
{
CurrentSelectInfo.HitPlane = new PlaneShape(Vector3.UnitZ, CurrentSelectInfo.PlaneDownHitPos.Z, null);
2014-03-20 18:20:52 -07:00
2017-03-15 16:17:06 -07:00
if (hitObject != Scene.SelectedItem)
{
if (Scene.SelectedItem == null)
{
// No selection exists
2017-08-22 15:55:52 -07:00
Scene.SelectedItem = hitObject;
2017-03-15 16:17:06 -07:00
}
else if ((ModifierKeys == Keys.Shift || ModifierKeys == Keys.Control)
&& !Scene.SelectedItem.Children.Contains(hitObject))
2017-03-15 16:17:06 -07:00
{
Scene.AddToSelection(hitObject);
}
else if (Scene.SelectedItem == hitObject || Scene.SelectedItem.Children.Contains(hitObject))
{
// Selection should not be cleared and drag should occur
}
else if (ModifierKeys != Keys.Shift)
{
2017-08-22 15:55:52 -07:00
Scene.SelectedItem = hitObject;
2017-03-15 16:17:06 -07:00
}
Invalidate();
2017-03-15 16:17:06 -07:00
}
transformOnMouseDown = Scene.SelectedItem.Matrix;
2015-04-08 15:20:10 -07:00
2015-05-30 12:48:16 -07:00
Invalidate();
2016-02-19 08:29:49 -08:00
CurrentSelectInfo.DownOnPart = true;
AxisAlignedBoundingBox selectedBounds = this.Scene.SelectedItem.GetAxisAlignedBoundingBox(Matrix4X4.Identity);
2016-02-19 08:29:49 -08:00
if (info.HitPosition.X < selectedBounds.Center.X)
2016-02-19 08:29:49 -08:00
{
if (info.HitPosition.Y < selectedBounds.Center.Y)
2016-02-19 08:29:49 -08:00
{
CurrentSelectInfo.HitQuadrant = HitQuadrant.LB;
}
else
{
CurrentSelectInfo.HitQuadrant = HitQuadrant.LT;
}
}
else
{
if (info.HitPosition.Y < selectedBounds.Center.Y)
2016-02-19 08:29:49 -08:00
{
CurrentSelectInfo.HitQuadrant = HitQuadrant.RB;
}
else
{
CurrentSelectInfo.HitQuadrant = HitQuadrant.RT;
}
}
2015-05-30 12:48:16 -07:00
}
}
2015-04-08 15:20:10 -07:00
}
2015-05-30 12:48:16 -07:00
}
}
2015-02-27 11:09:37 -08:00
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
// File system Drop validation
mouseEvent.AcceptDrop = this.AllowDragDrop()
&& mouseEvent.DragFiles?.Count > 0
&& mouseEvent.DragFiles.TrueForAll(filePath => ApplicationController.Instance.IsLoadableFile(filePath));
// View3DWidgets Filesystem DropDrop handler
if (mouseEvent.AcceptDrop
&& this.PositionWithinLocalBounds(mouseEvent.X, mouseEvent.Y))
{
if (this.DragOperationActive)
{
DragOver(screenSpaceMousePosition: this.TransformToScreenSpace(mouseEvent.Position));
}
else
{
// Project DragFiles to IEnumerable<FileSystemFileItem>
this.StartDragDrop(
mouseEvent.DragFiles.Select(path => new FileSystemFileItem(path)),
screenSpaceMousePosition: this.TransformToScreenSpace(mouseEvent.Position),
trackSourceFiles: true);
}
}
if (CurrentSelectInfo.DownOnPart && this.TrackballTumbleWidget.TransformState == TrackBallController.MouseDownType.None)
{
DragSelectedObject(new Vector2(mouseEvent.X, mouseEvent.Y));
}
if (DragSelectionInProgress)
{
DragSelectionEndPosition = mouseEvent.Position - OffsetToMeshViewerWidget();
DragSelectionEndPosition = new Vector2(
Math.Max(Math.Min(DragSelectionEndPosition.X, meshViewerWidget.LocalBounds.Right), meshViewerWidget.LocalBounds.Left),
Math.Max(Math.Min(DragSelectionEndPosition.Y, meshViewerWidget.LocalBounds.Top), meshViewerWidget.LocalBounds.Bottom));
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
2017-03-15 16:17:06 -07:00
public IntersectInfo GetIntersectPosition(Vector2 screenSpacePosition)
{
//Vector2 meshViewerWidgetScreenPosition = meshViewerWidget.TransformFromParentSpace(this, new Vector2(mouseEvent.X, mouseEvent.Y));
2017-03-15 16:17:06 -07:00
// Translate to local
Vector2 localPosition = this.TransformFromScreenSpace(screenSpacePosition);
2017-07-10 14:00:27 -07:00
Ray ray = this.World.GetRayForLocalBounds(localPosition);
2017-03-15 16:17:06 -07:00
return CurrentSelectInfo.HitPlane.GetClosestIntersection(ray);
}
public void DragSelectedObject(Vector2 localMousePostion)
2015-05-30 12:48:16 -07:00
{
2017-03-15 16:17:06 -07:00
Vector2 meshViewerWidgetScreenPosition = meshViewerWidget.TransformFromParentSpace(this, localMousePostion);
2017-07-10 14:00:27 -07:00
Ray ray = this.World.GetRayForLocalBounds(meshViewerWidgetScreenPosition);
2017-03-15 16:17:06 -07:00
IntersectInfo info = CurrentSelectInfo.HitPlane.GetClosestIntersection(ray);
if (info != null)
2015-05-30 12:48:16 -07:00
{
2017-03-15 16:17:06 -07:00
// move the mesh back to the start position
{
Matrix4X4 totalTransform = Matrix4X4.CreateTranslation(new Vector3(-CurrentSelectInfo.LastMoveDelta));
Scene.SelectedItem.Matrix *= totalTransform;
// Invalidate the item to account for the position change
Scene.SelectedItem.Invalidate();
2017-03-15 16:17:06 -07:00
}
2017-06-16 11:12:24 -07:00
Vector3 delta = info.HitPosition - CurrentSelectInfo.PlaneDownHitPos;
2017-03-15 16:17:06 -07:00
double snapGridDistance = this.InteractionLayer.SnapGridDistance;
2017-03-15 16:17:06 -07:00
if (snapGridDistance > 0)
2015-02-27 11:09:37 -08:00
{
2017-03-15 16:17:06 -07:00
// snap this position to the grid
AxisAlignedBoundingBox selectedBounds = this.Scene.SelectedItem.GetAxisAlignedBoundingBox(Matrix4X4.Identity);
2017-03-15 16:17:06 -07:00
double xSnapOffset = selectedBounds.minXYZ.X;
2017-03-15 16:17:06 -07:00
// snap the x position
if (CurrentSelectInfo.HitQuadrant == HitQuadrant.RB
|| CurrentSelectInfo.HitQuadrant == HitQuadrant.RT)
2016-02-18 09:36:01 -08:00
{
2017-03-15 16:17:06 -07:00
// switch to the other side
xSnapOffset = selectedBounds.maxXYZ.X;
2016-02-18 09:36:01 -08:00
}
double xToSnap = xSnapOffset + delta.X;
2016-02-18 09:36:01 -08:00
2017-03-15 16:17:06 -07:00
double snappedX = ((int)((xToSnap / snapGridDistance) + .5)) * snapGridDistance;
delta.X = snappedX - xSnapOffset;
2015-02-27 11:09:37 -08:00
double ySnapOffset = selectedBounds.minXYZ.Y;
2017-03-15 16:17:06 -07:00
// snap the y position
if (CurrentSelectInfo.HitQuadrant == HitQuadrant.LT
|| CurrentSelectInfo.HitQuadrant == HitQuadrant.RT)
{
2017-03-15 16:17:06 -07:00
// switch to the other side
ySnapOffset = selectedBounds.maxXYZ.Y;
2017-03-15 16:17:06 -07:00
}
double yToSnap = ySnapOffset + delta.Y;
2017-03-15 16:17:06 -07:00
double snappedY = ((int)((yToSnap / snapGridDistance) + .5)) * snapGridDistance;
delta.Y = snappedY - ySnapOffset;
2017-03-15 16:17:06 -07:00
}
// if the shift key is down only move on the major axis of x or y
if(Keyboard.IsKeyDown(Keys.ShiftKey))
{
if(Math.Abs(delta.X) < Math.Abs(delta.Y))
{
delta.X = 0;
}
else
{
delta.Y = 0;
}
}
2017-03-15 16:17:06 -07:00
// move the mesh back to the new position
{
Matrix4X4 totalTransform = Matrix4X4.CreateTranslation(new Vector3(delta));
2015-02-27 11:09:37 -08:00
2017-03-15 16:17:06 -07:00
Scene.SelectedItem.Matrix *= totalTransform;
2016-02-18 09:36:01 -08:00
2017-03-15 16:17:06 -07:00
CurrentSelectInfo.LastMoveDelta = delta;
}
2016-02-18 09:36:01 -08:00
2017-03-15 16:17:06 -07:00
Invalidate();
}
}
2015-02-27 11:09:37 -08:00
Vector2 OffsetToMeshViewerWidget()
{
List<GuiWidget> parents = new List<GuiWidget>();
GuiWidget parent = meshViewerWidget.Parent;
while (parent != this)
{
parents.Add(parent);
parent = parent.Parent;
}
Vector2 offset = new Vector2();
for(int i=parents.Count-1; i>=0; i--)
{
offset += parents[i].OriginRelativeParent;
}
return offset;
}
2017-07-10 14:00:27 -07:00
public void ResetView()
{
this.TrackballTumbleWidget.ZeroVelocity();
var world = this.World;
world.Reset();
world.Scale = .03;
world.Translate(-new Vector3(sceneContext.BedCenter));
world.Rotate(Quaternion.FromEulerAngles(new Vector3(0, 0, -MathHelper.Tau / 16)));
world.Rotate(Quaternion.FromEulerAngles(new Vector3(MathHelper.Tau * .19, 0, 0)));
2017-07-10 14:00:27 -07:00
}
2015-05-30 12:48:16 -07:00
public override void OnMouseUp(MouseEventArgs mouseEvent)
2015-04-08 15:20:10 -07:00
{
if (this.DragOperationActive)
{
this.FinishDrop(mouseUpInBounds: true);
}
2017-07-10 14:00:27 -07:00
if (this.TrackballTumbleWidget.TransformState == TrackBallController.MouseDownType.None)
2015-04-08 15:20:10 -07:00
{
2017-07-11 12:50:21 -07:00
if (Scene.SelectedItem != null
&& CurrentSelectInfo.DownOnPart
&& CurrentSelectInfo.LastMoveDelta != Vector3.Zero)
{
InteractionLayer.AddTransformSnapshot(transformOnMouseDown);
}
else if (DragSelectionInProgress)
{
2017-06-06 10:57:13 -07:00
DoRectangleSelection(null);
DragSelectionInProgress = false;
}
2015-05-30 12:48:16 -07:00
}
2015-04-08 15:20:10 -07:00
2017-03-15 16:17:06 -07:00
meshViewerWidget.SuppressUiVolumes = false;
2016-02-19 08:29:49 -08:00
CurrentSelectInfo.DownOnPart = false;
2015-04-08 15:20:10 -07:00
if (activeButtonBeforeMouseOverride != null)
{
viewControls3D.ActiveButton = (ViewControls3DButtons)activeButtonBeforeMouseOverride;
activeButtonBeforeMouseOverride = null;
}
2015-05-30 12:48:16 -07:00
base.OnMouseUp(mouseEvent);
if (deferEditorTillMouseUp)
{
this.deferEditorTillMouseUp = false;
Scene_SelectionChanged(null, null);
}
2015-05-30 12:48:16 -07:00
}
2015-04-08 15:20:10 -07:00
2017-09-16 01:36:19 -07:00
// TODO: Consider if we should always allow DragDrop or if we should prevent during printer or other scenarios
private bool AllowDragDrop() => true;
2015-05-30 12:48:16 -07:00
private void AutoSpin()
2015-05-30 12:48:16 -07:00
{
if (!HasBeenClosed && autoRotating)
2015-05-30 12:48:16 -07:00
{
// add it back in to keep it running.
UiThread.RunOnIdle(AutoSpin, .04);
if ((!timeSinceLastSpin.IsRunning || timeSinceLastSpin.ElapsedMilliseconds > 50)
&& hasDrawn)
{
hasDrawn = false;
timeSinceLastSpin.Restart();
Quaternion currentRotation = this.World.RotationMatrix.GetRotation();
2015-05-30 12:48:16 -07:00
Quaternion invertedRotation = Quaternion.Invert(currentRotation);
Quaternion rotateAboutZ = Quaternion.FromEulerAngles(new Vector3(0, 0, .01));
rotateAboutZ = invertedRotation * rotateAboutZ * currentRotation;
2017-07-10 14:00:27 -07:00
this.World.Rotate(rotateAboutZ);
2015-05-30 12:48:16 -07:00
Invalidate();
}
}
}
2017-03-15 16:17:06 -07:00
private void Scene_SelectionChanged(object sender, EventArgs e)
{
if (!Scene.HasSelection)
{
2018-01-09 09:14:12 -08:00
if (printer != null)
{
printer.ViewState.SelectedObjectPanelWidth = selectedObjectPanel.Width;
}
selectedObjectContainer.Visible = false;
2017-03-15 16:17:06 -07:00
return;
}
2015-05-30 12:48:16 -07:00
2017-04-05 19:03:04 -07:00
if (deferEditorTillMouseUp)
{
return;
}
2017-03-15 16:17:06 -07:00
var selectedItem = Scene.SelectedItem;
2015-05-30 12:48:16 -07:00
selectedObjectPanel.SetActiveItem(selectedItem);
2017-03-15 16:17:06 -07:00
}
2015-05-30 12:48:16 -07:00
2017-03-15 16:17:06 -07:00
private void DrawStuffForSelectedPart(Graphics2D graphics2D)
2015-05-30 12:48:16 -07:00
{
2017-03-15 16:17:06 -07:00
if (Scene.HasSelection)
2015-04-08 15:20:10 -07:00
{
2017-03-15 16:17:06 -07:00
AxisAlignedBoundingBox selectedBounds = Scene.SelectedItem.GetAxisAlignedBoundingBox(Scene.SelectedItem.Matrix);
Vector3 boundsCenter = selectedBounds.Center;
Vector3 centerTop = new Vector3(boundsCenter.X, boundsCenter.Y, selectedBounds.maxXYZ.Z);
2014-01-29 19:09:30 -08:00
2017-07-10 14:00:27 -07:00
Vector2 centerTopScreenPosition = this.World.GetScreenPosition(centerTop);
2017-03-15 16:17:06 -07:00
centerTopScreenPosition = meshViewerWidget.TransformToParentSpace(this, centerTopScreenPosition);
2017-11-01 18:13:47 -07:00
//graphics2D.Circle(screenPosition.x, screenPosition.y, 5, Color.Cyan);
2015-04-08 15:20:10 -07:00
VertexStorage zArrow = new VertexStorage();
2017-03-15 16:17:06 -07:00
zArrow.MoveTo(-6, -2);
zArrow.curve3(0, -4);
zArrow.LineTo(6, -2);
zArrow.LineTo(0, 12);
zArrow.LineTo(-6, -2);
}
2015-04-08 15:20:10 -07:00
}
public static Regex fileNameNumberMatch = new Regex("\\(\\d+\\)", RegexOptions.Compiled);
private SelectedObjectPanel selectedObjectPanel;
internal GuiWidget selectedObjectContainer;
2017-10-19 09:04:36 -07:00
public Task SaveChanges(IProgress<ProgressStatus> progress, CancellationToken cancellationToken)
2017-03-15 16:17:06 -07:00
{
var progressStatus = new ProgressStatus()
2015-05-30 12:48:16 -07:00
{
Status = "Saving Changes"
};
progress.Report(progressStatus);
2015-09-23 13:33:14 -07:00
sceneContext.Save((progress0to1, status) =>
{
progressStatus.Status = status;
progressStatus.Progress0To1 = progress0to1;
progress.Report(progressStatus);
});
2015-11-04 17:42:07 -08:00
return Task.CompletedTask;
2015-04-08 15:20:10 -07:00
}
internal void OpenSaveAsWindow()
2015-05-30 12:48:16 -07:00
{
DialogWindow.Show(
new SaveAsPage(
async (newName, destinationContainer) =>
{
// Save the scene to disk
await ApplicationController.Instance.Tasks.Execute(this.SaveChanges);
// Save to the destination provider
if (destinationContainer != null)
{
// save this part to correct library provider
if (destinationContainer is ILibraryWritableContainer writableContainer)
{
writableContainer.Add(new[]
{
new FileSystemFileItem(sceneContext.EditContext.PartFilePath)
{
Name = newName
}
});
destinationContainer.Dispose();
}
}
}));
2015-05-30 12:48:16 -07:00
}
public Vector2 DragSelectionStartPosition { get; private set; }
public bool DragSelectionInProgress { get; private set; }
public Vector2 DragSelectionEndPosition { get; private set; }
2017-03-15 16:17:06 -07:00
internal async void SwitchStateToEditing()
{
viewControls3D.ActiveButton = ViewControls3DButtons.PartSelect;
if (Scene.HasChildren())
2017-03-15 16:17:06 -07:00
{
// This should be very fast (only building up a trace data for non-meshes, mesh should happen as background task).
2017-03-15 16:17:06 -07:00
await Task.Run(() =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// Force trace data generation
foreach (var object3D in Scene.Children)
{
object3D.TraceData();
}
});
if (this.HasBeenClosed)
{
return;
}
Scene.SelectFirstChild();
}
2018-01-02 16:45:02 -08:00
this.Invalidate();
Scene.Invalidate();
2017-03-15 16:17:06 -07:00
viewControls3D.ActiveButton = ViewControls3DButtons.PartSelect;
2017-03-15 16:17:06 -07:00
}
2018-01-21 21:07:14 -08:00
internal GuiWidget ShowOverflowMenu(PopupMenu popupMenu)
{
var meshViewer = meshViewerWidget;
popupMenu.CreateBoolMenuItem(
"Show Print Bed".Localize(),
() => sceneContext.RendererOptions.RenderBed,
(value) =>
{
meshViewer.RenderBed = value;
sceneContext.RendererOptions.RenderBed = value;
});
if (sceneContext.BuildHeight > 0)
{
popupMenu.CreateBoolMenuItem(
"Show Print Area".Localize(),
() => meshViewer.RenderBuildVolume,
(value) => meshViewer.RenderBuildVolume = value);
}
popupMenu.CreateHorizontalLine();
AddRadioButton("Shaded".Localize(), RenderTypes.Shaded, popupMenu);
AddRadioButton("Outlines".Localize(), RenderTypes.Outlines, popupMenu);
AddRadioButton("Polygons".Localize(), RenderTypes.Polygons, popupMenu);
AddRadioButton("Materials Option".Localize(), RenderTypes.Materials, popupMenu);
AddRadioButton("Overhang".Localize(), RenderTypes.Overhang, popupMenu);
popupMenu.CreateHorizontalLine();
popupMenu.AddChild(new GridOptionsPanel(this.InteractionLayer));
return popupMenu;
}
private void AddRadioButton(string label, RenderTypes renderTypes, PopupMenu popupMenu, Action action = null)
{
var radioButton = new RadioButton(label, textColor: Color.Black)
{
Checked = (meshViewerWidget.RenderType == renderTypes),
HAnchor = HAnchor.MaxFitOrStretch,
Margin = 0
};
radioButton.CheckedStateChanged += (s, e) =>
{
if (radioButton.Checked)
{
if (action == null)
{
meshViewerWidget.RenderType = renderTypes;
UserSettings.Instance.set(UserSettingsKey.defaultRenderSetting, meshViewerWidget.RenderType.ToString());
}
else
{
action.Invoke();
}
}
};
2017-08-01 17:38:07 -07:00
popupMenu.CreateMenuItem(radioButton, $"{label}-Menu");
}
protected bool autoRotating = false;
protected bool allowAutoRotate = false;
public MeshViewerWidget meshViewerWidget;
public InteractiveScene Scene { get; }
protected ViewControls3D viewControls3D { get; }
public MeshSelectInfo CurrentSelectInfo { get; } = new MeshSelectInfo();
protected IObject3D FindHitObject3D(Vector2 screenPosition, ref IntersectInfo intersectionInfo)
{
Vector2 meshViewerWidgetScreenPosition = meshViewerWidget.TransformFromParentSpace(this, screenPosition);
2017-07-10 14:00:27 -07:00
Ray ray = this.World.GetRayForLocalBounds(meshViewerWidgetScreenPosition);
intersectionInfo = Scene.TraceData().GetClosestIntersection(ray);
if (intersectionInfo != null)
{
foreach (Object3D object3D in Scene.Children)
{
if (object3D.TraceData().Contains(intersectionInfo.HitPosition))
{
CurrentSelectInfo.PlaneDownHitPos = intersectionInfo.HitPosition;
CurrentSelectInfo.LastMoveDelta = new Vector3();
return object3D;
}
}
}
return null;
}
2016-02-19 08:29:49 -08:00
}
2015-05-30 12:48:16 -07:00
2016-02-19 08:29:49 -08:00
public enum HitQuadrant { LB, LT, RB, RT }
public class MeshSelectInfo
{
public HitQuadrant HitQuadrant;
public bool DownOnPart;
public PlaneShape HitPlane;
public Vector3 LastMoveDelta;
public Vector3 PlaneDownHitPos;
2015-04-08 15:20:10 -07:00
}
}