static string[] LoadRenderModelNames()
    {
        var results = new List<string>();
        results.Add("None");

        var error = HmdError.None;
        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
                return results.ToArray();
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);
        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
                OpenVR.Shutdown();
            return results.ToArray();
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        uint count = renderModels.GetRenderModelCount();
        for (uint i = 0; i < count; i++)
        {
            var buffer = new StringBuilder();
            var requiredSize = renderModels.GetRenderModelName(i, buffer, 0);
            if (requiredSize == 0)
                continue;

            buffer.EnsureCapacity((int)requiredSize);
            renderModels.GetRenderModelName(i, buffer, requiredSize);
            results.Add(buffer.ToString());
        }

        if (!SteamVR.active)
            OpenVR.Shutdown();

        return results.ToArray();
    }
    static RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
    {
        var pRenderModel = System.IntPtr.Zero;
        if (!renderModels.LoadRenderModel(renderModelName, ref pRenderModel))
        {
            Debug.LogError("Failed to load render model " + renderModelName);
            return null;
        }

        var renderModel = (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));

        var vertices = new Vector3[renderModel.unVertexCount];
        var normals = new Vector3[renderModel.unVertexCount];
        var uv = new Vector2[renderModel.unVertexCount];

        var type = typeof(RenderModel_Vertex_t);
        for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
        {
            var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
            var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

            vertices[iVert] = new Vector3(vert.vPosition.v[0], vert.vPosition.v[1], -vert.vPosition.v[2]);
            normals[iVert] = new Vector3(vert.vNormal.v[0], vert.vNormal.v[1], -vert.vNormal.v[2]);
            uv[iVert] = new Vector2(vert.rfTextureCoord[0], vert.rfTextureCoord[1]);
        }

        int indexCount = (int)renderModel.unTriangleCount * 3;
        var indices = new short[indexCount];
        Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

        var triangles = new int[indexCount];
        for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
        {
            triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
            triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
            triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
        }

        var mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.normals = normals;
        mesh.uv = uv;
        mesh.triangles = triangles;

        mesh.Optimize();
        //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

        // Check cache before loading texture.
        var material = materials[baseName + renderModel.diffuseTextureId] as Material;
        if (material == null || material.mainTexture == null)
        {
            var pDiffuseTexture = System.IntPtr.Zero;
            if (renderModels.LoadTexture(renderModel.diffuseTextureId, ref pDiffuseTexture))
            {
                var diffuseTexture = (RenderModel_TextureMap_t)Marshal.PtrToStructure(pDiffuseTexture, typeof(RenderModel_TextureMap_t));

                var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
                Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                int iColor = 0;
                for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                {
                    for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                    {
                        var r = textureMapData[iColor++];
                        var g = textureMapData[iColor++];
                        var b = textureMapData[iColor++];
                        var a = textureMapData[iColor++];
                        colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                    }
                }

                var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.ARGB32, true);
                texture.SetPixels32(colors);
                texture.Apply();

                material = new Material(Shader.Find("Standard"));
                material.mainTexture = texture;
                //material.hideFlags = HideFlags.DontUnloadUnusedAsset;

                materials[baseName + renderModel.diffuseTextureId] = material;
            }
            else
            {
                Debug.Log("Failed to load render model texture for render model " + renderModelName);
            }
        }

        renderModels.FreeRenderModel(ref renderModel);

        return new RenderModel(mesh, material);
    }
Esempio n. 3
0
		public CVRRenderModels VRRenderModels()
		{
			CheckClear();
			if (m_pVRRenderModels == null)
			{
				var eError = EVRInitError.None;
				var pInterface = OpenVRInterop.GetGenericInterface(FnTable_Prefix+IVRRenderModels_Version, ref eError);
				if (pInterface != IntPtr.Zero && eError == EVRInitError.None)
					m_pVRRenderModels = new CVRRenderModels(pInterface);
			}
			return m_pVRRenderModels;
		}
