2
0

SteamVR_ExternalCamera.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: Used to render an external camera of vr player (split front/back).
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using UnityEngine.Rendering;
  8. using Valve.VR;
  9. namespace Valve.VR
  10. {
  11. public class SteamVR_ExternalCamera : MonoBehaviour
  12. {
  13. private SteamVR_Action_Pose cameraPose = null;
  14. private SteamVR_Input_Sources cameraInputSource = SteamVR_Input_Sources.Camera;
  15. [System.Serializable]
  16. public struct Config
  17. {
  18. public float x, y, z;
  19. public float rx, ry, rz;
  20. public float fov;
  21. public float near, far;
  22. public float sceneResolutionScale;
  23. public float frameSkip;
  24. public float nearOffset, farOffset;
  25. public float hmdOffset;
  26. public float r, g, b, a; // chroma key override
  27. public bool disableStandardAssets;
  28. }
  29. [Space()]
  30. public Config config;
  31. public string configPath;
  32. [Tooltip("This will automatically activate the action set the specified pose belongs to. And deactivate it when this component is disabled.")]
  33. public bool autoEnableDisableActionSet = true;
  34. public void ReadConfig()
  35. {
  36. try
  37. {
  38. var mCam = new HmdMatrix34_t();
  39. var readCamMatrix = false;
  40. object c = config; // box
  41. var lines = System.IO.File.ReadAllLines(configPath);
  42. foreach (var line in lines)
  43. {
  44. var split = line.Split('=');
  45. if (split.Length == 2)
  46. {
  47. var key = split[0];
  48. if (key == "m")
  49. {
  50. var values = split[1].Split(',');
  51. if (values.Length == 12)
  52. {
  53. mCam.m0 = float.Parse(values[0]);
  54. mCam.m1 = float.Parse(values[1]);
  55. mCam.m2 = float.Parse(values[2]);
  56. mCam.m3 = float.Parse(values[3]);
  57. mCam.m4 = float.Parse(values[4]);
  58. mCam.m5 = float.Parse(values[5]);
  59. mCam.m6 = float.Parse(values[6]);
  60. mCam.m7 = float.Parse(values[7]);
  61. mCam.m8 = float.Parse(values[8]);
  62. mCam.m9 = float.Parse(values[9]);
  63. mCam.m10 = float.Parse(values[10]);
  64. mCam.m11 = float.Parse(values[11]);
  65. readCamMatrix = true;
  66. }
  67. }
  68. #if !UNITY_METRO
  69. else if (key == "disableStandardAssets")
  70. {
  71. var field = c.GetType().GetField(key);
  72. if (field != null)
  73. field.SetValue(c, bool.Parse(split[1]));
  74. }
  75. else
  76. {
  77. var field = c.GetType().GetField(key);
  78. if (field != null)
  79. field.SetValue(c, float.Parse(split[1]));
  80. }
  81. #endif
  82. }
  83. }
  84. config = (Config)c; //unbox
  85. // Convert calibrated camera matrix settings.
  86. if (readCamMatrix)
  87. {
  88. var t = new SteamVR_Utils.RigidTransform(mCam);
  89. config.x = t.pos.x;
  90. config.y = t.pos.y;
  91. config.z = t.pos.z;
  92. var angles = t.rot.eulerAngles;
  93. config.rx = angles.x;
  94. config.ry = angles.y;
  95. config.rz = angles.z;
  96. }
  97. }
  98. catch { }
  99. // Clear target so AttachToCamera gets called to pick up any changes.
  100. target = null;
  101. #if !UNITY_METRO
  102. // Listen for changes.
  103. if (watcher == null)
  104. {
  105. var fi = new System.IO.FileInfo(configPath);
  106. watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
  107. watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
  108. watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
  109. watcher.EnableRaisingEvents = true;
  110. }
  111. }
  112. System.IO.FileSystemWatcher watcher;
  113. #else
  114. }
  115. #endif
  116. public void SetupPose(SteamVR_Action_Pose newCameraPose, SteamVR_Input_Sources newCameraSource)
  117. {
  118. cameraPose = newCameraPose;
  119. cameraInputSource = newCameraSource;
  120. AutoEnableActionSet();
  121. SteamVR_Behaviour_Pose poseBehaviour = this.gameObject.AddComponent<SteamVR_Behaviour_Pose>();
  122. poseBehaviour.poseAction = newCameraPose;
  123. poseBehaviour.inputSource = newCameraSource;
  124. }
  125. public void SetupDeviceIndex(int deviceIndex)
  126. {
  127. SteamVR_TrackedObject trackedObject = this.gameObject.AddComponent<SteamVR_TrackedObject>();
  128. trackedObject.SetDeviceIndex(deviceIndex);
  129. }
  130. void OnChanged(object source, System.IO.FileSystemEventArgs e)
  131. {
  132. ReadConfig();
  133. }
  134. Camera cam;
  135. Transform target;
  136. GameObject clipQuad;
  137. Material clipMaterial;
  138. protected SteamVR_ActionSet activatedActionSet;
  139. protected SteamVR_Input_Sources activatedInputSource;
  140. public void AttachToCamera(SteamVR_Camera steamVR_Camera)
  141. {
  142. Camera vrcam;
  143. if (steamVR_Camera == null)
  144. {
  145. vrcam = Camera.main;
  146. if (target == vrcam.transform)
  147. return;
  148. target = vrcam.transform;
  149. }
  150. else
  151. {
  152. vrcam = steamVR_Camera.camera;
  153. if (target == steamVR_Camera.head)
  154. return;
  155. target = steamVR_Camera.head;
  156. }
  157. var root = transform.parent;
  158. var origin = target.parent;
  159. root.parent = origin;
  160. root.localPosition = Vector3.zero;
  161. root.localRotation = Quaternion.identity;
  162. root.localScale = Vector3.one;
  163. // Make a copy of the eye camera to pick up any camera fx.
  164. vrcam.enabled = false;
  165. var go = Instantiate(vrcam.gameObject);
  166. vrcam.enabled = true;
  167. go.name = "camera";
  168. DestroyImmediate(go.GetComponent<SteamVR_Camera>());
  169. DestroyImmediate(go.GetComponent<SteamVR_Fade>());
  170. cam = go.GetComponent<Camera>();
  171. cam.stereoTargetEye = StereoTargetEyeMask.None;
  172. cam.fieldOfView = config.fov;
  173. cam.useOcclusionCulling = false;
  174. cam.enabled = false; // manually rendered
  175. cam.rect = new Rect(0, 0, 1, 1); //fix order of operations issue
  176. colorMat = new Material(Shader.Find("Custom/SteamVR_ColorOut"));
  177. alphaMat = new Material(Shader.Find("Custom/SteamVR_AlphaOut"));
  178. clipMaterial = new Material(Shader.Find("Custom/SteamVR_ClearAll"));
  179. var offset = go.transform;
  180. offset.parent = transform;
  181. offset.localPosition = new Vector3(config.x, config.y, config.z);
  182. offset.localRotation = Quaternion.Euler(config.rx, config.ry, config.rz);
  183. offset.localScale = Vector3.one;
  184. // Strip children of cloned object (AudioListener in particular).
  185. while (offset.childCount > 0)
  186. DestroyImmediate(offset.GetChild(0).gameObject);
  187. // Setup clipping quad (using camera clip causes problems with shadows).
  188. clipQuad = GameObject.CreatePrimitive(PrimitiveType.Quad);
  189. clipQuad.name = "ClipQuad";
  190. DestroyImmediate(clipQuad.GetComponent<MeshCollider>());
  191. var clipRenderer = clipQuad.GetComponent<MeshRenderer>();
  192. clipRenderer.material = clipMaterial;
  193. clipRenderer.shadowCastingMode = ShadowCastingMode.Off;
  194. clipRenderer.receiveShadows = false;
  195. clipRenderer.lightProbeUsage = LightProbeUsage.Off;
  196. clipRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
  197. var clipTransform = clipQuad.transform;
  198. clipTransform.parent = offset;
  199. clipTransform.localScale = new Vector3(1000.0f, 1000.0f, 1.0f);
  200. clipTransform.localRotation = Quaternion.identity;
  201. clipQuad.SetActive(false);
  202. }
  203. public float GetTargetDistance()
  204. {
  205. if (target == null)
  206. return config.near + 0.01f;
  207. var offset = cam.transform;
  208. var forward = new Vector3(offset.forward.x, 0.0f, offset.forward.z).normalized;
  209. var targetPos = target.position + new Vector3(target.forward.x, 0.0f, target.forward.z).normalized * config.hmdOffset;
  210. var distance = -(new Plane(forward, targetPos)).GetDistanceToPoint(offset.position);
  211. return Mathf.Clamp(distance, config.near + 0.01f, config.far - 0.01f);
  212. }
  213. Material colorMat, alphaMat;
  214. public void RenderNear()
  215. {
  216. var w = Screen.width / 2;
  217. var h = Screen.height / 2;
  218. if (cam.targetTexture == null || cam.targetTexture.width != w || cam.targetTexture.height != h)
  219. {
  220. var tex = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32);
  221. tex.antiAliasing = QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing;
  222. cam.targetTexture = tex;
  223. }
  224. cam.nearClipPlane = config.near;
  225. cam.farClipPlane = config.far;
  226. var clearFlags = cam.clearFlags;
  227. var backgroundColor = cam.backgroundColor;
  228. cam.clearFlags = CameraClearFlags.Color;
  229. cam.backgroundColor = Color.clear;
  230. clipMaterial.color = new Color(config.r, config.g, config.b, config.a);
  231. float dist = Mathf.Clamp(GetTargetDistance() + config.nearOffset, config.near, config.far);
  232. var clipParent = clipQuad.transform.parent;
  233. clipQuad.transform.position = clipParent.position + clipParent.forward * dist;
  234. MonoBehaviour[] behaviours = null;
  235. bool[] wasEnabled = null;
  236. if (config.disableStandardAssets)
  237. {
  238. behaviours = cam.gameObject.GetComponents<MonoBehaviour>();
  239. wasEnabled = new bool[behaviours.Length];
  240. for (int i = 0; i < behaviours.Length; i++)
  241. {
  242. var behaviour = behaviours[i];
  243. if (behaviour.enabled && behaviour.GetType().ToString().StartsWith("UnityStandardAssets."))
  244. {
  245. behaviour.enabled = false;
  246. wasEnabled[i] = true;
  247. }
  248. }
  249. }
  250. clipQuad.SetActive(true);
  251. cam.Render();
  252. Graphics.DrawTexture(new Rect(0, 0, w, h), cam.targetTexture, colorMat);
  253. // Re-render scene with post-processing fx disabled (if necessary) since they override alpha.
  254. var pp = cam.gameObject.GetComponent("PostProcessingBehaviour") as MonoBehaviour;
  255. if ((pp != null) && pp.enabled)
  256. {
  257. pp.enabled = false;
  258. cam.Render();
  259. pp.enabled = true;
  260. }
  261. Graphics.DrawTexture(new Rect(w, 0, w, h), cam.targetTexture, alphaMat);
  262. // Restore settings.
  263. clipQuad.SetActive(false);
  264. if (behaviours != null)
  265. {
  266. for (int i = 0; i < behaviours.Length; i++)
  267. {
  268. if (wasEnabled[i])
  269. {
  270. behaviours[i].enabled = true;
  271. }
  272. }
  273. }
  274. cam.clearFlags = clearFlags;
  275. cam.backgroundColor = backgroundColor;
  276. }
  277. public void RenderFar()
  278. {
  279. cam.nearClipPlane = config.near;
  280. cam.farClipPlane = config.far;
  281. cam.Render();
  282. var w = Screen.width / 2;
  283. var h = Screen.height / 2;
  284. Graphics.DrawTexture(new Rect(0, h, w, h), cam.targetTexture, colorMat);
  285. }
  286. void OnGUI()
  287. {
  288. // Necessary for Graphics.DrawTexture to work even though we don't do anything here.
  289. }
  290. Camera[] cameras;
  291. Rect[] cameraRects;
  292. float sceneResolutionScale;
  293. void OnEnable()
  294. {
  295. // Move game view cameras to lower-right quadrant.
  296. cameras = FindObjectsOfType<Camera>();
  297. if (cameras != null)
  298. {
  299. var numCameras = cameras.Length;
  300. cameraRects = new Rect[numCameras];
  301. for (int i = 0; i < numCameras; i++)
  302. {
  303. var cam = cameras[i];
  304. cameraRects[i] = cam.rect;
  305. if (cam == this.cam)
  306. continue;
  307. if (cam.targetTexture != null)
  308. continue;
  309. if (cam.GetComponent<SteamVR_Camera>() != null)
  310. continue;
  311. cam.rect = new Rect(0.5f, 0.0f, 0.5f, 0.5f);
  312. }
  313. }
  314. if (config.sceneResolutionScale > 0.0f)
  315. {
  316. sceneResolutionScale = SteamVR_Camera.sceneResolutionScale;
  317. SteamVR_Camera.sceneResolutionScale = config.sceneResolutionScale;
  318. }
  319. AutoEnableActionSet();
  320. }
  321. private void AutoEnableActionSet()
  322. {
  323. if (autoEnableDisableActionSet)
  324. {
  325. if (cameraPose != null)
  326. {
  327. if (cameraPose.actionSet.IsActive(cameraInputSource) == false)
  328. {
  329. activatedActionSet = cameraPose.actionSet; //automatically activate the actionset if it isn't active already. (will deactivate on component disable)
  330. activatedInputSource = cameraInputSource;
  331. cameraPose.actionSet.Activate(cameraInputSource);
  332. }
  333. }
  334. }
  335. }
  336. void OnDisable()
  337. {
  338. if (autoEnableDisableActionSet)
  339. {
  340. if (activatedActionSet != null) //deactivate the action set we activated for this camera
  341. {
  342. activatedActionSet.Deactivate(activatedInputSource);
  343. activatedActionSet = null;
  344. }
  345. }
  346. // Restore game view cameras.
  347. if (cameras != null)
  348. {
  349. var numCameras = cameras.Length;
  350. for (int i = 0; i < numCameras; i++)
  351. {
  352. var cam = cameras[i];
  353. if (cam != null)
  354. cam.rect = cameraRects[i];
  355. }
  356. cameras = null;
  357. cameraRects = null;
  358. }
  359. if (config.sceneResolutionScale > 0.0f)
  360. {
  361. SteamVR_Camera.sceneResolutionScale = sceneResolutionScale;
  362. }
  363. }
  364. }
  365. }