-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathBoundsControl.cs
More file actions
926 lines (786 loc) · 37.4 KB
/
BoundsControl.cs
File metadata and controls
926 lines (786 loc) · 37.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
// Copyright (c) Mixed Reality Toolkit Contributors
// Licensed under the BSD 3-Clause
using System;
using Unity.Profiling;
using Unity.XR.CoreUtils.GUI;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
using static MixedReality.Toolkit.SpatialManipulation.ObjectManipulator;
namespace MixedReality.Toolkit.SpatialManipulation
{
/// <summary>
/// A <see cref="BoundsControl"/> creates a bounds visual around the specified object.
/// </summary>
/// <remarks>
/// Any <see cref="BoundsHandleInteractable"/> component on the bounds game object will forward their manipulation events
/// to this script, allowing for handle-based manipulation of the target object.
/// </remarks>
[RequireComponent(typeof(ConstraintManager))]
[AddComponentMenu("MRTK/Spatial Manipulation/Bounds Control")]
public class BoundsControl : MonoBehaviour
{
#region Serialized Fields/Properties
[Header("Bounds")]
[SerializeField]
[Tooltip("This prefab will be instantiated as the bounds visuals. Consider making your own prefab to modify how the visuals are drawn.")]
private GameObject boundsVisualsPrefab;
/// <summary>
/// This prefab will be instantiated as the bounds visuals.
/// </summary>
/// <remarks>
/// Consider making your own prefab to modify how the visuals are drawn.
/// </remarks>
public GameObject BoundsVisualsPrefab
{
get => boundsVisualsPrefab;
set
{
if (value != boundsVisualsPrefab)
{
boundsVisualsPrefab = value;
CreateBoundsVisuals();
}
}
}
[SerializeField]
[Tooltip("How should the bounds be automatically calculated?")]
private BoundsCalculator.BoundsCalculationMethod boundsCalculationMethod = BoundsCalculator.BoundsCalculationMethod.RendererOverCollider;
/// <summary>
/// How should the bounds be automatically calculated?
/// </summary>
public BoundsCalculator.BoundsCalculationMethod BoundsCalculationMethod
{
get => boundsCalculationMethod;
set
{
boundsCalculationMethod = value;
needsBoundsRecompute = ComputeBounds();
}
}
[SerializeField]
[Tooltip("Should BoundsControl include inactive objects when it traverses the hierarchy to calculate bounds?")]
private bool includeInactiveObjects = false;
/// <summary>
/// Should BoundsControl include inactive objects when it traverses the hierarchy to calculate bounds?
/// </summary>
public bool IncludeInactiveObjects
{
get => includeInactiveObjects;
set
{
if (includeInactiveObjects != value)
{
includeInactiveObjects = value;
needsBoundsRecompute = ComputeBounds();
}
}
}
[SerializeField]
[Tooltip("Should BoundsControl use a specific object to calculate bounds, instead of the entire hierarchy?")]
private bool overrideBounds = false;
/// <summary>
/// Should BoundsControl use a specific object to calculate bounds, instead of the entire hierarchy?
/// </summary>
public bool OverrideBounds
{
get => overrideBounds;
set
{
if (overrideBounds != value)
{
overrideBounds = value;
needsBoundsRecompute = ComputeBounds();
}
}
}
[SerializeField, DrawIf("overrideBounds")]
[Tooltip("The bounds will be calculated from this object and this object only, instead of the entire hierarchy.")]
private Transform boundsOverride;
/// <summary>
/// The bounds will be calculated from this object and this object only, instead of the entire hierarchy.
/// </summary>
public Transform BoundsOverride
{
get => boundsOverride;
set
{
if (value != boundsOverride)
{
boundsOverride = value;
needsBoundsRecompute = true;
}
}
}
[SerializeField]
[Tooltip("How should this BoundsControl flatten?")]
private FlattenMode flattenMode = FlattenMode.Auto;
/// <summary>
/// How should this BoundsControl flatten?
/// </summary>
public FlattenMode FlattenMode
{
get => flattenMode;
set
{
flattenMode = value;
needsBoundsRecompute = true;
}
}
[SerializeField]
[Tooltip("The bounds will be padded around the extent of the object by this amount, in world units.")]
private float boundsPadding = 0.01f;
/// <summary>
/// The bounds will be padded around the extent of the object by this amount, in world units.
/// </summary>
public float BoundsPadding
{
get => boundsPadding;
set
{
boundsPadding = value;
needsBoundsRecompute = true;
}
}
[Header("Interactable Connection")]
[SerializeField]
[Tooltip("Reference to the interactable (such as ObjectManipulator) in charge of the wrapped object")]
private StatefulInteractable interactable;
/// <summary>
/// Reference to the interactable (such as ObjectManipulator) in charge of the wrapped object
/// </summary>
public StatefulInteractable Interactable
{
get => interactable;
set
{
if (interactable != value)
{
UnsubscribeFromInteractable();
interactable = value;
SubscribeToInteractable();
}
}
}
[SerializeField]
[Tooltip("Toggle the handles when the interactable is selected, not moved, and then released.")]
private bool toggleHandlesOnClick = true;
/// <summary>
/// Toggle the handles when the interactable is selected, not moved, and then released.
/// </summary>
public bool ToggleHandlesOnClick
{
get => toggleHandlesOnClick;
set => toggleHandlesOnClick = value;
}
[SerializeField, DrawIf("toggleHandlesOnClick")]
[Tooltip("During a selection of the associated interactable, if the interactable is dragged/moved a smaller distance than this value, the handles will be activated/deactivated.")]
private float dragToggleThreshold = 0.02f;
/// <summary>
/// During a selection of the associated interactable, if the interactable is
/// dragged/moved a smaller distance than this value, the handles will be activated/deactivated.
/// </summary>
public float DragToggleThreshold { get => dragToggleThreshold; set => dragToggleThreshold = value; }
[Header("Manipulation")]
[SerializeField]
[Tooltip("The transform to be manipulated.")]
private Transform target;
/// <summary>
/// The transform to be manipulated. If null, it is automatically set
/// to the transform that this BoundsControl is on.
/// </summary>
public Transform Target
{
get
{
if (target == null)
{
target = transform;
}
return target;
}
set
{
target = value;
}
}
[SerializeField]
[Tooltip("Should any handles be visible?")]
private bool handlesActive = false;
/// <summary>
/// Should any handles be visible?
/// </summary>
public bool HandlesActive
{
get => handlesActive;
set => handlesActive = value;
}
[SerializeField]
[Tooltip("Which type of handles should be visible?")]
private HandleType enabledHandles = HandleType.Rotation | HandleType.Scale;
/// <summary>
/// Which type of handles should be visible?
/// </summary>
public HandleType EnabledHandles
{
get => enabledHandles;
set => enabledHandles = value;
}
[SerializeField, FlagsProperty]
[Tooltip("Specifies whether the rotate handles will rotate the object around its origin, or the center of its calculated bounds.")]
private RotateAnchorType rotateAnchor = RotateAnchorType.BoundsCenter;
/// <summary>
/// Specifies whether the rotate handles will rotate the object around its origin, or the center of its calculated bounds.
/// </summary>
public RotateAnchorType RotateAnchor
{
get => rotateAnchor;
set
{
if (rotateAnchor != value)
{
rotateAnchor = value;
}
}
}
[SerializeField, FlagsProperty]
[Tooltip("Specifies whether the scale handles will rotate the object around their opposing corner, or the center of its calculated bounds.")]
private ScaleAnchorType scaleAnchor = ScaleAnchorType.OppositeCorner;
/// <summary>
/// Specifies whether the scale handles will rotate the scale around the opposing corner, or the center of its calculated bounds.
/// </summary>
public ScaleAnchorType ScaleAnchor
{
get => scaleAnchor;
set
{
if (scaleAnchor != value)
{
scaleAnchor = value;
}
}
}
[SerializeField]
[Tooltip("Scale mode that is applied when interacting with scale handles - default is uniform scaling. Non uniform mode scales the control according to hand / controller movement in space.")]
private HandleScaleMode scaleBehavior = HandleScaleMode.Uniform;
/// <summary>
/// Scale behavior that is applied when interacting with scale handles - default is uniform scaling. Non uniform mode scales the control according to hand / controller movement in space.
/// </summary>
public HandleScaleMode ScaleBehavior
{
get => scaleBehavior;
set
{
if (scaleBehavior != value)
{
scaleBehavior = value;
}
}
}
[Header("Modifiers")]
[SerializeField]
[Tooltip("Check to enable frame-rate independent smoothing.")]
private bool smoothingActive = true;
/// <summary>
/// Check to enable frame-rate independent smoothing.
/// </summary>
public bool SmoothingActive
{
get => smoothingActive;
set => smoothingActive = value;
}
[SerializeField, DrawIf("smoothingActive")]
[Tooltip("Enter amount representing amount of smoothing to apply to the rotation. Smoothing of 0 means no smoothing. Max value means no change to value.")]
private float rotateLerpTime = 0.00001f;
/// <summary>
/// Enter amount representing amount of smoothing to apply to the rotation. Smoothing of 0 means no smoothing. Max value means no change to value.
/// </summary>
public float RotateLerpTime
{
get => rotateLerpTime;
set => rotateLerpTime = value;
}
[SerializeField, DrawIf("smoothingActive")]
[Tooltip("Enter amount representing amount of smoothing to apply to the scale. Smoothing of 0 means no smoothing. Max value means no change to value.")]
private float scaleLerpTime = 0.00001f;
/// <summary>
/// Enter amount representing amount of smoothing to apply to the scale. Smoothing of 0 means no smoothing. Max value means no change to value.
/// </summary>
public float ScaleLerpTime
{
get => scaleLerpTime;
set => scaleLerpTime = value;
}
[SerializeField, DrawIf("smoothingActive")]
[Tooltip("Enter amount representing amount of smoothing to apply to the translation. " +
"Smoothing of 0 means no smoothing. Max value means no change to value.")]
private float translateLerpTime = 0.00001f;
/// <summary>
/// Enter amount representing amount of smoothing to apply to the translation. Smoothing of 0
/// means no smoothing. Max value means no change to value.
/// </summary>
public float TranslateLerpTime
{
get => translateLerpTime;
set => translateLerpTime = value;
}
[SerializeField]
[Tooltip("Enable or disable constraint support of this component. When enabled, transform " +
"changes will be post processed by the linked constraint manager.")]
private bool enableConstraints = true;
/// <summary>
/// Enable or disable constraint support of this component. When enabled, transform
/// changes will be post processed by the linked constraint manager.
/// </summary>
public bool EnableConstraints
{
get => enableConstraints;
set => enableConstraints = value;
}
[SerializeField, DrawIf("enableConstraints")]
[Tooltip("Constraint manager slot to enable constraints when manipulating the object.")]
private ConstraintManager constraintsManager;
/// <summary>
/// Constraint manager slot to enable constraints when manipulating the object.
/// </summary>
public ConstraintManager ConstraintsManager
{
get => constraintsManager;
set => constraintsManager = value;
}
[SerializeField]
[Tooltip("The concrete types of ManipulationLogic<T> to use for manipulations.")]
private LogicType manipulationLogicTypes = new LogicType
{
moveLogicType = typeof(BoundsControlMoveLogic),
rotateLogicType = typeof(BoundsControlRotateLogic),
scaleLogicType = typeof(BoundsControlScaleLogic)
};
/// <summary>
/// The concrete types of <see cref="ManipulationLogicImplementations<T>"/> to use for manipulations.
/// </summary>
/// <remarks>
/// Setting this field at runtime can be expensive (reflection) and interrupt/break
/// currently occurring manipulations. Use with caution. Best used at startup or when
/// instantiating ObjectManipulators from code.
/// </remarks>
public LogicType ManipulationLogicTypes
{
get => manipulationLogicTypes;
set
{
// Re-instantiating manip logics is expensive and can interrupt ongoing interactions.
manipulationLogicTypes = value;
InstantiateManipulationLogic();
}
}
[Header("Events")]
[SerializeField]
private SelectEnterEvent manipulationStarted = new SelectEnterEvent();
/// <summary>
/// Fired when manipulation on a handle begins.
/// </summary>
public SelectEnterEvent ManipulationStarted
{
get => manipulationStarted;
set => manipulationStarted = value;
}
[SerializeField]
private SelectExitEvent manipulationEnded = new SelectExitEvent();
/// <summary>
/// Fired when manipulation on a handle ends.
/// </summary>
public SelectExitEvent ManipulationEnded
{
get => manipulationEnded;
set => manipulationEnded = value;
}
#endregion Serialized Fields/Properties
/// <summary>
/// Is this BoundsControl currently being manipulated?
/// </summary>
public bool IsManipulated => currentHandle != null;
/// <summary>
/// Is this BoundsControl actively flattening along its thinnest axis?
/// </summary>
public bool IsFlat { get; protected set; }
private Bounds currentBounds = new Bounds();
/// <summary>
/// Accessor that can be used to retrieve most recently calculated bounds for the bounds control cube
/// </summary>
public Bounds CurrentBounds => currentBounds;
// The box visuals GameObject instantiated at Awake.
private GameObject boxInstance;
// Used to determine whether the associated interactable was moved between select/deselect,
// which drives whether the handles get toggled on/off. If the interactable was moved less than a
// certain threshold, we toggle the handles on/off. If the interactable was moved further than the
// threshold, we don't toggle the handles (as it was probably an intentional ObjectManipulation!)
private Vector3 startMovePosition;
// The handle that is currently being manipulated.
private BoundsHandleInteractable currentHandle;
// A unit vector, relative to the transform target, that represents the flattening axis.
private Vector3 flattenVector;
// The transform of the object when the manipulation was initiated.
private MixedRealityTransform initialTransformOnGrabStart;
// The corner opposite from the current scale handle (if a scale handle is being selected)
private Vector3 oppositeCorner;
/// <summary>
/// Accessor for the corner opposite from the current scale handle (if a scale handle is being selected)
/// </summary>
public Vector3 OppositeCorner => oppositeCorner;
// Position of the anchor when manipulation started.
private Vector3 initialAnchorOnGrabStart;
// Delta from the anchor to the object's center when manipulation started.
private Vector3 initialAnchorDeltaOnGrabStart;
// If we calculate the bounds at Awake and discover a UGUI autolayout group,
// we need to queue up a second bounds computation pass to take the newly computed
// autolayout into account.
private bool needsBoundsRecompute = false;
// Number of frames to wait until we re-compute bounds for UGUI autolayout.
private int waitForFrames = 1;
// An absolute minimum scale to prevent the object from collapsing/inverting.
private Vector3 minimumScale;
// BC cannot scale below this "epsilon" value
private const float lowerAbsoluteClamp = 0.001f;
// Is Bounds Control host selected?
private bool isHostSelected = false;
// Has the bounds control moved past the toggle threshold throughout the time it was selected?
private bool hasPassedToggleThreshold = false;
/// <summary>
/// Struct that defines all the manipulation logic required types for translation, rotation and scaling respectively
/// </summary>
protected struct LogicImplementation
{
/// <summary>
/// Manipulation logic type for translation (returns a vector3)
/// </summary>
public ManipulationLogic<Vector3> moveLogic;
/// <summary>
/// Manipulation logic type for rotation (returns a quaternion)
/// </summary>
public ManipulationLogic<Quaternion> rotateLogic;
/// <summary>
/// Manipulation logic type for scaling (returns a vector3)
/// </summary>
public ManipulationLogic<Vector3> scaleLogic;
}
/// <summary>
/// The instantiated manipulation logic objects, as specified by the types in <see cref="ManipulationLogicTypes"/>.
/// </summary>
protected LogicImplementation ManipulationLogicImplementations { get; private set; }
private void InstantiateManipulationLogic()
{
// Re-instantiate the manipulation logic objects.
ManipulationLogicImplementations = new LogicImplementation()
{
moveLogic = Activator.CreateInstance(ManipulationLogicTypes.moveLogicType) as ManipulationLogic<Vector3>,
rotateLogic = Activator.CreateInstance(ManipulationLogicTypes.rotateLogicType) as ManipulationLogic<Quaternion>,
scaleLogic = Activator.CreateInstance(ManipulationLogicTypes.scaleLogicType) as ManipulationLogic<Vector3>,
};
}
/// <summary>
/// A Unity event function that is called when an enabled script instance is being loaded.
/// </summary>
private void Awake()
{
if (Interactable == null)
{
Interactable = GetComponentInParent<StatefulInteractable>();
}
else
{
SubscribeToInteractable();
}
// Clamp all scaling operations to a tiny fraction the initial scale,
// regardless if the user has applied a MinMaxScaleConstraint or not.
minimumScale = Target.transform.localScale * lowerAbsoluteClamp;
// Spawn our bounds visuals.
CreateBoundsVisuals();
// See if we have a constraints manager.
if (constraintsManager == null)
{
constraintsManager = GetComponent<ConstraintManager>();
}
// Setup constraints with the initial pose.
if (constraintsManager != null)
{
constraintsManager.Setup(new MixedRealityTransform(Target.transform));
}
ManipulationLogicTypes = manipulationLogicTypes;
}
/// <summary>
/// A Unity event function that is called every frame, if this object is enabled.
/// </summary>
protected virtual void Update()
{
// If we need to recompute bounds (usually because we found a
// UGUI element), make sure we've waited enough frames since
// startup, then recompute.
if (needsBoundsRecompute && waitForFrames-- <= 0)
{
ComputeBounds(true);
needsBoundsRecompute = false;
}
TransformTarget();
CheckToggleThreshold();
}
private void OnDestroy()
{
UnsubscribeFromInteractable();
}
private void OnHostSelected(SelectEnterEventArgs args)
{
isHostSelected = true;
hasPassedToggleThreshold = false;
// Track where the interactable was when it was selected.
// We compare against this when the selection ends.
startMovePosition = Target.localPosition;
}
private void OnHostDeselected(SelectExitEventArgs args)
{
if (!hasPassedToggleThreshold && toggleHandlesOnClick)
{
HandlesActive = !HandlesActive;
}
hasPassedToggleThreshold = false;
isHostSelected = false;
}
private void SubscribeToInteractable()
{
if (Interactable != null)
{
Interactable.firstSelectEntered.AddListener(OnHostSelected);
Interactable.lastSelectExited.AddListener(OnHostDeselected);
}
}
private void UnsubscribeFromInteractable()
{
if (Interactable != null)
{
Interactable.firstSelectEntered.RemoveListener(OnHostSelected);
Interactable.lastSelectExited.RemoveListener(OnHostDeselected);
}
}
private void CreateBoundsVisuals()
{
// Teardown the existing bounds visuals if we have any.
if (boxInstance != null)
{
Destroy(boxInstance);
boxInstance = null;
}
if (boundsVisualsPrefab != null)
{
boxInstance = Instantiate(boundsVisualsPrefab, transform);
// Compute bounds, but we might need to run it again one frame later,
// to take UGUI autolayout computation into account.
needsBoundsRecompute = ComputeBounds();
}
}
/// <summary>
/// Recomputes the bounds of the BoundsControl and updates the current bounds visuals to match.
/// </summary>
public void RecomputeBounds()
{
// Any subsequent/public calls to RecomputeBounds are considered a second pass.
ComputeBounds(true);
}
/// <summary>
/// Computes the bounds of the BoundsControl and updates the current bounds visuals to match.
/// </summary>
/// <remarks>
/// If <see langword="true"/> is returned, this function should be called again, with
/// <paramref name="isSecondPass"/> set to <see langword="true"/>, at least one frame from the
/// current frame. This will allow for <see cref="Canvas"/> elements to compute their layouts.
/// </remarks>
/// <param name="isSecondPass">
/// Is this the second pass? If not, we'll abort early if we find the need to queue up a second pass.
/// </param>
/// <returns>
/// <see langword="true"/> if a second computation pass is required, usually because we found a Canvas element somewhere.
/// </returns>
private bool ComputeBounds(bool isSecondPass = false)
{
// currentBounds are local to Target.
// needsBoundsRecompute will be set to true if and only if we find a UGUI autolayout.
// Use the bounds override if we have one.
Transform searchStart = (overrideBounds && boundsOverride != null) ? boundsOverride : Target;
currentBounds = BoundsCalculator.CalculateBounds(Target, searchStart, boxInstance.transform, out bool foundCanvas, boundsCalculationMethod, includeInactiveObjects, !isSecondPass);
// Immediately give up if we know we have a UGUI layout.
// We re-queue a second pass next frame.
if (foundCanvas && isSecondPass == false)
{
return foundCanvas;
}
// Transform bounds to world-scale. (Still Target-axis-aligned.)
Vector3 globalBoundsSize = Vector3.Scale(currentBounds.size, Target.lossyScale);
// Compute the flatten vector.
flattenVector = BoundsCalculator.CalculateFlattenVector(globalBoundsSize);
// Are we flattened?
bool isThinEnough = globalBoundsSize.x < 0.01f || globalBoundsSize.y < 0.01f || globalBoundsSize.z < 0.01f;
IsFlat = (isThinEnough && FlattenMode == FlattenMode.Auto) || FlattenMode == FlattenMode.Always;
// If flattened, flatten the padding by the flatten vector.
Vector3 padding = IsFlat ? Vector3.Scale(Vector3.one * BoundsPadding, Vector3.one - flattenVector) : Vector3.one * BoundsPadding;
// Rescale the padding back to local space, because we need to add it back onto the bounds.
Vector3 localPadding = Vector3.Scale(padding, new Vector3(1.0f / Target.lossyScale.x, 1.0f / Target.lossyScale.y, 1.0f / Target.lossyScale.z));
currentBounds.size += localPadding;
// Initialize the box instance to the correct size/position.
boxInstance.transform.localScale = currentBounds.size;
boxInstance.transform.localPosition = currentBounds.center;
return foundCanvas;
}
/// <summary>
/// Called by <see cref="BoundsHandleInteractable"/> from its OnSelectExited.
/// Routes the XRI event data through, as well as a reference to itself, the selected handle.
/// </summary>
internal void OnHandleSelectExited(BoundsHandleInteractable handle, SelectExitEventArgs args)
{
if (currentHandle == handle)
{
currentHandle = null;
// Notify listeners of manipulation end.
manipulationEnded?.Invoke(args);
}
}
/// <summary>
/// Called by <see cref="BoundsHandleInteractable"/> from its OnSelectEntered.
/// Routes the XRI event data through, as well as a reference to itself, the selected handle.
/// </summary>
internal void OnHandleSelectEntered(BoundsHandleInteractable handle, SelectEnterEventArgs args)
{
if (currentHandle != null)
{
return;
}
if ((handle.HandleType & EnabledHandles) == handle.HandleType)
{
// Notify listeners of manipulation start.
manipulationStarted?.Invoke(args);
currentHandle = handle;
initialTransformOnGrabStart = new MixedRealityTransform(Target.transform);
Vector3 anchorPoint = RotateAnchor == RotateAnchorType.BoundsCenter ? Target.transform.TransformPoint(currentBounds.center) : Target.transform.position;
initialAnchorOnGrabStart = anchorPoint;
initialAnchorDeltaOnGrabStart = Target.transform.position - anchorPoint;
// todo: move this out?
if (currentHandle.HandleType == HandleType.Scale)
{
// Will use this to scale the target relative to the opposite corner
oppositeCorner = boxInstance.transform.TransformPoint(-currentHandle.transform.localPosition);
// ScaleStarted?.Invoke();
ManipulationLogicImplementations.scaleLogic.Setup(currentHandle.interactorsSelecting, args.interactableObject, initialTransformOnGrabStart);
}
else if (currentHandle.HandleType == HandleType.Rotation)
{
// RotateStarted?.Invoke();
ManipulationLogicImplementations.rotateLogic.Setup(currentHandle.interactorsSelecting, args.interactableObject, initialTransformOnGrabStart);
}
else if (currentHandle.HandleType == HandleType.Translation)
{
// currentTranslationAxis = GetTranslationAxis(handle);
// TranslateStarted?.Invoke();
ManipulationLogicImplementations.moveLogic.Setup(currentHandle.interactorsSelecting, args.interactableObject, initialTransformOnGrabStart);
}
if (EnableConstraints && constraintsManager != null)
{
constraintsManager.OnManipulationStarted(new MixedRealityTransform(Target.transform));
}
}
}
private static readonly ProfilerMarker TransformTargetPerfMarker =
new ProfilerMarker("[MRTK] BoundsControl.TransformTarget");
private void TransformTarget()
{
using (TransformTargetPerfMarker.Auto())
{
if (currentHandle != null)
{
TransformFlags transformUpdated = 0;
MixedRealityTransform targetTransform = new MixedRealityTransform(target.transform);
if (currentHandle.HandleType == HandleType.Rotation)
{
var goalRotation = ManipulationLogicImplementations.rotateLogic.Update(currentHandle.interactorsSelecting, interactable, targetTransform, RotateAnchor == RotateAnchorType.BoundsCenter);
Quaternion rotationDelta = goalRotation * Quaternion.Inverse(initialTransformOnGrabStart.Rotation);
Vector3 goalPosition = initialAnchorOnGrabStart + (rotationDelta * initialAnchorDeltaOnGrabStart);
MixedRealityTransform constraintRotation = MixedRealityTransform.NewRotate(goalRotation);
if (EnableConstraints && constraintsManager != null)
{
constraintsManager.ApplyRotationConstraints(ref constraintRotation, true, currentHandle.IsGrabSelected);
}
// TODO: Elastics integration (soon!)
// if (elasticsManager != null)
// {
// transformUpdated = elasticsManager.ApplyTargetTransform(constraintRotation, TransformFlags.Rotate);
// }
if (!transformUpdated.IsMaskSet(TransformFlags.Rotate))
{
// Here, we apply smoothing to the new goal position using the rotateLerpTime, because this
// position modification is specifically for adjusting the object's origin based on the RotateAnchorType.
// This offset needs to match the smoothing on the rotation.
Target.transform.SetPositionAndRotation(
smoothingActive ?
Smoothing.SmoothTo(Target.transform.position, goalPosition, rotateLerpTime, Time.deltaTime) :
goalPosition,
smoothingActive ?
Smoothing.SmoothTo(Target.transform.rotation, constraintRotation.Rotation, rotateLerpTime, Time.deltaTime) :
constraintRotation.Rotation
);
}
}
else if (currentHandle.HandleType == HandleType.Scale)
{
Vector3 anchorPoint = ScaleAnchor == ScaleAnchorType.BoundsCenter ? Target.transform.TransformPoint(currentBounds.center) : oppositeCorner;
var newScale = ManipulationLogicImplementations.scaleLogic.Update(currentHandle.interactorsSelecting, interactable, targetTransform, ScaleAnchor == ScaleAnchorType.BoundsCenter);
MixedRealityTransform clampedTransform = MixedRealityTransform.NewScale(newScale);
if (EnableConstraints && constraintsManager != null)
{
constraintsManager.ApplyScaleConstraints(ref clampedTransform, true, currentHandle.IsGrabSelected);
}
// Clamp to an absolute minimum, regardless of whether a MinMaxScaleConstraint is being used or not.
// Prevents object from collapsing/inverting.
clampedTransform.Scale = Vector3.Max(clampedTransform.Scale, minimumScale);
// TODO: Elastics integration (soon!)
// if (elasticsManager != null)
// {
// transformUpdated = elasticsManager.ApplyTargetTransform(clampedTransform, TransformFlags.Scale);
// }
if (!transformUpdated.IsMaskSet(TransformFlags.Scale))
{
Target.transform.localScale = smoothingActive ?
Smoothing.SmoothTo(Target.transform.localScale, clampedTransform.Scale, scaleLerpTime, Time.deltaTime) :
clampedTransform.Scale;
}
var originalRelativePosition = Target.transform.InverseTransformDirection(initialTransformOnGrabStart.Position - anchorPoint);
var newPosition = Target.transform.TransformDirection(originalRelativePosition.Mul(clampedTransform.Scale.Div(initialTransformOnGrabStart.Scale))) + anchorPoint;
Target.transform.position = smoothingActive ? Smoothing.SmoothTo(Target.transform.position, newPosition, scaleLerpTime, Time.deltaTime) : newPosition;
}
else if (currentHandle.HandleType == HandleType.Translation)
{
var goal = ManipulationLogicImplementations.moveLogic.Update(currentHandle.interactorsSelecting, interactable, targetTransform, true);
MixedRealityTransform constraintTranslate = MixedRealityTransform.NewTranslate(goal);
if (EnableConstraints && constraintsManager != null)
{
constraintsManager.ApplyTranslationConstraints(ref constraintTranslate, true, currentHandle.IsGrabSelected);
}
// TODO: Elastics integration (soon!)
// if (elasticsManager != null)
// {
// transformUpdated = elasticsManager.ApplyTargetTransform(constraintTranslate, TransformFlags.Move);
// }
if (!transformUpdated.IsMaskSet(TransformFlags.Move))
{
Target.transform.position = smoothingActive ?
Smoothing.SmoothTo(Target.transform.position, constraintTranslate.Position, translateLerpTime, Time.deltaTime) :
constraintTranslate.Position;
}
}
}
}
}
private void CheckToggleThreshold()
{
if (isHostSelected && !hasPassedToggleThreshold && Vector3.Distance(startMovePosition, Target.localPosition) >= dragToggleThreshold)
{
hasPassedToggleThreshold = true;
}
}
}
}