/// <summary> /// Computes and stores a texture map for the current submesh. /// </summary> private void ComputeAndStoreTextureMap() { // Check if the asset has already been processed. string assetName = textureMapAssetPrefix + GeneralToolkit.ToString(_submeshIndex); string bundledAssetName = dataHandler.GetBundledAssetName(this, assetName); string textureMapRelativePath = Path.Combine(GeneralToolkit.tempDirectoryRelativePath, bundledAssetName + ".asset"); if (dataHandler.IsAssetAlreadyProcessed(textureMapRelativePath)) { return; } // Render to the preview camera a first time to initialize all buffers correctly. _previewCameraModel.pixelResolution = _textureMapResolution; _previewCameraManager.UpdateCameraModel(_previewCameraModel, true); _previewCameraManager.RenderPreviewToTarget(ref _previewCameraManager.targetTexture, false); // Render the mesh to the preview camera's target texture. Camera.onPreCull += DrawSubmeshAsTextureMapWithCamera; _previewCameraManager.RenderPreviewToTarget(ref _previewCameraManager.targetTexture, false); Camera.onPreCull -= DrawSubmeshAsTextureMapWithCamera; // Normalize the RGB channels by the alpha channel. RenderTexture tempTex = new RenderTexture(1, 1, 0); GeneralToolkit.CreateRenderTexture(ref tempTex, _textureMapResolution, 0, RenderTextureFormat.ARGB32, false, FilterMode.Point, TextureWrapMode.Clamp); Graphics.Blit(_previewCameraManager.targetTexture, tempTex, _normalizeByAlphaMat); // Apply a morphological dilation to better handle seams in the texture map.. GeneralToolkit.RenderTextureApplyMorphologicalDilation(ref tempTex, _textureMapResolution.x / 200, ImageProcessingKernelType.Box, false); // Copy the render texture to an output texture. Texture2D outTex = new Texture2D(1, 1); GeneralToolkit.CreateTexture2D(ref outTex, _textureMapResolution, TextureFormat.RGB24, false, FilterMode.Bilinear, TextureWrapMode.Clamp, true); GeneralToolkit.CopyRenderTextureToTexture2D(tempTex, ref outTex); outTex.filterMode = FilterMode.Bilinear; outTex.anisoLevel = 3; // Destroy created objects. DestroyImmediate(tempTex); // Save a copy as a png file for visualization. string copyName = DataHandler.GetBundledAssetPrefixFromType(this.GetType()) + assetName + ".png"; GeneralToolkit.SaveTexture2DToPNG(outTex, Path.Combine(GeneralToolkit.tempDirectoryAbsolutePath, copyName)); // Create an asset from the created texture map. AssetDatabase.CreateAsset(outTex, textureMapRelativePath); AssetDatabase.Refresh(); // Set the created texture in the final array. Texture2D texAsset = AssetDatabase.LoadAssetAtPath <Texture2D>(textureMapRelativePath); textureMaps[_submeshIndex] = (Texture2D)Instantiate(texAsset); }