Esempio n. 4
0
	RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
	{
        var pRenderModel = System.IntPtr.Zero;

		EVRRenderModelError error;
		while ( true )
		{
			error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
			if (error != EVRRenderModelError.Loading)
				break;

			System.Threading.Thread.Sleep(1);
		}

		if (error != EVRRenderModelError.None)
		{
			Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
			return null;
		}

        var renderModel = (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));

		var vertices = new Vector3[renderModel.unVertexCount];
		var normals = new Vector3[renderModel.unVertexCount];
		var uv = new Vector2[renderModel.unVertexCount];

		var type = typeof(RenderModel_Vertex_t);
		for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
		{
			var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
			var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

			vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
			normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
			uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
		}

		int indexCount = (int)renderModel.unTriangleCount * 3;
		var indices = new short[indexCount];
		Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

		var triangles = new int[indexCount];
		for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
		{
			triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
			triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
			triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
		}

		var mesh = new Mesh();
		mesh.vertices = vertices;
		mesh.normals = normals;
		mesh.uv = uv;
		mesh.triangles = triangles;

		mesh.Optimize();
		//mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

		// Check cache before loading texture.
		var material = materials[renderModel.diffuseTextureId] as Material;
		if (material == null || material.mainTexture == null)
		{
			var pDiffuseTexture = System.IntPtr.Zero;

			while (true)
			{
				error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
				if (error != EVRRenderModelError.Loading)
					break;

				System.Threading.Thread.Sleep(1);
			}

			if (error == EVRRenderModelError.None)
			{
				var diffuseTexture = (RenderModel_TextureMap_t)Marshal.PtrToStructure(pDiffuseTexture, typeof(RenderModel_TextureMap_t));
				var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.ARGB32, false);
				if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"))
				{
					var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
					Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

					var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
					int iColor = 0;
					for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
					{
						for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
						{
							var r = textureMapData[iColor++];
							var g = textureMapData[iColor++];
							var b = textureMapData[iColor++];
							var a = textureMapData[iColor++];
							colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
						}
					}

					texture.SetPixels32(colors);
					texture.Apply();
				}
				else
				{
					texture.Apply();

					while (true)
					{
						error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
						if (error != EVRRenderModelError.Loading)
							break;

						System.Threading.Thread.Sleep(1);
					}
				}

				material = new Material(shader != null ? shader : Shader.Find("Standard"));
				material.mainTexture = texture;
				//material.hideFlags = HideFlags.DontUnloadUnusedAsset;

				materials[renderModel.diffuseTextureId] = material;

				renderModels.FreeTexture(pDiffuseTexture);
			}
			else
			{
				Debug.Log("Failed to load render model texture for render model " + renderModelName);
			}
		}

		// Delay freeing when we can since we'll often get multiple requests for the same model right
		// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
		if (!Application.isPlaying)
			renderModels.FreeRenderModel(pRenderModel);
		else
#endif
			StartCoroutine(FreeRenderModel(pRenderModel));

		return new RenderModel(mesh, material);
	}
Esempio n. 5
0
 public void Clear()
 {
     m_pVRSystem = null;
     m_pVRChaperone = null;
     m_pVRChaperoneSetup = null;
     m_pVRCompositor = null;
     m_pVROverlay = null;
     m_pVRRenderModels = null;
     m_pVRExtendedDisplay = null;
     m_pVRSettings = null;
     m_pVRApplications = null;
 }
