-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathCutTool.cs
More file actions
1573 lines (1351 loc) · 62.4 KB
/
CutTool.cs
File metadata and controls
1573 lines (1351 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.EditorTools;
using UnityEngine;
using UnityEngine.ProBuilder;
using UnityEngine.ProBuilder.MeshOperations;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;
using Edge = UnityEngine.ProBuilder.Edge;
using Math = UnityEngine.ProBuilder.Math;
using UObject = UnityEngine.Object;
using RaycastHit = UnityEngine.ProBuilder.RaycastHit;
using UHandleUtility = UnityEditor.HandleUtility;
using ToolManager = UnityEditor.EditorTools.ToolManager;
using Vertex = UnityEngine.ProBuilder.Vertex;
namespace UnityEditor.ProBuilder
{
[EditorTool("Cut Tool", typeof(ProBuilderMesh), typeof(PositionToolContext))]
public class CutTool : EditorTool
{
ProBuilderMesh m_Mesh;
Texture2D m_CutCursorTexture;
Texture2D m_CutAddCursorTexture;
Texture2D m_CurrentCutCursor = null;
/// <summary>
/// Describes the different vertex types on the path.
/// </summary>
[Flags]
public enum VertexTypes
{
None = 0x0,
NewVertex = 1 << 0,
AddedOnEdge = 1 << 1,
ExistingVertex = 1 << 2,
VertexInShape = 1 << 3,
}
[Serializable]
internal struct CutVertexData
{
[SerializeField] Vector3 m_Position;
[SerializeField] Vector3 m_Normal;
[SerializeField] VertexTypes m_Types;
public Vector3 position
{
get => m_Position;
set => m_Position = value;
}
public Vector3 normal
{
get => m_Normal;
}
public VertexTypes types
{
get => m_Types;
}
public CutVertexData(Vector3 position, Vector3 normal, VertexTypes types = VertexTypes.None)
{
m_Position = position;
m_Normal = normal;
m_Types = types;
}
}
static readonly Color k_HandleColor = new Color(.8f, .8f, .8f, 1f);
static readonly Color k_HandleColorAddNewVertex = new Color(.01f, .9f, .3f, 1f);
static Color s_HandleColorAddVertexOnEdge = new Color(.3f, .01f, .9f, 1f);
static Color s_HandleColorUseExistingVertex = new Color(.01f, .5f, 1f, 1f);
static readonly Color k_HandleColorModifyVertex = new Color(1f, .75f, .0f, 1f);
const float k_HandleSize = .05f;
static readonly Color k_LineColor = new Color(0f, 55f / 255f, 1f, 1f);
static readonly Color k_InvalidLineColor = Color.red;
static readonly Color k_ConnectionsLineColor = new Color(0f, 200f / 255f, 170f / 200f, 1f);
static readonly Color k_DrawingLineColor = new Color(0.01f, .9f, 0.3f, 1f);
Color m_CurrentHandleColor = k_HandleColor;
GUIContent m_IconContent;
public override GUIContent toolbarIcon
{
get { return m_IconContent; }
}
//Handles and point placement
int m_ControlId;
bool m_PlacingPoint;
internal bool m_SnappingPoint;
bool m_ModifyingPoint; // State machine instead? //Status
int m_SelectedIndex = -2;
bool m_IsCutValid = true;
bool m_Dirty = false;
//Cut tool elements
internal Face m_TargetFace;
internal Face m_CurrentFace;
internal Vector3 m_CurrentPosition = Vector3.positiveInfinity;
internal Vector3 m_CurrentPositionNormal = Vector3.up;
internal VertexTypes m_CurrentVertexTypes = VertexTypes.None;
IList<Edge> m_SelectedEdges = null;
IList<int> m_SelectedVertices = null;
//Path composed of position that define a cut in the face
[SerializeField]
internal List<CutVertexData> m_CutPath = new List<CutVertexData>();
//Connection between the path and the mesh vertices to get a 'safe' cut
internal List<SimpleTuple<int, int>> m_MeshConnections = new List<SimpleTuple<int, int>>();
//Snapping
int m_SnapedVertexId = -1;
Edge m_SnapedEdge = Edge.Empty;
bool m_SnapToGeometry;
float m_SnappingDistance;
//Overlay fields
GUIContent m_OverlayTitle;
const string k_SnapToGeometryPrefKey = "VertexInsertion.snapToGeometry";
const string k_SnappingDistancePrefKey = "VertexInsertion.snappingDistance";
public bool isALoop
{
get
{
if (m_CutPath.Count < 3)
return false;
return Math.Approx3(m_CutPath[0].position, m_CutPath[m_CutPath.Count - 1].position);
}
}
public int connectionsToBordersCount
{
get
{
return m_CutPath.Count(data => (data.types & (VertexTypes.AddedOnEdge | VertexTypes.ExistingVertex)) != 0
&& (data.types & VertexTypes.VertexInShape) == 0);
}
}
/// <summary>
/// Update the mouse cursor depending on the tool status
/// </summary>
/// <returns>the texture to use as a cursor</returns>
Texture2D cursorTexture
{
get
{
if(m_CutPath.Count > 0)
return m_CutAddCursorTexture;
return m_CutCursorTexture;
}
}
public override bool IsAvailable()
{
return MeshSelection.selectedObjectCount == 1;
}
void OnEnable()
{
m_IconContent = new GUIContent()
{
image = IconUtility.GetIcon("Toolbar/CutTool"),
text = "Cut Tool",
tooltip = "Cut Tool"
};
s_HandleColorUseExistingVertex = Handles.selectedColor;
s_HandleColorAddVertexOnEdge = Handles.selectedColor;
m_OverlayTitle = new GUIContent("Cut Settings");
m_SnapToGeometry = EditorPrefs.GetBool( k_SnapToGeometryPrefKey, false );
m_SnappingDistance = EditorPrefs.GetFloat( k_SnappingDistancePrefKey, 0.1f );
m_CutCursorTexture = IconUtility.GetIcon("Cursors/cutCursor");
m_CutAddCursorTexture = IconUtility.GetIcon("Cursors/cutCursor-add");
m_Mesh = null;
}
public override void OnActivated()
{
if(MeshSelection.selectedObjectCount == 1)
{
m_Mesh = MeshSelection.activeMesh;
m_Mesh.ClearSelection();
m_SelectedVertices = m_Mesh.sharedVertexLookup.Keys.ToArray();
m_SelectedEdges = m_Mesh.faces.SelectMany(f => f.edges).Distinct().ToArray();
}
Undo.undoRedoPerformed += UndoRedoPerformed;
MeshSelection.objectSelectionChanged += UpdateTarget;
ProBuilderEditor.selectModeChanged += OnSelectModeChanged;
}
public override void OnWillBeDeactivated()
{
ExecuteCut(false);
Undo.undoRedoPerformed -= UndoRedoPerformed;
MeshSelection.objectSelectionChanged -= UpdateTarget;
ProBuilderEditor.selectModeChanged -= OnSelectModeChanged;
}
/// <summary>
/// Clear all data from the cut tool
/// </summary>
void Clear()
{
m_Mesh = null;
m_TargetFace = null;
m_CurrentFace = null;
m_PlacingPoint = false;
m_CurrentCutCursor = null;
m_CutPath.Clear();
m_MeshConnections.Clear();
m_SelectedVertices = null;
m_SelectedEdges = null;
EditorHandleDrawing.ClearHandles();
ProBuilderEditor.Refresh();
}
/// <summary>
/// Exit the tool and restore the previous tool
/// </summary>
void ExitTool()
{
Clear();
ToolManager.RestorePreviousTool();
}
/// <summary>
/// Undo/Redo callback: Reset and recompute lines, and update the targeted face if needed
/// </summary>
void UndoRedoPerformed()
{
if(m_CutPath.Count == 0 && m_Mesh != null)
{
m_TargetFace = null;
m_SelectedVertices = m_Mesh.sharedVertexLookup.Keys.ToArray();
m_SelectedEdges = m_Mesh.faces.SelectMany(f => f.edges).Distinct().ToArray();
}
m_SelectedIndex = -1;
m_MeshConnections.Clear();
m_Dirty = true;
}
void OnSelectModeChanged(SelectMode mode)
{
ToolManager.RestorePreviousPersistentTool();
}
/// <summary>
/// Update the mesh targeted by the tool.
/// This is used when the mesh selection is changed to refresh the tool.
/// </summary>
internal void UpdateTarget()
{
if(MeshSelection.activeMesh != m_Mesh)
{
Clear();
if(MeshSelection.selectedObjectCount == 1)
{
m_Mesh = MeshSelection.activeMesh;
m_Mesh.ClearSelection();
m_SelectedVertices = m_Mesh.sharedVertexLookup.Keys.ToArray();
m_SelectedEdges = m_Mesh.faces.SelectMany(f => f.edges).Distinct().ToArray();
if(m_CutPath.Count > 0)
{
m_CutPath.Clear();
m_MeshConnections.Clear();
}
}
}
}
/// <summary>
/// Creates a toggle for cut tool overlays.
/// </summary>
/// <param name="label">toggle title</param>
/// <param name="val">starting value for the toggle</param>
/// <returns>new toggle value</returns>
bool DoOverlayToggle(string label, bool val)
{
using(new GUILayout.HorizontalScope())
{
EditorGUILayout.LabelField(label, GUILayout.Width(225));
GUILayout.FlexibleSpace();
return EditorGUILayout.Toggle(val);
}
}
/// <summary>
/// Main GUI update for the tool, calls every secondary methods to place points, update lines and compute the cut
/// </summary>
/// <param name="window">current window calling the tool : SceneView</param>
public override void OnToolGUI( EditorWindow window )
{
// todo refactor overlays to use `Overlay` class
#pragma warning disable 618
SceneViewOverlay.Window( m_OverlayTitle, OnOverlayGUI, 0, SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle );
#pragma warning restore 618
var currentEvent = Event.current;
if (currentEvent.type == EventType.KeyDown)
HandleKeyEvent(currentEvent);
if(currentEvent.type == EventType.Repaint && m_Mesh != null)
{
DoExistingLinesGUI();
DoExistingPointsGUI();
}
if (EditorHandleUtility.SceneViewInUse(currentEvent))
return;
if(m_Mesh != null)
{
m_ControlId = GUIUtility.GetControlID(FocusType.Passive);
if(currentEvent.type == EventType.Layout)
HandleUtility.AddDefaultControl(m_ControlId);
DoPointPlacement(window);
//Refresh the cut shape if points have been added to it or removed.
if(m_Dirty)
RebuildCutShape();
if(currentEvent.type == EventType.Repaint)
{
DrawGuideLine();
DoCurrentPointsGUI();
DoVisualCues();
Cursor.SetCursor(m_CurrentCutCursor, Vector2.zero, CursorMode.Auto);
if(m_CurrentCutCursor != null)
{
Rect sceneViewRect = window.position;
sceneViewRect.x = 0;
sceneViewRect.y = 0;
SceneView.AddCursorRect(sceneViewRect, MouseCursor.CustomCursor);
}
}
}
}
bool IsCursorInSceneView(EditorWindow window)
{
if (!(window is SceneView sceneView))
return false;
var mousePos = Event.current.mousePosition;
mousePos = VisualElementExtensions.LocalToWorld(sceneView.cameraViewVisualElement, mousePos);
var ve = window.rootVisualElement.panel.Pick(mousePos);
if (ve == null)
return false;
return (ve == sceneView.cameraViewVisualElement);
}
/// <summary>
/// Overlay GUI
/// </summary>
/// <param name="target">the target of this overlay</param>
/// <param name="view">the current SceneView where to display the overlay</param>
void OnOverlayGUI(UObject target, SceneView view)
{
if(MeshSelection.selectedObjectCount != 1)
{
var rect = EditorGUILayout.GetControlRect(false, 45);
EditorGUI.HelpBox(rect, L10n.Tr("One and only one ProBuilder mesh must be selected."), MessageType.Warning);
}
GUI.enabled = MeshSelection.selectedObjectCount == 1;
m_SnapToGeometry = DoOverlayToggle(L10n.Tr("Snap to existing edges and vertices"), m_SnapToGeometry);
EditorPrefs.SetBool(k_SnapToGeometryPrefKey, m_SnapToGeometry);
if(!m_SnapToGeometry)
GUI.enabled = false;
EditorGUI.indentLevel++;
using(new GUILayout.HorizontalScope())
{
EditorGUILayout.LabelField(L10n.Tr("Snapping distance"), GUILayout.Width(200));
m_SnappingDistance = EditorGUILayout.FloatField(m_SnappingDistance);
EditorPrefs.SetFloat( k_SnappingDistancePrefKey, m_SnappingDistance);
}
EditorGUI.indentLevel--;
GUI.enabled = true;
if(MeshSelection.selectedObjectCount != 1)
GUI.enabled = false;
using(new GUILayout.HorizontalScope())
{
if(m_Mesh == null)
{
if(GUILayout.Button(EditorGUIUtility.TrTextContent("Start")))
UpdateTarget();
if(GUILayout.Button(EditorGUIUtility.TrTextContent("Quit")))
ExitTool();
}
else
{
if(GUILayout.Button(EditorGUIUtility.TrTextContent("Complete")))
ExecuteCut();
if(GUILayout.Button(EditorGUIUtility.TrTextContent("Cancel")))
ExitTool();
}
}
GUI.enabled = true;
}
/// <summary>
/// Handle key events
/// </summary>
/// <param name="evt">the current event to check</param>
void HandleKeyEvent(Event evt)
{
KeyCode key = evt.keyCode;
switch (key)
{
case KeyCode.Backspace:
{
if (m_CutPath.Count > 0)
{
UndoUtility.RecordObject(m_Mesh, "Delete Selected Points");
m_CutPath.RemoveAt(m_CutPath.Count - 1);
m_Dirty = true;
}
evt.Use();
break;
}
case KeyCode.Escape:
evt.Use();
ExitTool();
break;
case KeyCode.KeypadEnter:
case KeyCode.Return:
case KeyCode.Space:
evt.Use();
ExecuteCut();
ExitTool();
break;
}
}
/// <summary>
/// Compute the placement of the designated position, this method takes into account the snapping option
/// And check as well if the user is moving existing positions of the cut path.
/// The method is also in charge to add the new positions to the CutPath on user clicks
/// </summary>
void DoPointPlacement(EditorWindow window)
{
Event evt = Event.current;
EventType evtType = evt.type;
bool hasHitPosition = UpdateHitPosition();
//Updating visual helpers to get the right position and color to help in the placement
if (evtType == EventType.Repaint)
{
m_SnappingPoint = m_SnapToGeometry || (evt.modifiers & EventModifiers.Control) != 0;
m_ModifyingPoint = evt.shift;
if(!m_SnappingPoint &&
!m_ModifyingPoint &&
!m_PlacingPoint)
m_SelectedIndex = -1;
if (hasHitPosition && IsCursorInSceneView(window))
{
m_CurrentCutCursor = cursorTexture;
if( (m_CurrentVertexTypes & (VertexTypes.ExistingVertex | VertexTypes.VertexInShape)) != 0)
m_CurrentHandleColor = m_ModifyingPoint ? k_HandleColorModifyVertex : s_HandleColorUseExistingVertex;
else if ((m_CurrentVertexTypes & VertexTypes.AddedOnEdge) != 0)
m_CurrentHandleColor = s_HandleColorAddVertexOnEdge;
else
{
m_CurrentHandleColor = k_HandleColorAddNewVertex;
if(!m_PlacingPoint)
m_SelectedIndex = -1;
}
}
else
{
m_CurrentCutCursor = null;
m_CurrentPosition = Vector3.positiveInfinity;
m_CurrentVertexTypes = VertexTypes.None;
m_CurrentHandleColor = k_HandleColor;
}
}
//If the user is moving an existing point
if (m_PlacingPoint || m_ModifyingPoint)
{
if( evtType == EventType.MouseDown && evt.button == 0
&& HandleUtility.nearestControl == m_ControlId )
{
m_PlacingPoint = true;
}
if (evtType == EventType.MouseDrag)
{
if (hasHitPosition && m_SelectedIndex >= 0)
{
evt.Use();
CutVertexData data = m_CutPath[m_SelectedIndex];
data.position = m_CurrentPosition;
m_CutPath[m_SelectedIndex] = data;
m_Dirty = true;
}
}
if (evtType == EventType.MouseUp ||
evtType == EventType.Ignore ||
evtType == EventType.KeyDown ||
evtType == EventType.KeyUp)
{
evt.Use();
m_PlacingPoint = false;
m_SelectedIndex = -1;
}
}
//If the user is adding the current position to the cut.
else if (hasHitPosition
&& evtType == EventType.MouseDown && evt.button == 0
&& HandleUtility.nearestControl == m_ControlId)
{
if(CanAppendCurrentPointToPath())
{
AddCurrentPositionToPath();
evt.Use();
}
}
//If nothing in the current cut, then pass the mouse event to ProBuilder Editor to handle selection.
//This might disable the tool depending on the new selection.
if(m_CutPath.Count == 0
&& !hasHitPosition
&& HandleUtility.nearestControl == m_ControlId)
{
ProBuilderEditor.instance.HandleMouseEvent(SceneView.lastActiveSceneView, m_ControlId);
}
}
bool CanAppendCurrentPointToPath()
{
int polyCount = m_CutPath.Count;
if (!Math.IsNumber(m_CurrentPosition))
return false;
if (!(polyCount == 0 || m_SelectedIndex != polyCount - 1))
return false;
// duplicate points are not permitted, except the special case where placing a final point on the starting
// point finishes the cut operation.
for(int i = 1; i < polyCount; i++)
if (Math.Approx3(m_CutPath[i].position, m_CurrentPosition))
return false;
// when the existing vertex count is less than 3, don't allow the special duplicate first vertex position
return polyCount < 2 || !(polyCount < 3 && Math.Approx3(m_CutPath[0].position, m_CurrentPosition));
}
internal void AddCurrentPositionToPath(bool optimize = true)
{
UndoUtility.RecordObject(this, "Add Vertex On Path");
if(m_TargetFace == null)
{
m_TargetFace = m_CurrentFace;
var edges = m_TargetFace.edges;
m_SelectedVertices = edges.Select(e => e.a).ToArray();
m_SelectedEdges = edges.ToArray();
}
m_CutPath.Add(new CutVertexData(m_CurrentPosition, m_CurrentPositionNormal, m_CurrentVertexTypes));
m_PlacingPoint = true;
m_SelectedIndex = m_CutPath.Count - 1;
RebuildCutShape(optimize);
}
/// <summary>
/// Compute the position designated by the user in the current mesh/face taking into account snapping
/// </summary>
/// <returns>true is a valid position is computed in the mesh</returns>
bool UpdateHitPosition()
{
Event evt = Event.current;
Ray ray = UHandleUtility.GUIPointToWorldRay(evt.mousePosition);
RaycastHit pbHit;
m_CurrentFace = null;
if (UnityEngine.ProBuilder.HandleUtility.FaceRaycast(ray, m_Mesh, out pbHit))
{
UpdateCurrentPosition(m_Mesh.faces[pbHit.face], pbHit.point ,pbHit.normal);
return true;
}
return false;
}
/// <summary>
/// Add the position in the face to the cut taking into account snapping
/// </summary>
internal void UpdateCurrentPosition(Face face, Vector3 position, Vector3 normal)
{
m_CurrentPosition = position;
m_CurrentPositionNormal = normal;
m_CurrentFace = face;
m_CurrentVertexTypes = VertexTypes.None;
CheckPointInCutPath();
if (m_CurrentVertexTypes == VertexTypes.None && !m_ModifyingPoint)
CheckPointInMesh();
}
/// <summary>
/// Updates the connections between the cut path and the mesh vertices
/// </summary>
internal void UpdateMeshConnections()
{
m_MeshConnections.Clear();
if(m_CutPath.Count < 2)
return;
List<Vector3> existingVerticesInCut =
m_CutPath.Where(v => ( v.types | VertexTypes.ExistingVertex ) != 0)
.Select(v => v.position).ToList();
Vector3[] verticesPositions = m_Mesh.positionsInternal;
if(!isALoop)
{
//Connects to start and the end of the path to create a loop
float minDistToStart = Single.PositiveInfinity, minDistToStart2 = Single.PositiveInfinity;
float minDistToEnd = Single.PositiveInfinity, minDistToEnd2 = Single.PositiveInfinity;
int bestVertexIndexToStart = -1, bestVertexIndexToStart2 = -1, bestVertexIndexToEnd = -1, bestVertexIndexToEnd2 = -1;
float dist;
foreach(var vertexIndex in m_TargetFace.distinctIndexes)
{
if(existingVerticesInCut.Count > 0)
{
if(existingVerticesInCut.Exists(vert => Math.Approx3(verticesPositions[vertexIndex], vert)))
continue;
}
if(( m_CutPath[0].types & VertexTypes.NewVertex ) != 0)
{
dist = Vector3.Distance(verticesPositions[vertexIndex], m_CutPath[0].position);
if(dist < minDistToStart)
{
minDistToStart2 = minDistToStart;
bestVertexIndexToStart2 = bestVertexIndexToStart;
minDistToStart = dist;
bestVertexIndexToStart = vertexIndex;
}else if(dist < minDistToStart2)
{
minDistToStart2 = dist;
bestVertexIndexToStart2 = vertexIndex;
}
}
if(m_CutPath.Count > 1 && ( m_CutPath[m_CutPath.Count - 1].types & VertexTypes.NewVertex ) != 0)
{
dist = Vector3.Distance(verticesPositions[vertexIndex], m_CutPath[m_CutPath.Count - 1].position);
if(dist < minDistToEnd)
{
minDistToEnd2 = minDistToEnd;
bestVertexIndexToEnd2 = bestVertexIndexToEnd;
minDistToEnd = dist;
bestVertexIndexToEnd = vertexIndex;
}
else if(dist < minDistToEnd2)
{
minDistToEnd2 = dist;
bestVertexIndexToEnd2 = vertexIndex;
}
}
}
//Do not connect the 2 extremities to the same point
if(bestVertexIndexToStart == bestVertexIndexToEnd)
{
if(minDistToStart2 < minDistToEnd2)
bestVertexIndexToStart = bestVertexIndexToStart2;
else
bestVertexIndexToEnd = bestVertexIndexToEnd2;
}
if(bestVertexIndexToStart >= 0)
m_MeshConnections.Add(new SimpleTuple<int, int>(0,bestVertexIndexToStart));
if(bestVertexIndexToEnd >= 0)
m_MeshConnections.Add(new SimpleTuple<int, int>(m_CutPath.Count - 1,bestVertexIndexToEnd));
}
else if(isALoop && connectionsToBordersCount < 2)
{
//The path must have minimum connections with the face borders, find the closest vertices
foreach(var vertexIndex in m_TargetFace.distinctIndexes)
{
if(existingVerticesInCut.Count > 0)
{
if(existingVerticesInCut.Exists(vert => Math.Approx3(verticesPositions[vertexIndex], vert)))
continue;
}
int pathIndex = -1;
float minDistance = Single.MaxValue;
for(int i = 0; i < m_CutPath.Count; i++)
{
if(( m_CutPath[i].types & (VertexTypes.AddedOnEdge | VertexTypes.ExistingVertex) ) == 0)
{
float dist = Vector3.Distance(verticesPositions[vertexIndex], m_CutPath[i].position);
if(dist < minDistance)
{
minDistance = dist;
pathIndex = i;
}
}
}
if(pathIndex >= 0)
{
if(m_MeshConnections.Exists(tup => tup.item1 == pathIndex))
{
var tuple = m_MeshConnections.Find(tup => tup.item1 == pathIndex);
if(Vector3.Distance(m_CutPath[tuple.item1].position, verticesPositions[tuple.item2])
> Vector3.Distance(m_CutPath[pathIndex].position, verticesPositions[vertexIndex]))
{
m_MeshConnections.Remove(tuple);
m_MeshConnections.Add(new SimpleTuple<int, int>(pathIndex, vertexIndex));
}
}
else
m_MeshConnections.Add(new SimpleTuple<int, int>(pathIndex, vertexIndex));
}
}
m_MeshConnections.Sort((a,b) =>
(int)Mathf.Sign(Vector3.Distance(m_CutPath[a.item1].position, verticesPositions[a.item2])
- Vector3.Distance(m_CutPath[b.item1].position, verticesPositions[b.item2])));
int connectionsCount = 2 - connectionsToBordersCount;
m_MeshConnections.RemoveRange(connectionsCount,m_MeshConnections.Count - connectionsCount);
}
}
/// <summary>
/// Compute the cut result and display a notification
/// </summary>
void ExecuteCut(bool restorePrevious = true)
{
ActionResult result = DoCut();
EditorUtility.ShowNotification(result.notification);
if(restorePrevious)
ExitTool();
}
/// <summary>
/// Compute the faces resulting from the cut:
/// - First inserts points defining the cut as vertices in the face
/// - Compute the central polygon is the cut is creating a closed polygon in the face
/// - Update the rest of the face accordingly to the cut and the central polygon
/// </summary>
/// <returns>ActionResult success if it was possible to create the cut</returns>
internal ActionResult DoCut()
{
if (m_TargetFace == null || m_CutPath.Count < 2)
{
return new ActionResult(ActionResult.Status.Canceled, L10n.Tr("Not enough elements selected for a cut"));
}
if(!m_IsCutValid)
{
return new ActionResult(ActionResult.Status.Failure, L10n.Tr("The current cut overlaps itself"));
}
UndoUtility.RecordObject(m_Mesh, "Execute Cut");
List<Vertex> meshVertices = new List<Vertex>();
m_Mesh.GetVerticesInList(meshVertices);
Vertex[] formerVertices = new Vertex[m_MeshConnections.Count];
for(int i = 0; i < m_MeshConnections.Count; i++)
{
formerVertices[i] = meshVertices[m_MeshConnections[i].item2];
}
//Insert cut vertices in the mesh
List<Vertex> cutVertices = InsertVertices();
m_Mesh.GetVerticesInList(meshVertices);
//Retrieve indexes of the cut points in the mesh vertices
int[] cutIndexes = cutVertices.Select(vert => meshVertices.IndexOf(vert)).ToArray();
//Update mesh connections with new indexes
for(int i = 0; i<m_MeshConnections.Count; i++)
{
SimpleTuple<int, int> connection = m_MeshConnections[i];
connection.item1 = meshVertices.IndexOf(cutVertices[connection.item1]);
connection.item2 = meshVertices.IndexOf(formerVertices[i]);
m_MeshConnections[i] = connection;
}
List<Face> newFaces = new List<Face>();
// If the cut defines a loop in the face, create the polygon corresponding to that loop
if (isALoop)
{
Face f = m_Mesh.CreatePolygon(cutIndexes, false);
f.submeshIndex = m_TargetFace.submeshIndex;
if(f == null)
return new ActionResult(ActionResult.Status.Failure, L10n.Tr("Cut Shape is not valid"));
Vector3 nrm = Math.Normal(m_Mesh, f);
Vector3 targetNrm = Math.Normal(m_Mesh, m_TargetFace);
// If the shape is define in the wrong orientation compared to the former face, reverse it
if(Vector3.Dot(nrm,targetNrm) < 0f)
f.Reverse();
newFaces.Add(f);
}
//Compute the rest of the new faces (faces outside of the loop or division of the original face)
List<Face> faces = ComputeNewFaces(m_TargetFace, cutIndexes);
if(!isALoop)
newFaces.AddRange(faces);
//Remove inserted vertices only if they were inserted for the process
List<int> verticesIndexesToDelete = new List<int>();
for(int i = 0; i < m_CutPath.Count; i++)
{
if(( m_CutPath[i].types & VertexTypes.NewVertex ) != 0
&& ( m_CutPath[i].types & VertexTypes.VertexInShape ) == 0)
verticesIndexesToDelete.Add(cutIndexes[i]);
}
m_Mesh.DeleteVertices(verticesIndexesToDelete);
//Delete former face
m_Mesh.DeleteFace(m_TargetFace);
m_Mesh.ToMesh();
m_Mesh.Refresh();
m_Mesh.Optimize();
//Update mesh selection after the cut has been performed
MeshSelection.ClearElementSelection();
m_Mesh.SetSelectedFaces(newFaces);
ProBuilderEditor.Refresh();
Clear();
return new ActionResult(ActionResult.Status.Success, L10n.Tr("Cut executed"));
}
/// <summary>
/// Based on the new vertices inserted in the face, this method computes the different faces
/// created between the cut and the original face (external to the cut if it makes a loop)
///
/// The faces are created by parsing the edges that defines the border of the original face. Is an edge ends on a
/// vertex that is part of the cut, or belongs to a connection between the cut and the face,
/// we close the defined polygon using the cut (though ComputeFaceClosure method) and create a face out of this polygon
/// </summary>
/// <param name="face">Original face to modify</param>
/// <param name="cutVertexIndexes">Indexes of the new vertices inserted in the face</param>
/// <returns>The list of polygons to create (defined by their vertices indexes)</returns>
List<Face> ComputeNewFaces(Face face, IList<int> cutVertexIndexes)
{
List<Face> newFaces = new List<Face>();
//Get Vertices from the mesh
Dictionary<int, int> sharedToUnique = m_Mesh.sharedVertexLookup;
var cutVertexSharedIndexes = cutVertexIndexes.Select(ind => sharedToUnique[ind]).ToList();
//Parse peripheral edges to unique id and find a common point between the peripheral edges and the cut
var peripheralEdges = WingedEdge.SortEdgesByAdjacency(face);
var peripheralEdgesUnique = new List<Edge>();
int startIndex = -1;
for (int i = 0; i < peripheralEdges.Count; i++)
{
Edge eShared = peripheralEdges[i];
Edge eUnique = new Edge(sharedToUnique[eShared.a], sharedToUnique[eShared.b]);
peripheralEdgesUnique.Add(eUnique);
if (startIndex == -1 && ( cutVertexSharedIndexes.Contains(eUnique.a)
|| m_MeshConnections.Exists(tup => sharedToUnique[tup.item2] == eUnique.a)))
startIndex = i;
}
//Create a polygon for each cut reaching the mesh edges
List<Face> facesToDelete = new List<Face>();
List<int> polygon = new List<int>();
for (int i = startIndex; i <= peripheralEdgesUnique.Count + startIndex; i++)
{
polygon.Add(peripheralEdges[i % peripheralEdgesUnique.Count].a);
Edge e = peripheralEdgesUnique[i % peripheralEdgesUnique.Count];
if(polygon.Count > 1)
{
int index = -1;
if(cutVertexSharedIndexes.Contains(e.a)) // get next vertex
{
index = e.a;
}
else if(m_MeshConnections.Exists(tup => sharedToUnique[tup.item2] == e.a))
{
SimpleTuple<int, int> connection = m_MeshConnections.Find(tup => sharedToUnique[tup.item2] == e.a);
polygon.Add(connection.item1);
index = sharedToUnique[connection.item1];
}
if(index >= 0)
{
// In the case of only 2 distinct, a face should not be added.
if (polygon.Count != 2)
{
List<Face> toDelete;
Face newFace = ComputeFaceClosure(polygon, index, cutVertexSharedIndexes, out toDelete);
newFace.submeshIndex = m_TargetFace.submeshIndex;
newFaces.Add(newFace);
facesToDelete.AddRange(toDelete);
}
//Start a new polygon
polygon = new List<int>();
polygon.Add(peripheralEdges[i % peripheralEdgesUnique.Count].a);
}
}
}
polygon.Clear();
m_Mesh.DeleteFaces(facesToDelete);
return newFaces;
}
/// <summary>
/// The method computes all the possible faces that can be made starting by the vertices in polygonStart and ending with the cut
/// This method creates faces that are not the final one and that must be deleted at the end. These invalid faces are returned in facesToDelete
/// The only valid face is returned from this method. From all defined faces, the valid face is the one with the smaller area
/// (otherwise it means it covers another face of the mesh).
/// </summary>
/// <param name="polygonStart">Indexes of the first vertices of the new Face to define, these vertices are coming from the original face only</param>
/// <param name="currentIndex">Current vertex index in the cut</param>
/// <param name="cutIndexes">Indexes of the vertices defining the cut</param>
/// <param name="cutIndexes">out : extra faces created by this method that will need to be deleted after
/// (these faces cannot be deleted directly as it will break the m_MeshConnections by deleting some indexes before the end of the algorithm)
/// <returns>the valid face that need to be kept in the resulting mesh</returns>
Face ComputeFaceClosure( List<int> polygonStart, int currentIndex, List<int> cutIndexes, out List<Face> facesToDelete)
{
List<Vertex> meshVertices = new List<Vertex>();
IList<SharedVertex> uniqueIdToVertexIndex = m_Mesh.sharedVertices;
Dictionary<int, int> sharedToUnique = m_Mesh.sharedVertexLookup;
int polygonFirstVertex = polygonStart[0];
int startIndex = cutIndexes.IndexOf(currentIndex);
SimpleTuple<int,int> connection = m_MeshConnections.Find(tup => sharedToUnique[tup.item2] == sharedToUnique[polygonFirstVertex]);
List<List<int>> closureCandidates = new List<List<int>>();
//Go through the cut in reverse direction
int index;