mattercontrol/original/MatterControlLib/DesignTools/Operations/TwistObject3D.cs

377 lines
13 KiB
C#
Raw Permalink Normal View History

2019-05-09 08:38:13 -07:00
/*
Copyright (c) 2018, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
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.
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.
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
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.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.DataConverters3D;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DesignTools.Operations;
using MatterHackers.MatterControl.PartPreviewWindow;
using MatterHackers.PolygonMesh;
2019-06-02 22:29:54 -07:00
using MatterHackers.RenderOpenGl;
2019-05-09 08:38:13 -07:00
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;
using Newtonsoft.Json;
namespace MatterHackers.MatterControl.DesignTools
{
2023-10-24 17:53:43 -07:00
public class TwistObject3D : OperationSourceContainerObject3D, IPropertyGridModifier, IEditorDraw
2019-05-09 08:38:13 -07:00
{
public TwistObject3D()
{
Name = "Twist".Localize();
}
public enum RotationTypes
{
Angle,
Distance
}
[EnumDisplay(Mode = EnumDisplayAttribute.PresentationMode.Tabs)]
public RotationTypes RotationType { get; set; } = RotationTypes.Angle;
[MaxDecimalPlaces(2)]
2020-05-23 11:45:15 -07:00
[Description("The angle to rotate the top of the part")]
2021-09-23 20:49:47 -07:00
[Slider(3, 360, snapDistance: 1)]
public DoubleOrExpression Angle { get; set; } = 45;
2020-05-23 11:45:15 -07:00
[MaxDecimalPlaces(2)]
[Description("The distance along the circumference to rotate the top in mm")]
2021-09-23 20:49:47 -07:00
[Slider(1, 50, Easing.EaseType.Quadratic, snapDistance: 1)]
public DoubleOrExpression RotationDistance { get; set; } = 10;
2020-05-23 11:45:15 -07:00
[Description("Specifies the number of vertical cuts required to ensure the part can be twist well.")]
2022-02-22 11:49:37 -08:00
[Slider(0, 50, snapDistance: 1)]
2021-09-23 20:49:47 -07:00
public IntOrExpression RotationSlices { get; set; } = 5;
2020-05-23 11:45:15 -07:00
[Description("The source part is specifying a preferred radius. You can turn this off to set a specific radius.")]
public bool EditRadius { get; set; } = false;
[Description("The radius described by the source part or implied by the geometry.")]
[ReadOnly(true)]
public double PreferedRadius { get; set; } = 0;
2019-05-09 08:38:13 -07:00
[MaxDecimalPlaces(2)]
2020-05-23 11:45:15 -07:00
[Description("Specify the radius to use when calculating the circumference.")]
2021-09-23 20:49:47 -07:00
public DoubleOrExpression OverrideRadius { get; set; } = .01;
2019-05-09 08:38:13 -07:00
[DisplayName("Twist Right")]
public bool TwistCw { get; set; } = true;
2020-05-23 11:45:15 -07:00
[Description("Enable advanced features like specifying when the twist starts and stops on the part.")]
public bool Advanced { get; set; } = false;
[ReadOnly(true)]
[DisplayName("")] // clear the display name so this text will be the full width of the editor
2020-05-23 11:45:15 -07:00
public string EasyModeMessage { get; set; } = "You can switch to Advanced mode to get more twist options.";
[Description("Allows for the repositioning of the rotation origin")]
public Vector2 RotationOffset { get; set; }
public Easing.EaseType EasingType { get; set; } = Easing.EaseType.Linear;
2020-05-23 11:45:15 -07:00
[EnumDisplay(Mode = EnumDisplayAttribute.PresentationMode.Buttons)]
public Easing.EaseOption EasingOption { get; set; } = Easing.EaseOption.InOut;
2020-05-23 11:45:15 -07:00
[Description("The percentage up from the bottom to end the twist")]
2021-09-23 20:49:47 -07:00
[Slider(0, 100, Easing.EaseType.Quadratic, snapDistance: 1)]
public DoubleOrExpression EndHeightPercent { get; set; } = 100;
[Description("The percentage up from the bottom to start the twist")]
[Slider(0, 100, Easing.EaseType.Quadratic, snapDistance: 1)]
public DoubleOrExpression StartHeightPercent { get; set; } = 0;
2020-05-23 11:45:15 -07:00
public IRadiusProvider RadiusProvider
{
get
{
if (this.SourceContainer.Children.Count == 1
&& this.SourceContainer.Children.First() is IRadiusProvider radiusProvider)
{
return radiusProvider;
}
return null;
}
}
public void DrawEditor(Object3DControlsLayer layer, DrawEventArgs e)
2019-05-09 08:38:13 -07:00
{
var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox();
var rotationCenter = SourceContainer.GetSmallestEnclosingCircleAlongZ().Center + RotationOffset;
var center = new Vector3(rotationCenter.X, rotationCenter.Y, sourceAabb.Center.Z);
2019-05-09 08:38:13 -07:00
// render the top and bottom rings
layer.World.RenderCylinderOutline(this.WorldMatrix(), center, 1, sourceAabb.ZSize, 15, Color.Red, Color.Red, 5);
2019-05-09 08:38:13 -07:00
// turn the lighting back on
GL.Enable(EnableCap.Lighting);
}
public AxisAlignedBoundingBox GetEditorWorldspaceAABB(Object3DControlsLayer layer)
{
var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox();
var rotationCenter = SourceContainer.GetSmallestEnclosingCircleAlongZ().Center + RotationOffset;
var center = new Vector3(rotationCenter.X, rotationCenter.Y, sourceAabb.Center.Z);
return AxisAlignedBoundingBox.CenteredBox(new Vector3(1, 1, sourceAabb.ZSize), center).NewTransformed(this.WorldMatrix());
}
2019-05-09 08:38:13 -07:00
public override Task Rebuild()
{
this.DebugDepth("Rebuild");
bool valuesChanged = false;
2021-09-23 20:49:47 -07:00
var aabb = this.GetAxisAlignedBoundingBox();
2019-05-09 08:38:13 -07:00
2021-09-23 20:49:47 -07:00
var angle = Angle.ClampIfNotCalculated(this, 0, 10000, ref valuesChanged);
var rotationDistance = RotationDistance.ClampIfNotCalculated(this, 0, 10000, ref valuesChanged);
2022-02-22 11:49:37 -08:00
var rotationSlices = RotationSlices.ClampIfNotCalculated(this, 0, 300, ref valuesChanged);
2021-09-23 20:49:47 -07:00
var endHeightPercent = EndHeightPercent.ClampIfNotCalculated(this, 0, 100, ref valuesChanged);
endHeightPercent = EndHeightPercent.ClampIfNotCalculated(this, 1, 100, ref valuesChanged);
var startHeightPercent = StartHeightPercent.ClampIfNotCalculated(this, 0, endHeightPercent - 1, ref valuesChanged);
startHeightPercent = Math.Min(endHeightPercent - 1, startHeightPercent);
var overrideRadius = OverrideRadius.ClampIfNotCalculated(this, 1, Math.Max(aabb.XSize, aabb.YSize), ref valuesChanged);
2020-05-23 11:45:15 -07:00
2019-05-09 08:38:13 -07:00
var rebuildLocks = this.RebuilLockAll();
return ApplicationController.Instance.Tasks.Execute(
"Twist".Localize(),
null,
(reporter, cancellationToken) =>
{
var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox();
var bottom = sourceAabb.MinXYZ.Z;
2021-09-23 20:49:47 -07:00
var top = sourceAabb.ZSize * endHeightPercent / 100.0;
var size = sourceAabb.ZSize;
if (Advanced)
{
2021-09-23 20:49:47 -07:00
bottom += sourceAabb.ZSize * startHeightPercent / 100.0;
size = top - bottom;
}
2021-09-23 20:49:47 -07:00
double numberOfCuts = rotationSlices;
double cutSize = size / numberOfCuts;
2019-05-09 08:38:13 -07:00
var cuts = new List<double>();
for (int i = 0; i < numberOfCuts + 1; i++)
2019-05-09 08:38:13 -07:00
{
var ratio = i / numberOfCuts;
if (Advanced)
{
var goal = ratio;
var current = .5;
var next = .25;
// look for an x value that equals the goal
for (int j = 0; j < 64; j++)
{
var xAtY = Easing.Calculate(EasingType, EasingOption, current);
if (xAtY < goal)
{
current += next;
}
else if (xAtY > goal)
{
current -= next;
}
next *= .5;
}
ratio = current;
}
cuts.Add(bottom - cutSize + (size * ratio));
2019-05-09 08:38:13 -07:00
}
// get the rotation from the center of the circumscribed circle of the convex hull
var enclosingCircle = SourceContainer.GetSmallestEnclosingCircleAlongZ();
var rotationCenter = enclosingCircle.Center + RotationOffset;
2019-05-09 08:38:13 -07:00
var twistedChildren = new List<IObject3D>();
foreach (var sourceItem in SourceContainer.VisibleMeshes())
{
var originalMesh = sourceItem.Mesh;
2023-03-10 17:15:55 -08:00
var status = "Copy Mesh".Localize();
reporter?.Invoke(0, status);
2019-05-09 08:38:13 -07:00
var transformedMesh = originalMesh.Copy(CancellationToken.None);
var itemMatrix = sourceItem.WorldMatrix(SourceContainer);
// transform into this space
transformedMesh.Transform(itemMatrix);
2023-03-10 17:15:55 -08:00
status = "Split Mesh".Localize();
reporter?.Invoke(0, status);
2019-05-11 14:54:01 -07:00
2019-05-09 08:38:13 -07:00
// split the mesh along the z axis
transformedMesh.SplitOnPlanes(Vector3.UnitZ, cuts, cutSize / 8);
for (int i = 0; i < transformedMesh.Vertices.Count; i++)
{
var position = transformedMesh.Vertices[i];
var ratio = (position.Z - bottom) / size;
if (Advanced)
{
if (position.Z < bottom)
{
ratio = 0;
}
else if (position.Z > top)
{
ratio = 1;
}
else
{
ratio = (position.Z - bottom) / size;
ratio = Easing.Calculate(EasingType, EasingOption, ratio);
}
}
2021-09-23 20:49:47 -07:00
var angleToRotate = ratio * angle / 360.0 * MathHelper.Tau;
if (RotationType == RotationTypes.Distance)
{
2020-05-23 11:45:15 -07:00
IRadiusProvider radiusProvider = RadiusProvider;
// start off with assuming we want to set the radius
2021-09-23 20:49:47 -07:00
var radius = overrideRadius;
2020-05-23 11:45:15 -07:00
if (radiusProvider != null && !this.EditRadius)
{
2020-05-23 11:45:15 -07:00
// have a radius provider and not wanting to edit
radius = radiusProvider.Radius;
}
2020-05-23 11:45:15 -07:00
else if (!this.EditRadius)
{
2020-05-23 11:45:15 -07:00
// not wanting to edit
radius = enclosingCircle.Radius;
}
2020-05-23 11:45:15 -07:00
if (this.PreferedRadius != radius)
{
this.PreferedRadius = radius;
2021-09-23 20:49:47 -07:00
this.OverrideRadius.ClampIfNotCalculated(this, radius, radius, ref valuesChanged);
2020-05-23 11:45:15 -07:00
UiThread.RunOnIdle(() => Invalidate(InvalidateType.DisplayValues));
}
2021-09-23 20:49:47 -07:00
angleToRotate = ratio * (rotationDistance / radius);
}
2019-05-09 08:38:13 -07:00
if (!TwistCw)
{
angleToRotate = -angleToRotate;
}
var positionXy = new Vector2(position) - rotationCenter;
positionXy.Rotate(angleToRotate);
positionXy += rotationCenter;
transformedMesh.Vertices[i] = new Vector3Float(positionXy.X, positionXy.Y, position.Z);
}
// transform back into item local space
transformedMesh.Transform(itemMatrix.Inverted);
//transformedMesh.MergeVertices(.1);
2019-05-09 08:38:13 -07:00
transformedMesh.CalculateNormals();
var twistedChild = new Object3D()
{
Mesh = transformedMesh
};
2020-05-23 11:45:15 -07:00
twistedChild.CopyWorldProperties(sourceItem, SourceContainer, Object3DPropertyFlags.All, false);
2019-05-09 08:38:13 -07:00
twistedChild.Visible = true;
twistedChildren.Add(twistedChild);
}
RemoveAllButSource();
this.SourceContainer.Visible = false;
this.Children.Modify((list) =>
{
list.AddRange(twistedChildren);
});
2022-05-02 07:35:09 -07:00
ApplyHoles(reporter, cancellationToken.Token);
UiThread.RunOnIdle(() =>
{
rebuildLocks.Dispose();
2021-12-05 22:01:50 -08:00
this.CancelAllParentBuilding();
Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
2021-09-23 20:49:47 -07:00
Invalidate(InvalidateType.DisplayValues);
});
2019-05-09 08:38:13 -07:00
return Task.CompletedTask;
});
}
private Dictionary<string, bool> changeSet = new Dictionary<string, bool>();
public void UpdateControls(PublicPropertyChange change)
{
changeSet.Clear();
changeSet.Add(nameof(RotationDistance), RotationType == RotationTypes.Distance);
changeSet.Add(nameof(Angle), RotationType == RotationTypes.Angle);
changeSet.Add(nameof(RotationOffset), Advanced);
changeSet.Add(nameof(StartHeightPercent), Advanced);
changeSet.Add(nameof(EasingOption), Advanced && EasingType != Easing.EaseType.Linear);
changeSet.Add(nameof(EasingType), Advanced);
changeSet.Add(nameof(EndHeightPercent), Advanced);
2020-05-23 11:45:15 -07:00
changeSet.Add(nameof(EasyModeMessage), !Advanced);
2020-05-24 08:34:06 -07:00
changeSet.Add(nameof(PreferedRadius), RadiusProvider != null && !this.EditRadius && RotationType == RotationTypes.Distance);
2020-05-23 11:45:15 -07:00
changeSet.Add(nameof(OverrideRadius), (RadiusProvider == null || this.EditRadius) && RotationType == RotationTypes.Distance);
changeSet.Add(nameof(EditRadius), RadiusProvider != null && RotationType == RotationTypes.Distance);
// first turn on all the settings we want to see
foreach (var kvp in changeSet.Where(c => c.Value))
{
change.SetRowVisible(kvp.Key, () => kvp.Value);
}
// then turn off all the settings we want to hide
foreach (var kvp in changeSet.Where(c => !c.Value))
{
change.SetRowVisible(kvp.Key, () => kvp.Value);
}
}
2019-05-09 08:38:13 -07:00
}
}