BlueGit

blue-star ggj-2020

Files

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

OVRCubemapCapture.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRCubemapCapture.cs 9.4 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
17
18using UnityEngine;
19using System.Collections;
20using System.IO;
21
22/// <summary>
23/// Helper script for capture cubemap and save it into PNG or JPG file
24/// </summary>
25
26/// <description>
27/// How it works:
28/// 1) This script can be attached to a existing game object, you can also use prefab Assets\OVR\Prefabs\OVRCubemapCaptureProbe
29/// There are 2 ways to trigger a capture if you attached this script to a game object.
30/// * Automatic capturing: if [autoTriggerAfterLaunch] is true, a automatic capturing will be triggered after [autoTriggerDelay] seconds.
31/// * Keyboard trigger: press key [triggeredByKey], a capturing will be triggered.
32/// 2) If you like to trigger the screen capture in your code logic, just call static function [OVRCubemapCapture.TriggerCubemapCapture] with proper input arguments.
33/// </description>
34
35public class OVRCubemapCapture : MonoBehaviour
36{
37 /// <summary>
38 /// Enable the automatic screenshot trigger, which will capture a cubemap after autoTriggerDelay (seconds)
39 /// </summary>
40 public bool autoTriggerAfterLaunch = true;
41 public float autoTriggerDelay = 1.0f;
42 private float autoTriggerElapse = 0.0f;
43
44 /// <summary>
45 /// Trigger cubemap screenshot if user pressed key triggeredByKey
46 /// </summary>
47 public KeyCode triggeredByKey = KeyCode.F8;
48
49 /// <summary>
50 /// The complete file path for saving the cubemap screenshot, including the filename and extension
51 /// if pathName is blank, screenshots will be saved into %USERPROFILE%\Documents\OVR_ScreenShot360
52 /// </summary>
53 public string pathName;
54
55 /// <summary>
56 /// The cube face resolution
57 /// </summary>
58 public int cubemapSize = 2048;
59
60 // Update is called once per frame
61 void Update()
62 {
63 // Trigger after autoTriggerDelay
64 if (autoTriggerAfterLaunch)
65 {
66 autoTriggerElapse += Time.deltaTime;
67 if (autoTriggerElapse >= autoTriggerDelay)
68 {
69 autoTriggerAfterLaunch = false;
70 TriggerCubemapCapture(transform.position, cubemapSize, pathName);
71 }
72 }
73
74 // Trigger by press triggeredByKey
75 if ( Input.GetKeyDown( triggeredByKey ) )
76 {
77 TriggerCubemapCapture(transform.position, cubemapSize, pathName);
78 }
79 }
80
81 /// <summary>
82 /// Generate unity cubemap at specific location and save into JPG/PNG
83 /// </summary>
84 /// <description>
85 /// Default save folder: your app's persistentDataPath
86 /// Default file name: using current time OVR_hh_mm_ss.png
87 /// Note1: this will take a few seconds to finish
88 /// Note2: if you only want to specify path not filename, please end [pathName] with "/"
89 /// </description>
90
91 public static void TriggerCubemapCapture(Vector3 capturePos, int cubemapSize = 2048, string pathName = null)
92 {
93 GameObject ownerObj = new GameObject("CubemapCamera", typeof(Camera));
94 ownerObj.hideFlags = HideFlags.HideAndDontSave;
95 ownerObj.transform.position = capturePos;
96 ownerObj.transform.rotation = Quaternion.identity;
97 Camera camComponent = ownerObj.GetComponent<Camera>();
98 camComponent.farClipPlane = 10000.0f;
99 camComponent.enabled = false;
100
101 Cubemap cubemap = new Cubemap(cubemapSize, TextureFormat.RGB24, false);
102 RenderIntoCubemap(camComponent, cubemap);
103 SaveCubemapCapture(cubemap, pathName);
104 DestroyImmediate(cubemap);
105 DestroyImmediate(ownerObj);
106 }
107
108
109 public static void RenderIntoCubemap(Camera ownerCamera, Cubemap outCubemap)
110 {
111 int width = (int)outCubemap.width;
112 int height = (int)outCubemap.height;
113
114 CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
115 Vector3[] faceAngles = new Vector3[] { new Vector3(0.0f, 90.0f, 0.0f), new Vector3(0.0f, -90.0f, 0.0f), new Vector3(-90.0f, 0.0f, 0.0f), new Vector3(90.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 180.0f, 0.0f) };
116
117 // Backup states
118 RenderTexture backupRenderTex = RenderTexture.active;
119 float backupFieldOfView = ownerCamera.fieldOfView;
120 float backupAspect = ownerCamera.aspect;
121 Quaternion backupRot = ownerCamera.transform.rotation;
122 //RenderTexture backupRT = ownerCamera.targetTexture;
123
124 // Enable 8X MSAA
125 RenderTexture faceTexture = new RenderTexture(width, height, 24);
126 faceTexture.antiAliasing = 8;
127 faceTexture.dimension = UnityEngine.Rendering.TextureDimension.Tex2D;
128 faceTexture.hideFlags = HideFlags.HideAndDontSave;
129
130 // For intermediate saving
131 Texture2D swapTex = new Texture2D(width, height, TextureFormat.RGB24, false);
132 swapTex.hideFlags = HideFlags.HideAndDontSave;
133
134 // Capture 6 Directions
135 ownerCamera.targetTexture = faceTexture;
136 ownerCamera.fieldOfView = 90;
137 ownerCamera.aspect = 1.0f;
138
139 Color[] mirroredPixels = new Color[swapTex.height * swapTex.width];
140 for (int i = 0; i < faces.Length; i++)
141 {
142 ownerCamera.transform.eulerAngles = faceAngles[i];
143 ownerCamera.Render();
144 RenderTexture.active = faceTexture;
145 swapTex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
146
147 // Mirror vertically to meet the standard of unity cubemap
148 Color[] OrignalPixels = swapTex.GetPixels();
149 for (int y1 = 0; y1 < height; y1++)
150 {
151 for (int x1 = 0; x1 < width; x1++)
152 {
153 mirroredPixels[y1 * width + x1] = OrignalPixels[((height - 1 - y1) * width) + x1];
154 }
155 };
156 outCubemap.SetPixels(mirroredPixels, faces[i]);
157 }
158
159 outCubemap.SmoothEdges();
160
161 // Restore states
162 RenderTexture.active = backupRenderTex;
163 ownerCamera.fieldOfView = backupFieldOfView;
164 ownerCamera.aspect = backupAspect;
165 ownerCamera.transform.rotation = backupRot;
166 ownerCamera.targetTexture = backupRenderTex;
167
168 DestroyImmediate(swapTex);
169 DestroyImmediate(faceTexture);
170
171 }
172
173
174 /// <summary>
175 /// Save unity cubemap into NPOT 6x1 cubemap/texture atlas in the following format PX NX PY NY PZ NZ
176 /// </summary>
177 /// <description>
178 /// Supported format: PNG/JPG
179 /// Default file name: using current time OVR_hh_mm_ss.png
180 /// </description>
181
182 public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
183 {
184 string fileName;
185 string dirName;
186 int width = cubemap.width;
187 int height = cubemap.height;
188 int x = 0;
189 int y = 0;
190 bool saveToPNG = true;
191
192 if (string.IsNullOrEmpty(pathName))
193 {
194 dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
195 fileName = null;
196 }
197 else
198 {
199 dirName = Path.GetDirectoryName(pathName);
200 fileName = Path.GetFileName(pathName);
201
202 if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
203 dirName += "/";
204 }
205
206 if (string.IsNullOrEmpty(fileName))
207 fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";
208
209 string extName = Path.GetExtension(fileName);
210 if (extName == ".png")
211 {
212 saveToPNG = true;
213 }
214 else if (extName == ".jpg")
215 {
216 saveToPNG = false;
217 }
218 else
219 {
220 Debug.LogError("Unsupported file format" + extName);
221 return false;
222 }
223
224 // Validate path
225 try
226 {
227 System.IO.Directory.CreateDirectory(dirName);
228 }
229 catch (System.Exception e)
230 {
231 Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
232 return false;
233 }
234
235
236 // Create the new texture
237 Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
238 if (tex == null)
239 {
240 Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
241 return false;
242 }
243
244 // Merge all the cubemap faces into the texture
245 // Reference cubemap format: http://docs.unity3d.com/Manual/class-Cubemap.html
246 CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
247 for (int i = 0; i < faces.Length; i++)
248 {
249 // get the pixels from the cubemap
250 Color[] srcPixels = null;
251 Color[] pixels = cubemap.GetPixels(faces[i]);
252 // if desired, flip them as they are ordered left to right, bottom to top
253 srcPixels = new Color[pixels.Length];
254 for (int y1 = 0; y1 < height; y1++)
255 {
256 for (int x1 = 0; x1 < width; x1++)
257 {
258 srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
259 }
260 }
261 // Copy them to the dest texture
262 tex.SetPixels(x, y, width, height, srcPixels);
263 x += width;
264 }
265
266 try
267 {
268 // Encode the texture and save it to disk
269 byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();
270
271 System.IO.File.WriteAllBytes(dirName + fileName, bytes);
272 Debug.Log("Cubemap file created " + dirName + fileName);
273 }
274 catch (System.Exception e)
275 {
276 Debug.LogError("Failed to save cubemap file since " + e.ToString());
277 return false;
278 }
279
280 DestroyImmediate(tex);
281 return true;
282 }
283
284}