GvrPointerGraphicRaycaster.cs
12 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
//-----------------------------------------------------------------------
// <copyright file="GvrPointerGraphicRaycaster.cs" company="Google Inc.">
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
using Gvr.Internal;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>This script provides a raycaster for use with the `GvrPointerInputModule`.</summary>
/// <remarks><para>
/// This behaves similarly to the standards Graphic raycaster, except that it utilize raycast
/// modes specifically for Gvr.
/// </para><para>
/// See `GvrBasePointerRaycaster.cs` and `GvrPointerInputModule.cs` for more details.
/// </para></remarks>
[AddComponentMenu("GoogleVR/GvrPointerGraphicRaycaster")]
[RequireComponent(typeof(Canvas))]
[HelpURL("https://developers.google.com/vr/unity/reference/class/GvrPointerGraphicRaycaster")]
public class GvrPointerGraphicRaycaster : GvrBasePointerRaycaster
{
/// <summary>Flag for ignoring reversed graphics direction.</summary>
public bool ignoreReversedGraphics = true;
/// <summary>The type of objects which can block raycasts.</summary>
public BlockingObjects blockingObjects = BlockingObjects.ThreeD;
/// <summary>The blocking layer mask to use when raycasting.</summary>
public LayerMask blockingMask = NO_EVENT_MASK_SET;
private const int NO_EVENT_MASK_SET = -1;
private static List<Graphic> sortedGraphics = new List<Graphic>();
private Canvas targetCanvas;
private List<Graphic> raycastResults = new List<Graphic>();
private Camera cachedPointerEventCamera;
/// <summary>
/// Initializes a new instance of the <see cref="GvrPointerGraphicRaycaster" /> class.
/// </summary>
protected GvrPointerGraphicRaycaster()
{
}
/// <summary>Types of blocking objects this object's raycasts can hit.</summary>
public enum BlockingObjects
{
/// <summary>This cannot hit any objects.</summary>
None = 0,
/// <summary>This can hit only 2D objects.</summary>
TwoD = 1,
/// <summary>This can hit only 3D objects.</summary>
ThreeD = 2,
/// <summary>This can hit all objects.</summary>
All = 3,
}
/// <summary>Gets the event Camera used for gaze-based raycasts.</summary>
/// <value>The event camera.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"UnityRules.LegacyGvrStyleRules",
"VR1001:AccessibleNonConstantPropertiesMustBeUpperCamelCase",
Justification = "Legacy Public API.")]
public override Camera eventCamera
{
[SuppressMemoryAllocationError(IsWarning = true,
Reason = "A getter for a Camera should not allocate.")]
get
{
GvrBasePointer pointer = GvrPointerInputModule.Pointer;
if (pointer == null)
{
return null;
}
if (pointer.raycastMode == GvrBasePointer.RaycastMode.Hybrid)
{
return GetCameraForRaycastMode(pointer, CurrentRaycastModeForHybrid);
}
else
{
return GetCameraForRaycastMode(pointer, pointer.raycastMode);
}
}
}
/// <summary>Perform raycast on the scene.</summary>
/// <param name="pointerRay">The ray to use for the operation.</param>
/// <param name="radius">The radius of the ray to use when testing for hits.</param>
/// <param name="eventData">The event data triggered by any resultant Raycast hits.</param>
/// <param name="resultAppendList">The results are appended to this list.</param>
/// <returns>Returns `true` if the Raycast has at least one hit, `false` otherwise.</returns>
protected override bool PerformRaycast(GvrBasePointer.PointerRay pointerRay,
float radius,
PointerEventData eventData,
List<RaycastResult> resultAppendList)
{
if (targetCanvas == null)
{
targetCanvas = GetComponent<Canvas>();
if (targetCanvas == null)
{
return false;
}
}
if (eventCamera == null)
{
return false;
}
if (targetCanvas.renderMode != RenderMode.WorldSpace)
{
Debug.LogError("GvrPointerGraphicRaycaster requires that the canvas renderMode is set "
+ "to WorldSpace.");
return false;
}
float hitDistance = float.MaxValue;
if (blockingObjects != BlockingObjects.None)
{
float dist = pointerRay.distance;
if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
{
RaycastHit hit;
if (Physics.Raycast(pointerRay.ray, out hit, dist, blockingMask))
{
hitDistance = hit.distance;
}
}
if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
{
RaycastHit2D hit = Physics2D.Raycast(pointerRay.ray.origin,
pointerRay.ray.direction,
dist,
blockingMask);
if (hit.collider != null)
{
hitDistance = hit.fraction * dist;
}
}
}
raycastResults.Clear();
Ray finalRay;
Raycast(targetCanvas,
pointerRay.ray,
eventCamera,
pointerRay.distance,
raycastResults,
out finalRay);
bool foundHit = false;
for (int index = 0; index < raycastResults.Count; index++)
{
GameObject go = raycastResults[index].gameObject;
bool appendGraphic = true;
if (ignoreReversedGraphics)
{
// If we have a camera compare the direction against the cameras forward.
Vector3 cameraFoward = eventCamera.transform.rotation * Vector3.forward;
Vector3 dir = go.transform.rotation * Vector3.forward;
appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
}
if (appendGraphic)
{
float resultDistance = 0;
Transform trans = go.transform;
Vector3 transForward = trans.forward;
// http://geomalgorithms.com/a06-_intersect-2.html
float transDot = Vector3.Dot(transForward, trans.position - pointerRay.ray.origin);
float rayDot = Vector3.Dot(transForward, pointerRay.ray.direction);
resultDistance = transDot / rayDot;
Vector3 hitPosition =
pointerRay.ray.origin + (pointerRay.ray.direction * resultDistance);
// Check to see if the go is behind the camera.
if (resultDistance < 0 ||
resultDistance >= hitDistance ||
resultDistance > pointerRay.distance)
{
continue;
}
resultDistance = resultDistance + pointerRay.distanceFromStart;
Transform pointerTransform =
GvrPointerInputModule.Pointer.PointerTransform;
float delta = (hitPosition - pointerTransform.position).magnitude;
if (delta < pointerRay.distanceFromStart)
{
continue;
}
RaycastResult castResult = new RaycastResult
{
gameObject = go,
module = this,
distance = resultDistance,
worldPosition = hitPosition,
screenPosition = eventCamera.WorldToScreenPoint(hitPosition),
index = resultAppendList.Count,
depth = raycastResults[index].depth,
sortingLayer = targetCanvas.sortingLayerID,
sortingOrder = targetCanvas.sortingOrder
};
resultAppendList.Add(castResult);
foundHit = true;
}
}
return foundHit;
}
// Perform a raycast into the screen and collect all graphics underneath it.
private static void Raycast(Canvas canvas, Ray ray, Camera cam, float distance,
List<Graphic> results, out Ray finalRay)
{
Vector3 screenPoint = cam.WorldToScreenPoint(ray.GetPoint(distance));
finalRay = cam.ScreenPointToRay(screenPoint);
// Necessary for the event system
IList<Graphic> foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
for (int i = 0; i < foundGraphics.Count; ++i)
{
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1 || !graphic.raycastTarget)
{
continue;
}
if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform,
screenPoint,
cam))
{
continue;
}
if (graphic.Raycast(screenPoint, cam))
{
sortedGraphics.Add(graphic);
}
}
sortedGraphics.Sort((g1, g2) => g2.depth.CompareTo(g1.depth));
for (int i = 0; i < sortedGraphics.Count; ++i)
{
results.Add(sortedGraphics[i]);
}
sortedGraphics.Clear();
}
private Camera GetCameraForRaycastMode(GvrBasePointer pointer, GvrBasePointer.RaycastMode mode)
{
switch (mode)
{
case GvrBasePointer.RaycastMode.Direct:
return GetCameraForRaycastModeDirect(pointer);
case GvrBasePointer.RaycastMode.Camera:
default:
return pointer.PointerCamera;
}
}
private Camera GetCameraForRaycastModeDirect(GvrBasePointer pointer)
{
// Clear cachedPointerEventCamera if the pointer has changed.
if (cachedPointerEventCamera != null &&
cachedPointerEventCamera.gameObject !=
GvrPointerInputModule.Pointer.PointerTransform.gameObject)
{
cachedPointerEventCamera = null;
}
// Get and cache the pointer's camera component.
if (cachedPointerEventCamera == null)
{
Transform pointerTransform = GvrPointerInputModule.Pointer.PointerTransform;
cachedPointerEventCamera = pointerTransform.GetComponent<Camera>();
}
// Still no pointer camera? Add a dummy one.
if (cachedPointerEventCamera == null)
{
cachedPointerEventCamera = AddDummyCameraToPointer(pointer);
}
return cachedPointerEventCamera;
}
private Camera AddDummyCameraToPointer(GvrBasePointer pointer)
{
Camera camera = pointer.PointerTransform.gameObject.AddComponent<Camera>();
camera.enabled = false;
camera.nearClipPlane = 0.01f; // Minimum Near Clip Plane.
return camera;
}
}