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));
        }
Пример #2
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);
	}
        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);
        }
Пример #4
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);
 }