OculusSpatializerUnity.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /************************************************************************************
  2. Filename : OculusSpatializerUnity.cs
  3. Content : Interface into real-time geometry reflection engine for native Unity
  4. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  5. Licensed under the Oculus SDK Version 3.5 (the "License");
  6. you may not use the Oculus SDK except in compliance with the License,
  7. which is provided at the time of installation or download, or which
  8. otherwise accompanies this software in either electronic or hard copy form.
  9. You may obtain a copy of the License at
  10. https://developer.oculus.com/licenses/sdk-3.5/
  11. Unless required by applicable law or agreed to in writing, the Oculus SDK
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. ************************************************************************************/
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using UnityEngine;
  20. using System.Runtime.InteropServices;
  21. public class OculusSpatializerUnity : MonoBehaviour
  22. {
  23. public LayerMask layerMask = -1;
  24. public bool visualizeRoom = true;
  25. bool roomVisualizationInitialized = false;
  26. public int raysPerSecond = 256;
  27. public float roomInterpSpeed = 0.9f;
  28. public float maxWallDistance = 50.0f;
  29. public int rayCacheSize = 512;
  30. public bool dynamicReflectionsEnabled = true;
  31. AudioRaycastCallback _raycastCallback; // cache an instance of the delegate so the GC doesn't nuke it!
  32. float particleSize = 0.2f;
  33. float particleOffset = 0.1f;
  34. GameObject room;
  35. Renderer[] wallRenderer = new Renderer[6];
  36. float[] dims = new float[3] { 1.0f, 1.0f, 1.0f };
  37. float[] coefs = new float[6];
  38. const int HIT_COUNT = 2048;
  39. Vector3[] points = new Vector3[HIT_COUNT];
  40. Vector3[] normals = new Vector3[HIT_COUNT];
  41. ParticleSystem sys;
  42. ParticleSystem.Particle[] particles = new ParticleSystem.Particle[HIT_COUNT];
  43. static LayerMask gLayerMask = -1;
  44. static Vector3 swapHandedness(Vector3 vec) { return new Vector3(vec.x, vec.y, -vec.z); }
  45. static void AudioRaycast(Vector3 origin, Vector3 direction, out Vector3 point, out Vector3 normal, System.IntPtr data)
  46. {
  47. point = Vector3.zero;
  48. normal = Vector3.zero;
  49. RaycastHit hitInfo;
  50. if (Physics.Raycast(swapHandedness(origin), swapHandedness(direction), out hitInfo, 1000.0f, gLayerMask.value))
  51. {
  52. point = swapHandedness(hitInfo.point);
  53. normal = swapHandedness(hitInfo.normal);
  54. }
  55. }
  56. void Start()
  57. {
  58. _raycastCallback = new AudioRaycastCallback(AudioRaycast);
  59. OSP_Unity_AssignRaycastCallback(_raycastCallback, System.IntPtr.Zero);
  60. }
  61. void OnDestroy()
  62. {
  63. OSP_Unity_AssignRaycastCallback(System.IntPtr.Zero, System.IntPtr.Zero);
  64. }
  65. void Update()
  66. {
  67. if (dynamicReflectionsEnabled)
  68. {
  69. OSP_Unity_AssignRaycastCallback(_raycastCallback, System.IntPtr.Zero);
  70. }
  71. else
  72. {
  73. OSP_Unity_AssignRaycastCallback(System.IntPtr.Zero, System.IntPtr.Zero);
  74. }
  75. OSP_Unity_SetDynamicRoomRaysPerSecond(raysPerSecond);
  76. OSP_Unity_SetDynamicRoomInterpSpeed(roomInterpSpeed);
  77. OSP_Unity_SetDynamicRoomMaxWallDistance(maxWallDistance);
  78. OSP_Unity_SetDynamicRoomRaysRayCacheSize(rayCacheSize);
  79. gLayerMask = layerMask;
  80. OSP_Unity_UpdateRoomModel(1.0f);
  81. if (visualizeRoom)
  82. {
  83. if (!roomVisualizationInitialized)
  84. {
  85. inititalizeRoomVisualization();
  86. roomVisualizationInitialized = true;
  87. }
  88. Vector3 pos;
  89. OSP_Unity_GetRoomDimensions(dims, coefs, out pos);
  90. pos.z *= -1; // swap to left-handed
  91. var size = new Vector3(dims[0], dims[1], dims[2]);
  92. float magSqrd = size.sqrMagnitude;
  93. if (!float.IsNaN(magSqrd) && 0.0f < magSqrd && magSqrd < 1000000.0f)
  94. {
  95. transform.localScale = size * 0.999f;
  96. }
  97. transform.position = pos;
  98. OSP_Unity_GetRaycastHits(points, normals, HIT_COUNT);
  99. for (int i = 0; i < HIT_COUNT; ++i)
  100. {
  101. if (points[i] == Vector3.zero)
  102. points[i].y = -10000.0f; // hide it
  103. // swap to left-handed
  104. points[i].z *= -1;
  105. normals[i].z *= -1;
  106. particles[i].position = points[i] + normals[i] * particleOffset;
  107. if (normals[i] != Vector3.zero)
  108. particles[i].rotation3D = Quaternion.LookRotation(normals[i]).eulerAngles;
  109. particles[i].startSize = particleSize;
  110. particles[i].startColor = new Color(208 / 255f, 38 / 255f, 174 / 255f, 1.0f);
  111. }
  112. for (int wall = 0; wall < 6; ++wall)
  113. {
  114. var color = Color.Lerp(Color.red, Color.green, coefs[wall]);
  115. wallRenderer[wall].material.SetColor("_TintColor", color);
  116. }
  117. sys.SetParticles(particles, particles.Length);
  118. }
  119. }
  120. private void inititalizeRoomVisualization()
  121. {
  122. Debug.Log("Oculus Audio dynamic room estimation visualization enabled");
  123. transform.position = Vector3.zero; // move to the origin otherwise things are displaced
  124. // Create a particle system to visualize the ray cast hits
  125. GameObject decalManager = new GameObject("DecalManager");
  126. decalManager.transform.parent = transform;
  127. sys = decalManager.AddComponent<ParticleSystem>();
  128. {
  129. var main = sys.main;
  130. main.simulationSpace = ParticleSystemSimulationSpace.World;
  131. main.loop = false;
  132. main.playOnAwake = false;
  133. var emission = sys.emission;
  134. emission.enabled = false;
  135. var shape = sys.shape;
  136. shape.enabled = false;
  137. var renderer = sys.GetComponent<ParticleSystemRenderer>();
  138. renderer.renderMode = ParticleSystemRenderMode.Mesh;
  139. renderer.material.shader = Shader.Find("Particles/Additive");
  140. Texture2D decalTex;
  141. {
  142. const int SIZE = 64;
  143. const int RING_COUNT = 2;
  144. decalTex = new Texture2D(SIZE, SIZE);
  145. const int HALF_SIZE = SIZE / 2;
  146. for (int i = 0; i < SIZE / 2; ++i)
  147. {
  148. for (int j = 0; j < SIZE / 2; ++j)
  149. {
  150. // distance from center
  151. float deltaX = (float)(HALF_SIZE - i);
  152. float deltaY = (float)(HALF_SIZE - j);
  153. float dist = Mathf.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
  154. float t = (RING_COUNT * dist) / HALF_SIZE;
  155. float alpha = (dist < HALF_SIZE) ? Mathf.Clamp01(Mathf.Sin(Mathf.PI * 2.0f * t)) : 0.0f;
  156. Color col = new Color(1.0f, 1.0f, 1.0f, alpha);
  157. // Two way symmetry
  158. decalTex.SetPixel(i, j, col);
  159. decalTex.SetPixel(SIZE - i, j, col);
  160. decalTex.SetPixel(i, SIZE - j, col);
  161. decalTex.SetPixel(SIZE - i, SIZE - j, col);
  162. }
  163. }
  164. decalTex.Apply();
  165. }
  166. renderer.material.mainTexture = decalTex;
  167. // Make a quad
  168. var m = new Mesh();
  169. m.name = "ParticleQuad";
  170. const float size = 0.5f;
  171. m.vertices = new Vector3[] {
  172. new Vector3(-size, -size, 0.0f),
  173. new Vector3( size, -size, 0.0f),
  174. new Vector3( size, size, 0.0f),
  175. new Vector3(-size, size, 0.0f)
  176. };
  177. m.uv = new Vector2[] {
  178. new Vector2(0, 0),
  179. new Vector2(0, 1),
  180. new Vector2(1, 1),
  181. new Vector2(1, 0)
  182. };
  183. m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
  184. m.RecalculateNormals();
  185. renderer.mesh = m;
  186. }
  187. sys.Emit(HIT_COUNT);
  188. // Construct the visual representation of the room
  189. room = new GameObject("RoomVisualizer");
  190. room.transform.parent = transform;
  191. room.transform.localPosition = Vector3.zero;
  192. Texture2D wallTex;
  193. {
  194. const int SIZE = 32;
  195. wallTex = new Texture2D(SIZE, SIZE);
  196. Color transparent = new Color(0.0f, 0.0f, 0.0f, 0.0f);
  197. for (int i = 0; i < SIZE; ++i)
  198. {
  199. for (int j = 0; j < SIZE; ++j)
  200. {
  201. wallTex.SetPixel(i, j, transparent);
  202. }
  203. }
  204. for (int i = 0; i < SIZE; ++i)
  205. {
  206. Color color1 = Color.white * 0.125f;
  207. wallTex.SetPixel(SIZE / 4, i, color1);
  208. wallTex.SetPixel(i, SIZE / 4, color1);
  209. wallTex.SetPixel(3 * SIZE / 4, i, color1);
  210. wallTex.SetPixel(i, 3 * SIZE / 4, color1);
  211. color1 *= 2.0f;
  212. wallTex.SetPixel(SIZE / 2, i, color1);
  213. wallTex.SetPixel(i, SIZE / 2, color1);
  214. color1 *= 2.0f;
  215. wallTex.SetPixel(0, i, color1);
  216. wallTex.SetPixel(i, 0, color1);
  217. }
  218. wallTex.Apply();
  219. }
  220. for (int wall = 0; wall < 6; ++wall)
  221. {
  222. var m = new Mesh();
  223. m.name = "Plane" + wall;
  224. const float size = 0.5f;
  225. var verts = new Vector3[4];
  226. int axis = wall / 2;
  227. int sign = (wall % 2 == 0) ? 1 : -1;
  228. for (int i = 0; i < 4; ++i)
  229. {
  230. verts[i][axis] = sign * size;
  231. verts[i][(axis + 1) % 3] = size * ((i == 1 || i == 2) ? 1 : -1);
  232. verts[i][(axis + 2) % 3] = size * ((i == 2 || i == 3) ? 1 : -1);
  233. }
  234. m.vertices = verts;
  235. m.uv = new Vector2[]
  236. {
  237. new Vector2(0, 0),
  238. new Vector2(0, 1),
  239. new Vector2(1, 1),
  240. new Vector2(1, 0)
  241. };
  242. m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
  243. m.RecalculateNormals();
  244. var go = new GameObject("Wall_" + wall);
  245. go.AddComponent<MeshFilter>().mesh = m;
  246. var renderer = go.AddComponent<MeshRenderer>();
  247. wallRenderer[wall] = renderer;
  248. renderer.material.shader = Shader.Find("Particles/Additive");
  249. renderer.material.mainTexture = wallTex;
  250. renderer.material.mainTextureScale = new Vector2(8, 8);
  251. go.transform.parent = room.transform;
  252. room.transform.localPosition = Vector3.zero;
  253. }
  254. }
  255. // * * * * * * * * * * * * *
  256. // Import functions
  257. public delegate void AudioRaycastCallback(Vector3 origin, Vector3 direction,
  258. out Vector3 point, out Vector3 normal,
  259. System.IntPtr data);
  260. private const string strOSP = "AudioPluginOculusSpatializer";
  261. [DllImport(strOSP)]
  262. private static extern int OSP_Unity_AssignRaycastCallback(System.MulticastDelegate callback, System.IntPtr data);
  263. [DllImport(strOSP)]
  264. private static extern int OSP_Unity_AssignRaycastCallback(System.IntPtr callback, System.IntPtr data);
  265. [DllImport(strOSP)]
  266. private static extern int OSP_Unity_SetDynamicRoomRaysPerSecond(int RaysPerSecond);
  267. [DllImport(strOSP)]
  268. private static extern int OSP_Unity_SetDynamicRoomInterpSpeed(float InterpSpeed);
  269. [DllImport(strOSP)]
  270. private static extern int OSP_Unity_SetDynamicRoomMaxWallDistance(float MaxWallDistance);
  271. [DllImport(strOSP)]
  272. private static extern int OSP_Unity_SetDynamicRoomRaysRayCacheSize(int RayCacheSize);
  273. [DllImport(strOSP)]
  274. private static extern int OSP_Unity_UpdateRoomModel(float wetLevel); // call from main thread!!
  275. [DllImport(strOSP)]
  276. private static extern int OSP_Unity_GetRoomDimensions(float[] roomDimensions, float[] reflectionsCoefs, out Vector3 position);
  277. [DllImport(strOSP)]
  278. private static extern int OSP_Unity_GetRaycastHits(Vector3[] points, Vector3[] normals, int length);
  279. }