-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathMRTKLineVisual.cs
More file actions
502 lines (429 loc) · 19.5 KB
/
Copy pathMRTKLineVisual.cs
File metadata and controls
502 lines (429 loc) · 19.5 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
// Copyright (c) Mixed Reality Toolkit Contributors
// Licensed under the BSD 3-Clause
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.XR.Interaction.Toolkit.Interactors;
using static MixedReality.Toolkit.Input.XRRayInteractorExtensions;
namespace MixedReality.Toolkit.Input
{
/// <summary>
/// This visual component helps align a <see cref="LineRenderer"/> with the Interactor, while giving it "bendy" qualities
/// via the Bezier Data Provider
/// </summary>
[AddComponentMenu("MRTK/Input/MRTK Line Visual")]
[DisallowMultipleComponent]
[DefaultExecutionOrder(XRInteractionUpdateOrder.k_LineVisual)]
public class MRTKLineVisual : MonoBehaviour
{
[Header("Visual Settings")]
[SerializeField]
[Tooltip("Color gradient when there is no applicable target.")]
Gradient noTargetColorGradient = new Gradient
{
colorKeys = new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
alphaKeys = new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) },
};
/// <summary>
///Color gradient when there is no applicable target.
/// </summary>
public Gradient NoTargetColorGradient
{
get => noTargetColorGradient;
set => noTargetColorGradient = value;
}
[SerializeField]
[Tooltip("Color gradient when hovering over a valid target.")]
Gradient validColorGradient = new Gradient
{
colorKeys = new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
alphaKeys = new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) },
};
/// <summary>
/// Color gradient when hovering over a valid target.
/// </summary>
public Gradient ValidColorGradient
{
get => validColorGradient;
set => validColorGradient = value;
}
[SerializeField]
[Tooltip("Color gradient during a selection.")]
Gradient selectActiveColorGradient = new Gradient
{
colorKeys = new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
alphaKeys = new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) },
};
/// <summary>
/// Color gradient during a selection.
/// </summary>
public Gradient SelectActiveColorGradient
{
get => selectActiveColorGradient;
set => selectActiveColorGradient = value;
}
[SerializeField]
[Tooltip("On hit, the gradient will be applied evenly along the line renderer until it's total length is longer than this value multiplied by the ray interactor's max raycast distance")]
[Range(0.01f, 1)]
float maxGradientLength = 0.3f;
/// <summary>
/// On hit, the gradient will be applied evenly along the line renderer until it's total length is longer than this value multiplied by the ray interactor's max raycast distance.
/// </summary>
public float MaxGradientLength
{
get => maxGradientLength;
set => maxGradientLength = value;
}
[SerializeField]
[Tooltip("The width of the line.")]
private AnimationCurve lineWidth = AnimationCurve.Linear(0f, 1f, 1f, 1f);
/// <summary>
/// The width of the line.
/// </summary>
public AnimationCurve LineWidth
{
get => lineWidth;
set => lineWidth = value;
}
[Range(0.0001f, 1f)]
[SerializeField]
[Tooltip("The overall multiplier that is applied to the LineRenderer to get the final width of the line.")]
private float widthMultiplier = 0.0015f;
/// <summary>
/// The overall multiplier that is applied to the LineRenderer to get the final width of the line.
/// </summary>
public float WidthMultiplier
{
get => widthMultiplier;
set => widthMultiplier = Mathf.Clamp(value, 0f, 10f);
}
[Tooltip("Where to place the first control point of the bezier curve.")]
[SerializeField]
[Range(0f, 0.5f)]
private float startPointLerp = 0.267f;
[SerializeField]
[Tooltip("Where to place the second control point of the bezier curve.")]
[Range(0.5f, 1f)]
private float endPointLerp = 0.637f;
[Header("Mixed Reality Line Renderer Settings")]
[SerializeField]
[Tooltip("The ray interactor which this visual represents.")]
private XRRayInteractor rayInteractor;
[SerializeField]
[Tooltip("The line renderer this visual has control over.")]
private LineRenderer lineRenderer = null;
[SerializeField]
[Tooltip("The line data that represented by this visual.")]
private BaseMixedRealityLineDataProvider lineDataProvider = null;
[SerializeField]
[Tooltip("Whether to round the edges of the line renderer.")]
private bool roundedEdges = true;
/// <summary>
/// Whether to round the edges of the line renderer.
/// </summary>
public bool RoundedEdges
{
get => roundedEdges;
set => roundedEdges = value;
}
[SerializeField]
[Tooltip("Whether to round the endpoints of the line renderer.")]
private bool roundedCaps = true;
/// <summary>
/// Whether to round the endpoints of the line renderer.
/// </summary>
public bool RoundedCaps
{
get => roundedCaps;
set => roundedCaps = value;
}
[SerializeField]
[Tooltip("Whether the line renderer stops after hitting an object.")]
private bool stopLineAtFirstRaycastHit = true;
/// <summary>
/// Whether the line renderer stops after hitting an object.
/// </summary>
public bool StopLineAtFirstRaycastHit
{
get => stopLineAtFirstRaycastHit;
set => stopLineAtFirstRaycastHit = value;
}
// Reusable array for retrieving points from the XRRayInteractor
private Vector3[] rayPositions = null;
private int rayPositionsCount = -1;
// reusable lists of the points used for the line renderer
private Vector3[] rendererPositions;
// reusable values derived from raycast hit data
private Vector3 reticlePosition;
private TargetHitDetails selectedHitDetails = new TargetHitDetails();
private float hitDistance;
/// <summary>
/// Used internally to determine if the ray we are visualizing hit an object or not.
/// </summary>
private bool rayHasHit;
// private array used to clear the line renderer when needed
private readonly Vector3[] clearPositions = { Vector3.zero, Vector3.zero };
// Property block for writing per-object material properties
private MaterialPropertyBlock propertyBlock;
#region MonoBehaviour
/// <summary>
/// A Unity event function that is called when the script should reset it's default values
/// </summary>
protected void Reset()
{
if (TryFindLineRenderer())
{
ClearLineRenderer();
InitializeLineRendererProperties();
}
// Try to find a corresponding line data source and raise a warning if it was not initialized and does not exist
if (lineDataProvider == null && !TryGetComponent(out lineDataProvider))
{
Debug.LogWarning("No Line Data Provider found for Interactor Line Visual.", this);
enabled = false;
}
}
#if UNITY_EDITOR
/// <summary>
/// A Unity Editor only event function that is called when the script is loaded or a value changes in the Unity Inspector.
/// </summary>
protected void OnValidate()
{
// We check if this instance has actually been changed, since OnValidate() is called
// on save and Unity detects any setter calls (even if we're just setting the same value)
// as dirtying the line renderer. If MRTK is consumed via UPM, this causes
// Unity to try to save "changes" to a prefab in an immutable folder.
if (UnityEditor.EditorUtility.IsDirty(this))
{
InitializeLineRendererProperties();
}
}
#endif // UNITY_EDITOR
/// <summary>
/// A Unity event function that is called when the script component has been enabled.
/// </summary>
protected void OnEnable()
{
propertyBlock = new MaterialPropertyBlock();
rayInteractor.selectEntered.AddListener(LocateTargetHitPoint);
Application.onBeforeRender += UpdateLineVisual;
Reset();
UpdateLineVisual();
}
/// <summary>
/// A Unity event function that is called when the script component has been disabled.
/// </summary>
protected void OnDisable()
{
rayInteractor.selectEntered.RemoveListener(LocateTargetHitPoint);
Application.onBeforeRender -= UpdateLineVisual;
if (lineRenderer != null)
{
lineRenderer.enabled = false;
}
}
#endregion
#region LineVisual Updates
private static readonly ProfilerMarker UpdateLinePerfMarker = new ProfilerMarker("[MRTK] MRTKLineVisual.UpdateLineVisual");
// Cached value of the current gradient. Used to avoid making calls to lineRenderer.colorGradient, which allocs
private Gradient cachedGradient = new Gradient();
[BeforeRenderOrder(XRInteractionUpdateOrder.k_BeforeRenderLineVisual)]
private void UpdateLineVisual()
{
using(UpdateLinePerfMarker.Auto())
{
InitializeLineRendererProperties();
if (lineRenderer == null)
{
return;
}
if (rayInteractor == null)
{
lineRenderer.enabled = false;
return;
}
// Get all the line sample points from the ILineRenderable interface
if (!rayInteractor.GetLinePoints(ref rayPositions, out rayPositionsCount))
{
lineRenderer.enabled = false;
ClearLineRenderer();
return;
}
// Sanity check.
if (rayPositions == null ||
rayPositions.Length == 0 ||
rayPositionsCount == 0 ||
rayPositionsCount > rayPositions.Length)
{
lineRenderer.enabled = false;
ClearLineRenderer();
return;
}
// Finally enable the line renderer if we pass the other checks
lineRenderer.enabled = rayInteractor.isHoverActive;
// Exit early if the line renderer is ultimately disabled
if (!lineRenderer.enabled)
{
ClearLineRenderer();
return;
}
// Assign the first point to the ray origin
lineDataProvider.FirstPoint = rayPositions[0];
// If the interactor is currently selecting, lock the end of the ray to the selected object
if (rayInteractor.hasSelection)
{
// Assign the last point to the one saved by the callback
lineDataProvider.LastPoint = selectedHitDetails.HitTargetTransform.TransformPoint(selectedHitDetails.TargetLocalHitPoint);
rayHasHit = true;
}
// Otherwise draw out the line exactly as the Ray Interactor prescribes
else
{
// If the ray hits an object, truncate the visual appropriately
// Remove the last point in the list to keep the number of points consistent.
if (rayInteractor.TryGetHitInfo(out reticlePosition, out _, out int endPositionInLine, out bool isValidTarget))
{
// End the line at the current hit point.
if ((isValidTarget || StopLineAtFirstRaycastHit) && endPositionInLine > 0 && endPositionInLine < rayPositionsCount)
{
rayPositions[endPositionInLine] = reticlePosition;
rayPositionsCount = endPositionInLine + 1;
hitDistance = (reticlePosition - rayPositions[0]).magnitude;
rayHasHit = true;
}
else
{
rayHasHit = false;
}
}
else
{
rayHasHit = false;
}
// Assign the last point to last point in the data structure
lineDataProvider.LastPoint = rayPositions[rayPositionsCount - 1];
}
// Project forward based on pointer direction to get an 'expected' position of the first control point if we've hit an object
if (rayHasHit)
{
Vector3 startPoint = lineDataProvider.FirstPoint;
Vector3 expectedPoint = startPoint + rayInteractor.rayOriginTransform.forward * hitDistance;
// Lerp between the expected position and the expected point if we've hit an object
lineDataProvider.SetPoint(1, Vector3.Lerp(startPoint, expectedPoint, startPointLerp));
// Get our next 'expected' position by lerping between the expected point and the end point
// The result will be a line that starts moving in the pointer's direction then bends towards the target
expectedPoint = Vector3.Lerp(expectedPoint, lineDataProvider.LastPoint, endPointLerp);
lineDataProvider.SetPoint(2, Vector3.Lerp(startPoint, expectedPoint, endPointLerp));
}
// Set positions for the rendered ray visual after passing it through the lineDataProvider
lineRenderer.positionCount = lineStepCount;
if (rendererPositions == null || rendererPositions.Length != lineRenderer.positionCount)
{
rendererPositions = new Vector3[lineStepCount];
}
for (int i = 0; i < lineStepCount; i++)
{
float normalizedDistance = GetNormalizedPointAlongLine(i);
rendererPositions[i] = lineDataProvider.GetPoint(normalizedDistance);
}
lineRenderer.SetPositions(rendererPositions);
// Now handle coloring the line visual
// If our interactor is a variable select interactor, change the material property based on select progress
if (rayInteractor != null)
{
lineRenderer.GetPropertyBlock(propertyBlock);
propertyBlock.SetFloat("_Shift_", rayInteractor.largestInteractionStrength.Value);
lineRenderer.SetPropertyBlock(propertyBlock);
}
// If we are hovering over a valid object or are currently selecting one, lerp the color based on selectedness
if (rayHasHit || rayInteractor.hasSelection)
{
if (rayInteractor != null)
{
cachedGradient = ColorUtilities.GradientLerp(ValidColorGradient, SelectActiveColorGradient, rayInteractor.largestInteractionStrength.Value);
}
else
{
cachedGradient = ColorUtilities.GradientLerp(ValidColorGradient, SelectActiveColorGradient, rayInteractor.hasSelection ? 1 : 0);
}
// apply the compression effect
var compressionAmount = Mathf.Clamp(rayInteractor.maxRaycastDistance * MaxGradientLength / hitDistance, 0.0f, 1.0f);
cachedGradient = ColorUtilities.GradientCompress(cachedGradient, 0.0f, compressionAmount);
}
else
{
cachedGradient = NoTargetColorGradient;
}
lineRenderer.colorGradient = cachedGradient;
}
}
private void InitializeLineRendererProperties()
{
if (TryFindLineRenderer())
{
// Set line renderer properties
lineRenderer.numCapVertices = RoundedCaps ? 8 : 0;
lineRenderer.numCornerVertices = RoundedEdges ? 8 : 0;
lineRenderer.useWorldSpace = true;
lineRenderer.startWidth = 1;
lineRenderer.endWidth = 1;
lineRenderer.startColor = Color.white;
lineRenderer.endColor = Color.white;
lineRenderer.widthCurve = LineWidth;
lineRenderer.widthMultiplier = WidthMultiplier;
lineRenderer.shadowCastingMode = ShadowCastingMode.Off;
lineRenderer.lightProbeUsage = LightProbeUsage.Off;
}
}
/// <summary>
/// Used to locate and lock the raycast hit data on a select
/// </summary>
private void LocateTargetHitPoint(SelectEnterEventArgs args)
{
// If no hit interactable or we haven't even gotten any ray positions yet, abort
if (args == null || rayPositions == null || rayPositionsCount <= 0)
{
return;
}
rayInteractor.TryLocateTargetHitPoint(args.interactableObject, out selectedHitDetails);
hitDistance = (selectedHitDetails.HitDistanceReferencePoint - rayPositions[0]).magnitude;
}
#endregion
private bool TryFindLineRenderer()
{
if (lineRenderer == null)
{
if (!TryGetComponent(out lineRenderer))
{
Debug.LogWarning("No Line Renderer found for MRTK Ray Interactor Visual.", this);
enabled = false;
return false;
}
}
return true;
}
private void ClearLineRenderer()
{
if (TryFindLineRenderer())
{
lineRenderer.SetPositions(clearPositions);
lineRenderer.positionCount = 0;
}
}
[Range(2, 128)]
[SerializeField]
[Tooltip("Number of steps to interpolate along line in Interpolated step mode")]
private int lineStepCount = 16;
/// <summary>
/// Gets the normalized distance along the line path (range 0 to 1) going the given number of steps provided
/// </summary>
/// <param name="stepNum">Number of steps to take "walking" along the curve </param>
protected virtual float GetNormalizedPointAlongLine(int stepNum)
{
// Normalized length along line
float normalizedDistance = (1f / (lineStepCount - 1)) * stepNum;
return normalizedDistance;
}
}
}