BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Scripts / Util / OVRRaycaster.cs

OVRRaycaster.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRRaycaster.cs 11.3 KiB Download Raw
1/************************************************************************************
2Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
3
4Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
5the Utilities SDK except in compliance with the License, which is provided at the time of installation
6or download, or which otherwise accompanies this software in either electronic or hard copy form.
7
8You may obtain a copy of the License at
9https://developer.oculus.com/licenses/utilities-1.31
10
11Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
12under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13ANY KIND, either express or implied. See the License for the specific language governing
14permissions and limitations under the License.
15************************************************************************************/
16
17using System;
18using System.Collections;
19using System.Collections.Generic;
20using System.Text;
21using UnityEngine;
22using UnityEngine.UI;
23using UnityEngine.EventSystems;
24using UnityEngine.Serialization;
25
26/// <summary>
27/// Extension of GraphicRaycaster to support ray casting with world space rays instead of just screen-space
28/// pointer positions
29/// </summary>
30[RequireComponent(typeof(Canvas))]
31public class OVRRaycaster : GraphicRaycaster, IPointerEnterHandler
32{
33 [Tooltip("A world space pointer for this canvas")]
34 public GameObject pointer;
35
36 public int sortOrder = 0;
37
38 protected OVRRaycaster()
39 { }
40
41 [NonSerialized]
42 private Canvas m_Canvas;
43
44 private Canvas canvas
45 {
46 get
47 {
48 if (m_Canvas != null)
49 return m_Canvas;
50
51 m_Canvas = GetComponent<Canvas>();
52 return m_Canvas;
53 }
54 }
55
56 public override Camera eventCamera
57 {
58 get
59 {
60 return canvas.worldCamera;
61 }
62 }
63
64 public override int sortOrderPriority
65 {
66 get
67 {
68 return sortOrder;
69 }
70 }
71
72 protected override void Start()
73 {
74 if(!canvas.worldCamera)
75 {
76 Debug.Log("Canvas does not have an event camera attached. Attaching OVRCameraRig.centerEyeAnchor as default.");
77 OVRCameraRig rig = FindObjectOfType<OVRCameraRig>();
78 canvas.worldCamera = rig.centerEyeAnchor.gameObject.GetComponent<Camera>();
79 }
80 }
81
82 /// <summary>
83 /// For the given ray, find graphics on this canvas which it intersects and are not blocked by other
84 /// world objects
85 /// </summary>
86 [NonSerialized]
87 private List<RaycastHit> m_RaycastResults = new List<RaycastHit>();
88 private void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList, Ray ray, bool checkForBlocking)
89 {
90 //This function is closely based on
91 //void GraphicRaycaster.Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
92
93 if (canvas == null)
94 return;
95
96 float hitDistance = float.MaxValue;
97
98 if (checkForBlocking && blockingObjects != BlockingObjects.None)
99 {
100 float dist = eventCamera.farClipPlane;
101
102 if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
103 {
104 var hits = Physics.RaycastAll(ray, dist, m_BlockingMask);
105
106 if (hits.Length > 0 && hits[0].distance < hitDistance)
107 {
108 hitDistance = hits[0].distance;
109 }
110 }
111
112 if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
113 {
114 var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask);
115
116 if (hits.Length > 0 && hits[0].fraction * dist < hitDistance)
117 {
118 hitDistance = hits[0].fraction * dist;
119 }
120 }
121 }
122
123 m_RaycastResults.Clear();
124
125 GraphicRaycast(canvas, ray, m_RaycastResults);
126
127 for (var index = 0; index < m_RaycastResults.Count; index++)
128 {
129 var go = m_RaycastResults[index].graphic.gameObject;
130 bool appendGraphic = true;
131
132 if (ignoreReversedGraphics)
133 {
134 // If we have a camera compare the direction against the cameras forward.
135 var cameraFoward = ray.direction;
136 var dir = go.transform.rotation * Vector3.forward;
137 appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
138 }
139
140 // Ignore points behind us (can happen with a canvas pointer)
141 if (eventCamera.transform.InverseTransformPoint(m_RaycastResults[index].worldPos).z <= 0)
142 {
143 appendGraphic = false;
144 }
145
146 if (appendGraphic)
147 {
148 float distance = Vector3.Distance(ray.origin, m_RaycastResults[index].worldPos);
149
150 if (distance >= hitDistance)
151 {
152 continue;
153 }
154
155 var castResult = new RaycastResult
156 {
157 gameObject = go,
158 module = this,
159 distance = distance,
160 index = resultAppendList.Count,
161 depth = m_RaycastResults[index].graphic.depth,
162
163 worldPosition = m_RaycastResults[index].worldPos
164 };
165 resultAppendList.Add(castResult);
166 }
167 }
168 }
169
170 /// <summary>
171 /// Performs a raycast using eventData.worldSpaceRay
172 /// </summary>
173 /// <param name="eventData"></param>
174 /// <param name="resultAppendList"></param>
175 public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
176 {
177 if (eventData.IsVRPointer())
178 {
179 Raycast(eventData, resultAppendList, eventData.GetRay(), true);
180 }
181 }
182 /// <summary>
183 /// Performs a raycast using the pointer object attached to this OVRRaycaster
184 /// </summary>
185 /// <param name="eventData"></param>
186 /// <param name="resultAppendList"></param>
187 public void RaycastPointer(PointerEventData eventData, List<RaycastResult> resultAppendList)
188 {
189 if (pointer != null && pointer.activeInHierarchy)
190 {
191 Raycast(eventData, resultAppendList, new Ray(eventCamera.transform.position, (pointer.transform.position - eventCamera.transform.position).normalized), false);
192 }
193 }
194
195
196 /// <summary>
197 /// Perform a raycast into the screen and collect all graphics underneath it.
198 /// </summary>
199 [NonSerialized]
200 static readonly List<RaycastHit> s_SortedGraphics = new List<RaycastHit>();
201 private void GraphicRaycast(Canvas canvas, Ray ray, List<RaycastHit> results)
202 {
203 //This function is based closely on :
204 // void GraphicRaycaster.Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results)
205 // But modified to take a Ray instead of a canvas pointer, and also to explicitly ignore
206 // the graphic associated with the pointer
207
208 // Necessary for the event system
209 var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
210 s_SortedGraphics.Clear();
211 for (int i = 0; i < foundGraphics.Count; ++i)
212 {
213 Graphic graphic = foundGraphics[i];
214
215 // -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
216 if (graphic.depth == -1 || (pointer == graphic.gameObject))
217 continue;
218 Vector3 worldPos;
219 if (RayIntersectsRectTransform(graphic.rectTransform, ray, out worldPos))
220 {
221 //Work out where this is on the screen for compatibility with existing Unity UI code
222 Vector2 screenPos = eventCamera.WorldToScreenPoint(worldPos);
223 // mask/image intersection - See Unity docs on eventAlphaThreshold for when this does anything
224 if (graphic.Raycast(screenPos, eventCamera))
225 {
226 RaycastHit hit;
227 hit.graphic = graphic;
228 hit.worldPos = worldPos;
229 hit.fromMouse = false;
230 s_SortedGraphics.Add(hit);
231 }
232 }
233 }
234
235 s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth));
236
237 for (int i = 0; i < s_SortedGraphics.Count; ++i)
238 {
239 results.Add(s_SortedGraphics[i]);
240 }
241 }
242 /// <summary>
243 /// Get screen position of worldPosition contained in this RaycastResult
244 /// </summary>
245 /// <param name="worldPosition"></param>
246 /// <returns></returns>
247 public Vector2 GetScreenPosition(RaycastResult raycastResult)
248 {
249 // In future versions of Uinty RaycastResult will contain screenPosition so this will not be necessary
250 return eventCamera.WorldToScreenPoint(raycastResult.worldPosition);
251 }
252
253
254 /// <summary>
255 /// Detects whether a ray intersects a RectTransform and if it does also
256 /// returns the world position of the intersection.
257 /// </summary>
258 /// <param name="rectTransform"></param>
259 /// <param name="ray"></param>
260 /// <param name="worldPos"></param>
261 /// <returns></returns>
262 static bool RayIntersectsRectTransform(RectTransform rectTransform, Ray ray, out Vector3 worldPos)
263 {
264 Vector3[] corners = new Vector3[4];
265 rectTransform.GetWorldCorners(corners);
266 Plane plane = new Plane(corners[0], corners[1], corners[2]);
267
268 float enter;
269 if (!plane.Raycast(ray, out enter))
270 {
271 worldPos = Vector3.zero;
272 return false;
273 }
274
275 Vector3 intersection = ray.GetPoint(enter);
276
277 Vector3 BottomEdge = corners[3] - corners[0];
278 Vector3 LeftEdge = corners[1] - corners[0];
279 float BottomDot = Vector3.Dot(intersection - corners[0], BottomEdge);
280 float LeftDot = Vector3.Dot(intersection - corners[0], LeftEdge);
281 if (BottomDot < BottomEdge.sqrMagnitude && // Can use sqrMag because BottomEdge is not normalized
282 LeftDot < LeftEdge.sqrMagnitude &&
283 BottomDot >= 0 &&
284 LeftDot >= 0)
285 {
286 worldPos = corners[0] + LeftDot * LeftEdge / LeftEdge.sqrMagnitude + BottomDot * BottomEdge / BottomEdge.sqrMagnitude;
287 return true;
288 }
289 else
290 {
291 worldPos = Vector3.zero;
292 return false;
293 }
294 }
295
296
297 struct RaycastHit
298 {
299 public Graphic graphic;
300 public Vector3 worldPos;
301 public bool fromMouse;
302 };
303
304
305 /// <summary>
306 /// Is this the currently focussed Raycaster according to the InputModule
307 /// </summary>
308 /// <returns></returns>
309 public bool IsFocussed()
310 {
311 OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
312 return inputModule && inputModule.activeGraphicRaycaster == this;
313 }
314
315 public void OnPointerEnter(PointerEventData e)
316 {
317 if (e.IsVRPointer())
318 {
319 // Gaze has entered this canvas. We'll make it the active one so that canvas-mouse pointer can be used.
320 OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
321 if(inputModule != null)
322 {
323 inputModule.activeGraphicRaycaster = this;
324 }
325
326 }
327 }
328}