Esempio n. 6
0
 private SteamVR_RenderModel.RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
 {
     IntPtr zero = IntPtr.Zero;
     EVRRenderModelError eVRRenderModelError;
     while (true)
     {
         eVRRenderModelError = renderModels.LoadRenderModel_Async(renderModelName, ref zero);
         if (eVRRenderModelError != EVRRenderModelError.Loading)
         {
             break;
         }
         Thread.Sleep(1);
     }
     if (eVRRenderModelError != EVRRenderModelError.None)
     {
         UnityEngine.Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, eVRRenderModelError.ToString()));
         return null;
     }
     RenderModel_t renderModel_t = (RenderModel_t)Marshal.PtrToStructure(zero, typeof(RenderModel_t));
     Vector3[] array = new Vector3[renderModel_t.unVertexCount];
     Vector3[] array2 = new Vector3[renderModel_t.unVertexCount];
     Vector2[] array3 = new Vector2[renderModel_t.unVertexCount];
     Type typeFromHandle = typeof(RenderModel_Vertex_t);
     int num = 0;
     while ((long)num < (long)((ulong)renderModel_t.unVertexCount))
     {
         IntPtr ptr = new IntPtr(renderModel_t.rVertexData.ToInt64() + (long)(num * Marshal.SizeOf(typeFromHandle)));
         RenderModel_Vertex_t renderModel_Vertex_t = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, typeFromHandle);
         array[num] = new Vector3(renderModel_Vertex_t.vPosition.v0, renderModel_Vertex_t.vPosition.v1, -renderModel_Vertex_t.vPosition.v2);
         array2[num] = new Vector3(renderModel_Vertex_t.vNormal.v0, renderModel_Vertex_t.vNormal.v1, -renderModel_Vertex_t.vNormal.v2);
         array3[num] = new Vector2(renderModel_Vertex_t.rfTextureCoord0, renderModel_Vertex_t.rfTextureCoord1);
         num++;
     }
     int num2 = (int)(renderModel_t.unTriangleCount * 3u);
     short[] array4 = new short[num2];
     Marshal.Copy(renderModel_t.rIndexData, array4, 0, array4.Length);
     int[] array5 = new int[num2];
     int num3 = 0;
     while ((long)num3 < (long)((ulong)renderModel_t.unTriangleCount))
     {
         array5[num3 * 3] = (int)array4[num3 * 3 + 2];
         array5[num3 * 3 + 1] = (int)array4[num3 * 3 + 1];
         array5[num3 * 3 + 2] = (int)array4[num3 * 3];
         num3++;
     }
     Mesh mesh = new Mesh();
     mesh.vertices = array;
     mesh.normals = array2;
     mesh.uv = array3;
     mesh.triangles = array5;
     mesh.Optimize();
     Material material = SteamVR_RenderModel.materials[renderModel_t.diffuseTextureId] as Material;
     if (material == null || material.mainTexture == null)
     {
         IntPtr zero2 = IntPtr.Zero;
         while (true)
         {
             eVRRenderModelError = renderModels.LoadTexture_Async(renderModel_t.diffuseTextureId, ref zero2);
             if (eVRRenderModelError != EVRRenderModelError.Loading)
             {
                 break;
             }
             Thread.Sleep(1);
         }
         if (eVRRenderModelError == EVRRenderModelError.None)
         {
             RenderModel_TextureMap_t renderModel_TextureMap_t = (RenderModel_TextureMap_t)Marshal.PtrToStructure(zero2, typeof(RenderModel_TextureMap_t));
             Texture2D texture2D = new Texture2D((int)renderModel_TextureMap_t.unWidth, (int)renderModel_TextureMap_t.unHeight, TextureFormat.ARGB32, false);
             if (SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX)
             {
                 texture2D.Apply();
                 while (true)
                 {
                     eVRRenderModelError = renderModels.LoadIntoTextureD3D11_Async(renderModel_t.diffuseTextureId, texture2D.GetNativeTexturePtr());
                     if (eVRRenderModelError != EVRRenderModelError.Loading)
                     {
                         break;
                     }
                     Thread.Sleep(1);
                 }
             }
             else
             {
                 byte[] array6 = new byte[(int)(renderModel_TextureMap_t.unWidth * renderModel_TextureMap_t.unHeight * '\u0004')];
                 Marshal.Copy(renderModel_TextureMap_t.rubTextureMapData, array6, 0, array6.Length);
                 Color32[] array7 = new Color32[(int)(renderModel_TextureMap_t.unWidth * renderModel_TextureMap_t.unHeight)];
                 int num4 = 0;
                 for (int i = 0; i < (int)renderModel_TextureMap_t.unHeight; i++)
                 {
                     for (int j = 0; j < (int)renderModel_TextureMap_t.unWidth; j++)
                     {
                         byte r = array6[num4++];
                         byte g = array6[num4++];
                         byte b = array6[num4++];
                         byte a = array6[num4++];
                         array7[i * (int)renderModel_TextureMap_t.unWidth + j] = new Color32(r, g, b, a);
                     }
                 }
                 texture2D.SetPixels32(array7);
                 texture2D.Apply();
             }
             material = new Material((!(this.shader != null)) ? Shader.Find("Standard") : this.shader);
             material.mainTexture = texture2D;
             SteamVR_RenderModel.materials[renderModel_t.diffuseTextureId] = material;
             renderModels.FreeTexture(zero2);
         }
         else
         {
             UnityEngine.Debug.Log("Failed to load render model texture for render model " + renderModelName);
         }
     }
     base.StartCoroutine(this.FreeRenderModel(zero));
     return new SteamVR_RenderModel.RenderModel(mesh, material);
 }
    static RenderModel LoadRenderModel(string renderModelName)
    {
        var error = HmdError.None;
        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
                return null;
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);
        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
                OpenVR.Shutdown();
            return null;
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        var renderModel = new RenderModel_t();
        if (!renderModels.LoadRenderModel(renderModelName, ref renderModel))
        {
            Debug.LogError("Failed to load render model " + renderModelName);

            if (!SteamVR.active)
                OpenVR.Shutdown();
            return null;
        }

        var vertices = new Vector3[renderModel.unVertexCount];
        var normals = new Vector3[renderModel.unVertexCount];
        var uv = new Vector2[renderModel.unVertexCount];

        var type = typeof(RenderModel_Vertex_t);
        for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
        {
            var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
            var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

            vertices[iVert] = new Vector3(vert.vPosition.v[0], vert.vPosition.v[1], -vert.vPosition.v[2]);
            normals[iVert] = new Vector3(vert.vNormal.v[0], vert.vNormal.v[1], -vert.vNormal.v[2]);
            uv[iVert] = new Vector2(vert.rfTextureCoord[0], vert.rfTextureCoord[1]);
        }

        int indexCount = (int)renderModel.unTriangleCount * 3;
        var indices = new short[indexCount];
        Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

        var triangles = new int[indexCount];
        for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
        {
            triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
            triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
            triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
        }

        var mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.normals = normals;
        mesh.uv = uv;
        mesh.triangles = triangles;

        mesh.Optimize();
        //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

        var textureMapData = new byte[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight * 4]; // RGBA
        Marshal.Copy(renderModel.diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

        var colors = new Color32[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight];
        int iColor = 0;
        for (int iHeight = 0; iHeight < renderModel.diffuseTexture.unHeight; iHeight++)
        {
            for (int iWidth = 0; iWidth < renderModel.diffuseTexture.unWidth; iWidth++)
            {
                var r = textureMapData[iColor++];
                var g = textureMapData[iColor++];
                var b = textureMapData[iColor++];
                var a = textureMapData[iColor++];
                colors[iHeight * renderModel.diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
            }
        }

        var texture = new Texture2D(renderModel.diffuseTexture.unWidth, renderModel.diffuseTexture.unHeight, TextureFormat.ARGB32, true);
        texture.SetPixels32(colors);
        texture.Apply();

        //texture.hideFlags = HideFlags.DontUnloadUnusedAsset;

        renderModels.FreeRenderModel(ref renderModel);

        if (!SteamVR.active)
            OpenVR.Shutdown();

        return new RenderModel(mesh, texture);
    }
        public void UpdateComponents(CVRRenderModels renderModels)
        {
            if (renderModels == null)
            {
                return;
            }

            if (transform.childCount == 0)
            {
                return;
            }

            if (nameCache == null)
            {
                nameCache = new Dictionary <int, string>();
            }

            for (int childIndex = 0; childIndex < transform.childCount; childIndex++)
            {
                Transform child = transform.GetChild(childIndex);

                // Cache names since accessing an object's name allocates memory.
                string componentName;
                if (!nameCache.TryGetValue(child.GetInstanceID(), out componentName))
                {
                    componentName = child.name;
                    nameCache.Add(child.GetInstanceID(), componentName);
                }

                var componentState = new RenderModel_ComponentState_t();
                if (!renderModels.GetComponentStateForDevicePath(renderModelName, componentName, SteamVR_Input_Source.GetHandle(inputSource), ref controllerModeState, ref componentState))
                {
                    continue;
                }

                child.localPosition = componentState.mTrackingToComponentRenderModel.GetPosition();
                child.localRotation = componentState.mTrackingToComponentRenderModel.GetRotation();

                Transform attach = null;
                for (int childChildIndex = 0; childChildIndex < child.childCount; childChildIndex++)
                {
                    Transform childChild      = child.GetChild(childChildIndex);
                    int       childInstanceID = childChild.GetInstanceID();
                    string    childName;
                    if (!nameCache.TryGetValue(childInstanceID, out childName))
                    {
                        childName = childChild.name;
                        nameCache.Add(childInstanceID, componentName);
                    }

                    if (childName == SteamVR_RenderModel.k_localTransformName)
                    {
                        attach = childChild;
                    }
                }

                if (attach != null)
                {
                    attach.position = transform.TransformPoint(componentState.mTrackingToComponentLocal.GetPosition());
                    attach.rotation = transform.rotation * componentState.mTrackingToComponentLocal.GetRotation();

                    initializedAttachPoints = true;
                }

                bool visible = (componentState.uProperties & (uint)EVRComponentProperty.IsVisible) != 0;
                if (visible != child.gameObject.activeSelf)
                {
                    child.gameObject.SetActive(visible);
                }
            }
        }
        RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
        {
            var pRenderModel = System.IntPtr.Zero;

            EVRRenderModelError error;

            while (true)
            {
                error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
                if (error != EVRRenderModelError.Loading)
                {
                    break;
                }

                Sleep();
            }

            if (error != EVRRenderModelError.None)
            {
                Debug.LogError(string.Format("<b>[SteamVR]</b> Failed to load render model {0} - {1}", renderModelName, error.ToString()));
                return(null);
            }

            var renderModel = MarshalRenderModel(pRenderModel);

            var vertices = new Vector3[renderModel.unVertexCount];
            var normals  = new Vector3[renderModel.unVertexCount];
            var uv       = new Vector2[renderModel.unVertexCount];

            var type = typeof(RenderModel_Vertex_t);

            for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
            {
                var ptr  = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
                var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

                vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
                normals[iVert]  = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
                uv[iVert]       = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
            }

            int indexCount = (int)renderModel.unTriangleCount * 3;
            var indices    = new short[indexCount];

            Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

            var triangles = new int[indexCount];

            for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
            {
                triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
                triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
                triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
            }

            var mesh = new Mesh();

            mesh.vertices  = vertices;
            mesh.normals   = normals;
            mesh.uv        = uv;
            mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
            mesh.Optimize();
#endif
            //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

            // Check cache before loading texture.
            var material = materials[renderModel.diffuseTextureId] as Material;
            if (material == null || material.mainTexture == null)
            {
                var pDiffuseTexture = System.IntPtr.Zero;

                while (true)
                {
                    error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                    if (error != EVRRenderModelError.Loading)
                    {
                        break;
                    }

                    Sleep();
                }

                if (error == EVRRenderModelError.None)
                {
                    var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
                    var texture        = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
                    if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
                    {
                        texture.Apply();
                        System.IntPtr texturePointer = texture.GetNativeTexturePtr();
                        while (true)
                        {
                            error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
                            if (error != EVRRenderModelError.Loading)
                            {
                                break;
                            }

                            Sleep();
                        }
                    }
                    else
                    {
                        var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
                        Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                        var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                        int iColor = 0;
                        for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                        {
                            for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                            {
                                var r = textureMapData[iColor++];
                                var g = textureMapData[iColor++];
                                var b = textureMapData[iColor++];
                                var a = textureMapData[iColor++];
                                colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                            }
                        }

                        texture.SetPixels32(colors);
                        texture.Apply();
                    }

                    material             = new Material(shader != null ? shader : Shader.Find("Standard"));
                    material.mainTexture = texture;
                    //material.hideFlags = HideFlags.DontUnloadUnusedAsset;

                    materials[renderModel.diffuseTextureId] = material;

                    renderModels.FreeTexture(pDiffuseTexture);
                }
                else
                {
                    Debug.Log("<b>[SteamVR]</b> Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
                }
            }

            // Delay freeing when we can since we'll often get multiple requests for the same model right
            // after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                renderModels.FreeRenderModel(pRenderModel);
            }
            else
#endif
            StartCoroutine(FreeRenderModel(pRenderModel));

            return(new RenderModel(mesh, material));
        }
        IEnumerator SetModelAsync(string newRenderModelName)
        {
            meshRenderers.Clear();

            if (string.IsNullOrEmpty(newRenderModelName))
            {
                yield break;
            }

            // Preload all render models before asking for the data to create meshes.
            using (RenderModelInterfaceHolder holder = new RenderModelInterfaceHolder())
            {
                CVRRenderModels renderModels = holder.instance;
                if (renderModels == null)
                {
                    yield break;
                }

                // Gather names of render models to preload.
                string[] renderModelNames;

                uint count = renderModels.GetComponentCount(newRenderModelName);
                if (count > 0)
                {
                    renderModelNames = new string[count];

                    for (int componentIndex = 0; componentIndex < count; componentIndex++)
                    {
                        uint capacity = renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, null, 0);
                        if (capacity == 0)
                        {
                            continue;
                        }

                        var componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
                        if (renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, componentNameStringBuilder, capacity) == 0)
                        {
                            continue;
                        }

                        string componentName = componentNameStringBuilder.ToString();

                        capacity = renderModels.GetComponentRenderModelName(newRenderModelName, componentName, null, 0);
                        if (capacity == 0)
                        {
                            continue;
                        }

                        var nameStringBuilder = new System.Text.StringBuilder((int)capacity);
                        if (renderModels.GetComponentRenderModelName(newRenderModelName, componentName, nameStringBuilder, capacity) == 0)
                        {
                            continue;
                        }

                        var s = nameStringBuilder.ToString();

                        // Only need to preload if not already cached.
                        RenderModel model = models[s] as RenderModel;
                        if (model == null || model.mesh == null)
                        {
                            renderModelNames[componentIndex] = s;
                        }
                    }
                }
                else
                {
                    // Only need to preload if not already cached.
                    RenderModel model = models[newRenderModelName] as RenderModel;
                    if (model == null || model.mesh == null)
                    {
                        renderModelNames = new string[] { newRenderModelName };
                    }
                    else
                    {
                        renderModelNames = new string[0];
                    }
                }

                // Keep trying every 100ms until all components finish loading.
                while (true)
                {
                    var loading = false;
                    for (int renderModelNameIndex = 0; renderModelNameIndex < renderModelNames.Length; renderModelNameIndex++)
                    {
                        if (string.IsNullOrEmpty(renderModelNames[renderModelNameIndex]))
                        {
                            continue;
                        }

                        var pRenderModel = System.IntPtr.Zero;

                        var error = renderModels.LoadRenderModel_Async(renderModelNames[renderModelNameIndex], ref pRenderModel);
                        //Debug.Log("<b>[SteamVR]</b> renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());

                        if (error == EVRRenderModelError.Loading)
                        {
                            loading = true;
                        }
                        else if (error == EVRRenderModelError.None)
                        {
                            // Preload textures as well.
                            var renderModel = MarshalRenderModel(pRenderModel);

                            // Check the cache first.
                            var material = materials[renderModel.diffuseTextureId] as Material;
                            if (material == null || material.mainTexture == null)
                            {
                                var pDiffuseTexture = System.IntPtr.Zero;

                                error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                                //Debug.Log("<b>[SteamVR]</b> renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());

                                if (error == EVRRenderModelError.Loading)
                                {
                                    loading = true;
                                }
                            }
                        }
                    }

                    if (loading)
                    {
                        yield return(new WaitForSecondsRealtime(0.1f));
                    }
                    else
                    {
                        break;
                    }
                }
            }

            bool success = SetModel(newRenderModelName);

            this.renderModelName = newRenderModelName;
            SteamVR_Events.RenderModelLoaded.Send(this, success);
        }
Esempio n. 11
0
 public CVRRenderModels VRRenderModels()
 {
     this.CheckClear();
     if (this.m_pVRRenderModels == null)
     {
         EVRInitError eVRInitError = EVRInitError.None;
         IntPtr genericInterface = OpenVRInterop.GetGenericInterface("FnTable:IVRRenderModels_005", ref eVRInitError);
         if (genericInterface != IntPtr.Zero && eVRInitError == EVRInitError.None)
         {
             this.m_pVRRenderModels = new CVRRenderModels(genericInterface);
         }
     }
     return this.m_pVRRenderModels;
 }