private void DisplayUpdateGUI() { EditorGUILayout.IntPopup(this.m_UpdateMode, CustomRenderTextureEditor.styles.updateModeStrings, CustomRenderTextureEditor.styles.updateModeValues, CustomRenderTextureEditor.styles.updateMode, new GUILayoutOption[0]); EditorGUI.indentLevel++; if (this.m_UpdateMode.intValue == 1) { EditorGUILayout.PropertyField(this.m_UpdatePeriod, CustomRenderTextureEditor.styles.updatePeriod, new GUILayoutOption[0]); } EditorGUILayout.PropertyField(this.m_DoubleBuffered, CustomRenderTextureEditor.styles.doubleBuffered, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_WrapUpdateZones, CustomRenderTextureEditor.styles.wrapUpdateZones, new GUILayoutOption[0]); bool flag = true; UnityEngine.Object[] targets = base.targets; for (int i = 0; i < targets.Length; i++) { UnityEngine.Object @object = targets[i]; CustomRenderTexture customRenderTexture = @object as CustomRenderTexture; if (customRenderTexture != null && customRenderTexture.dimension != TextureDimension.Cube) { flag = false; } } if (flag) { int num = 0; int intValue = this.m_CubeFaceMask.intValue; Rect rect = GUILayoutUtility.GetRect(0f, EditorGUIUtility.singleLineHeight * 3f + EditorGUIUtility.standardVerticalSpacing * 2f); EditorGUI.BeginProperty(rect, GUIContent.none, this.m_CubeFaceMask); Rect position = rect; position.width = 100f; position.height = EditorGUIUtility.singleLineHeight; int num2 = 0; Rect position2 = rect; EditorGUI.LabelField(position2, CustomRenderTextureEditor.styles.cubemapFacesLabel); EditorGUI.BeginChangeCheck(); for (int j = 0; j < 3; j++) { position.x = rect.x + EditorGUIUtility.labelWidth - 15f; for (int k = 0; k < 2; k++) { bool flag2 = EditorGUI.ToggleLeft(position, CustomRenderTextureEditor.styles.cubemapFaces[num2], (intValue & 1 << num2) != 0); if (flag2) { num |= 1 << num2; } num2++; position.x += 100f; } position.y += EditorGUIUtility.singleLineHeight; } if (EditorGUI.EndChangeCheck()) { this.m_CubeFaceMask.intValue = num; } EditorGUI.EndProperty(); } EditorGUILayout.IntPopup(this.m_UpdateZoneSpace, CustomRenderTextureEditor.styles.updateZoneSpaceStrings, CustomRenderTextureEditor.styles.updateZoneSpaceValues, CustomRenderTextureEditor.styles.updateZoneSpace, new GUILayoutOption[0]); if (!this.multipleEditing) { Rect rect2 = GUILayoutUtility.GetRect(0f, this.m_RectList.GetHeight() + 16f, new GUILayoutOption[] { GUILayout.ExpandWidth(true) }); float num3 = 15f; rect2.x += num3; rect2.width -= num3; this.m_RectList.DoList(rect2); } else { EditorGUILayout.HelpBox("Update Zones cannot be changed while editing multiple Custom Textures.", MessageType.Info); } EditorGUI.indentLevel--; }
public static Texture DuplicateTexture(Texture source, bool copyContent = true) { TextureCreationFlags flags = source.mipmapCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; switch (source) { case Texture2D t2D: var new2D = new Texture2D(t2D.width, t2D.height, t2D.graphicsFormat, t2D.mipmapCount, flags); CopyCommonTextureSettings(source, new2D); if (copyContent) { for (int mipLevel = 0; mipLevel < t2D.mipmapCount; mipLevel++) { new2D.SetPixelData(t2D.GetPixelData <byte>(mipLevel), mipLevel); } } return(new2D); case Texture3D t3D: var new3D = new Texture3D(t3D.width, t3D.height, t3D.depth, t3D.graphicsFormat, flags, t3D.mipmapCount); CopyCommonTextureSettings(source, new3D); if (copyContent) { for (int mipLevel = 0; mipLevel < t3D.mipmapCount; mipLevel++) { new3D.SetPixelData(t3D.GetPixelData <byte>(mipLevel), mipLevel); } } return(new3D); case Cubemap cube: var newCube = new Cubemap(cube.width, cube.graphicsFormat, flags, cube.mipmapCount); CopyCommonTextureSettings(source, newCube); if (copyContent) { for (int slice = 0; slice < 6; slice++) { for (int mipLevel = 0; mipLevel < cube.mipmapCount; mipLevel++) { newCube.SetPixelData(cube.GetPixelData <byte>(mipLevel, (CubemapFace)slice), mipLevel, (CubemapFace)slice); } } } return(newCube); case CustomRenderTexture rt: var newRT = new CustomRenderTexture(rt.width, rt.height, rt.graphicsFormat); newRT.dimension = rt.dimension; newRT.depth = rt.depth; newRT.volumeDepth = rt.volumeDepth; CopyCommonTextureSettings(source, newRT); newRT.enableRandomWrite = rt.enableRandomWrite; if (copyContent) { for (int slice = 0; slice < TextureUtils.GetSliceCount(rt); slice++) { for (int mipLevel = 0; mipLevel < rt.mipmapCount; mipLevel++) { Graphics.CopyTexture(rt, slice, mipLevel, newRT, slice, mipLevel); } } } return(newRT); default: throw new System.Exception("Can't duplicate texture of type " + source.GetType()); } void CopyCommonTextureSettings(Texture source, Texture destination) { destination.name = source.name; destination.wrapMode = source.wrapMode; destination.filterMode = source.filterMode; destination.wrapModeU = source.wrapModeU; destination.wrapModeV = source.wrapModeV; destination.wrapModeW = source.wrapModeW; destination.anisoLevel = source.anisoLevel; } }
void OnRenderImage(RenderTexture src, RenderTexture dest) { if (cameraSet == CameraSet.test) { //Graphics.Blit(src, dest, mtest); //return; if (cbuf == null) { DestroyImmediate(cbuf); cbuf = new CustomRenderTexture(src.width, src.height, RenderTextureFormat.Depth); cbuf.doubleBuffered = true; cbuf.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(src, cbuf); Debug.Log("first frame"); Graphics.Blit(cbuf, dest); return; } // Graphics.Blit(cbuffer, scbuffer); mtest.SetFloat("_BlurAmount", acc); mtest.SetTexture("_OldFrame", cbuf); mtest.SetTexture("_CurFrame", src); Graphics.Blit(src, cbuf, mtest); Graphics.Blit(cbuf, dest); return; } if (cbuffer == null) { DestroyImmediate(cbuffer); cbuffer = new RenderTexture(src.width, src.height, 0); cbuffer.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(src, cbuffer); DestroyImmediate(scbuffer); scbuffer = new RenderTexture(src.width, src.height, 0); scbuffer.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(src, scbuffer); } if (dbuffer == null) { DestroyImmediate(dbuffer); //GraphicsFormat.R32G32B32A32_SFloat //GraphicsFormat. dbuffer = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGBFloat); dbuffer.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(src, dbuffer, mDepth); //mDepthBuffer.SetTexture("_DepthBuffer",dbuffer); //mDepthBuffer.SetFloat("_Num",frames); //Graphics.Blit(src,dbuffer,mDepthBuffer); DestroyImmediate(sdbuffer); sdbuffer = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGBFloat); sdbuffer.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(dbuffer, sdbuffer); } if (mDepthBuffer != null && mColorBuffer != null) { Graphics.Blit(dbuffer, sdbuffer); mDepthBuffer.SetTexture("_DepthBuffer", sdbuffer); mDepthBuffer.SetFloat("_Num", frames); Graphics.Blit(src, dbuffer, mDepthBuffer); Graphics.Blit(cbuffer, scbuffer); mColorBuffer.SetTexture("_DepthBuffer", dbuffer); mColorBuffer.SetTexture("_CurFrame", src); mColorBuffer.SetTexture("_OldFrame", scbuffer); mColorBuffer.SetFloat("_AccumOrig", acc); Graphics.Blit(src, cbuffer, mColorBuffer); if (cameraSet == CameraSet.deleteFrame) { if (timer < 1) { timer += (1 / frames); } else { Graphics.Blit(cbuffer, dest); timer = 0; } } else if (cameraSet == CameraSet.normel) { Graphics.Blit(cbuffer, dest); } } else { Graphics.Blit(src, dest); } }
public static void UpdateCustomRenderTexture(CommandBuffer cmd, CustomRenderTexture crt, int updateCount, int mipLevel = 0, MaterialPropertyBlock block = null) { // Prepare "self" texture for reading in the shader for double buffered custom textures RenderTexture textureSelf2D = null; RenderTexture textureSelf3D = null; RenderTexture textureSelfCube = null; if (crt.doubleBuffered) { if (crt.dimension == TextureDimension.Tex2D) { textureSelf2D = crt; } if (crt.dimension == TextureDimension.Cube) { textureSelfCube = crt; } if (crt.dimension == TextureDimension.Tex3D) { textureSelf3D = crt; } } if (crt.doubleBuffered) { // Update the internal double buffered render texture (resize / alloc / ect.) crt.EnsureDoubleBufferConsistency(); } if (block == null) { block = new MaterialPropertyBlock(); } // If the user didn't called the update on CRT, we still process it because it's realtime for (int i = 0; i < updateCount; i++) { // TODO: cache everything List <CustomRenderTextureUpdateZone> updateZones = new List <CustomRenderTextureUpdateZone>(); crt.GetUpdateZones(updateZones); if (updateZones.Count == 0) { updateZones.Add(new CustomRenderTextureUpdateZone { needSwap = false, updateZoneCenter = new Vector3(0.5f, 0.5f, 0.5f), updateZoneSize = Vector3.one, rotation = 0, passIndex = 0 }); } foreach (var zone in updateZones) { var zoneCenters = updateZones.Select(z => new Vector4(z.updateZoneCenter.x, z.updateZoneCenter.y, z.updateZoneCenter.z, 0)).ToList(); var zoneSizesAndRotation = updateZones.Select(z => new Vector4(z.updateZoneSize.x, z.updateZoneSize.y, z.updateZoneSize.z, z.rotation)).ToList(); var zonePrimitiveIDs = Enumerable.Range(0, updateZones.Count).Select(j => (float)j).ToList();// updateZones.Select(z => 0.0f).ToList(); int sliceCount = GetSliceCount(crt, mipLevel); // Copy all the slices in case the texture is double buffered if (zone.needSwap) { var doubleBuffer = crt.GetDoubleBufferRenderTexture(); if (doubleBuffer != null) { // For now, it's just a copy, once we actually do the swap of pointer, be careful to reset the Active Render Texture for (int sliceIndex = 0; sliceIndex < sliceCount; sliceIndex++) { cmd.CopyTexture(doubleBuffer, sliceIndex, crt, sliceIndex); } } } for (int slice = 0; slice < sliceCount; slice++) { RenderTexture renderTexture = crt.doubleBuffered ? crt.GetDoubleBufferRenderTexture() : crt; cmd.SetRenderTarget(renderTexture, mipLevel, (crt.dimension == TextureDimension.Cube) ? (CubemapFace)slice : CubemapFace.Unknown, (crt.dimension == TextureDimension.Tex3D) ? slice : 0); cmd.SetViewport(new Rect(0, 0, Mathf.Max(1, crt.width >> mipLevel), Mathf.Max(1, crt.height >> mipLevel))); block.SetVector(kCustomRenderTextureInfo, GetTextureInfos(crt, slice, mipLevel)); block.SetVector(kCustomRenderTextureParameters, GetTextureParameters(crt, slice, mipLevel)); block.SetFloat(kMipLevel, mipLevel); if (textureSelf2D != null) { block.SetTexture(kSelf2D, textureSelf2D); } if (textureSelf3D != null) { block.SetTexture(kSelf3D, textureSelf3D); } if (textureSelfCube != null) { block.SetTexture(kSelfCube, textureSelfCube); } int passIndex = zone.passIndex == -1 ? 0 : zone.passIndex; block.SetVectorArray(kUpdateDataCenters, zoneCenters); block.SetVectorArray(kUpdateDataSizesAndRotation, zoneSizesAndRotation); block.SetFloatArray(kUpdateDataPrimitiveIDs, zonePrimitiveIDs); cmd.DrawProcedural(Matrix4x4.identity, crt.material, passIndex, MeshTopology.Triangles, 6 * updateZones.Count, 1, block); } } } }
protected bool UpdateTempRenderTexture(ref CustomRenderTexture target, bool hasMips = false, bool autoGenerateMips = false, CustomRenderTextureUpdateMode updateMode = CustomRenderTextureUpdateMode.OnDemand, bool depthBuffer = false, GraphicsFormat overrideGraphicsFormat = GraphicsFormat.None) { if (graph.mainOutputTexture == null) { return(false); } bool changed = false; int outputWidth = rtSettings.GetWidth(graph); int outputHeight = rtSettings.GetHeight(graph); int outputDepth = rtSettings.GetDepth(graph); GraphicsFormat targetFormat = overrideGraphicsFormat != GraphicsFormat.None ? overrideGraphicsFormat : rtSettings.GetGraphicsFormat(graph); TextureDimension dimension = GetTempTextureDimension(); outputWidth = Mathf.Max(outputWidth, 1); outputHeight = Mathf.Max(outputHeight, 1); outputDepth = Mathf.Max(outputDepth, 1); if (dimension == TextureDimension.Cube) { outputHeight = outputDepth = outputWidth; // we only use the width for cubemaps } if (targetFormat == GraphicsFormat.None) { targetFormat = graph.mainOutputTexture.graphicsFormat; } if (dimension == TextureDimension.None) { dimension = TextureDimension.Tex2D; } if (target == null) { target = new CustomRenderTexture(outputWidth, outputHeight, targetFormat) { volumeDepth = Math.Max(1, outputDepth), depth = depthBuffer ? 32 : 0, dimension = dimension, name = $"Mixture Temp {name}", updateMode = CustomRenderTextureUpdateMode.OnDemand, doubleBuffered = rtSettings.doubleBuffered, wrapMode = rtSettings.wrapMode, filterMode = rtSettings.filterMode, useMipMap = hasMips, autoGenerateMips = autoGenerateMips, enableRandomWrite = true, hideFlags = HideFlags.HideAndDontSave, updatePeriod = GetUpdatePeriod(), }; target.Create(); target.material = MixtureUtils.dummyCustomRenderTextureMaterial; return(true); } // TODO: check if format is supported by current system // Warning: here we use directly the settings from the if (target.width != Math.Max(1, outputWidth) || target.height != Math.Max(1, outputHeight) || target.graphicsFormat != targetFormat || target.dimension != dimension || target.volumeDepth != outputDepth || target.filterMode != rtSettings.filterMode || target.doubleBuffered != rtSettings.doubleBuffered || target.wrapMode != rtSettings.wrapMode || target.useMipMap != hasMips || target.autoGenerateMips != autoGenerateMips || target.updatePeriod != GetUpdatePeriod()) { target.Release(); target.width = Math.Max(1, outputWidth); target.height = Math.Max(1, outputHeight); target.graphicsFormat = (GraphicsFormat)targetFormat; target.dimension = dimension; target.volumeDepth = outputDepth; target.doubleBuffered = rtSettings.doubleBuffered; target.wrapMode = rtSettings.wrapMode; target.filterMode = rtSettings.filterMode; target.useMipMap = hasMips; target.autoGenerateMips = autoGenerateMips; target.enableRandomWrite = true; target.updatePeriod = GetUpdatePeriod(); target.hideFlags = HideFlags.HideAndDontSave; target.Create(); if (target.material == null) { target.material = MixtureUtils.dummyCustomRenderTextureMaterial; } changed = true; } // Patch update mode based on graph type target.updateMode = updateMode; if (target.doubleBuffered) { target.EnsureDoubleBufferConsistency(); var rt = target.GetDoubleBufferRenderTexture(); if (rt.enableRandomWrite != true) { rt.Release(); rt.enableRandomWrite = true; rt.Create(); } } if (target.IsCreated()) { target.Create(); } return(changed); }
// CustomRenderTexture.Initialize have been called by the user static void OnInitializeCalled(CustomRenderTexture crt) { needsInitialization.Add(crt); customRenderTextureLastUpdateTime.Remove(crt); }
static void OnCRTUnloaded(CustomRenderTexture crt) { customRenderTextures.Remove(crt); customRenderTextureLastUpdateTime.Remove(crt); }
protected override bool ProcessNode() { if (graph.outputTexture == null) { Debug.LogError("Output Node can't write to target texture, Graph references a null output texture"); return(false); } // Update the renderTexture reference for realtime graph if (graph.isRealtime) { if (tempRenderTexture != graph.outputTexture) { onTempRenderTextureUpdated?.Invoke(); } tempRenderTexture = graph.outputTexture as CustomRenderTexture; } var inputPort = GetPort(nameof(input), nameof(input)); if (inputPort.GetEdges().Count == 0) { if (uniqueMessages.Add("OutputNotConnected")) { AddMessage("Output node input is not connected", NodeMessageType.Warning); } input = TextureUtils.GetBlackTexture(rtSettings); // TODO: set a black texture of texture dimension as default value return(false); } else { uniqueMessages.Clear(); ClearMessages(); } // Update the renderTexture size and format: if (UpdateTempRenderTexture(ref tempRenderTexture)) { onTempRenderTextureUpdated?.Invoke(); } if (input.dimension != graph.outputTexture.dimension) { Debug.LogError("Error: Expected texture type input for the OutputNode is " + graph.outputTexture.dimension + " but " + input?.dimension + " was provided"); return(false); } MixtureUtils.SetupDimensionKeyword(finalCopyMaterial, input.dimension); // Manually reset all texture inputs ResetMaterialPropertyToDefault(finalCopyMaterial, "_Source_2D"); ResetMaterialPropertyToDefault(finalCopyMaterial, "_Source_3D"); ResetMaterialPropertyToDefault(finalCopyMaterial, "_Source_Cube"); if (input.dimension == TextureDimension.Tex2D) { finalCopyMaterial.SetTexture("_Source_2D", input); } else if (input.dimension == TextureDimension.Tex3D) { finalCopyMaterial.SetTexture("_Source_3D", input); } else { finalCopyMaterial.SetTexture("_Source_Cube", input); } tempRenderTexture.material = finalCopyMaterial; return(true); }
public void OnGUI() { if (GUILayout.Button("reset noise")) { NoiseTexGenerator.Init(); } CustomRenderTexture[] crtList = new CustomRenderTexture[NoiseTexGenerator.NOISE_NUM]; for (int i = 0; i < NoiseTexGenerator.NOISE_NUM; i++) { GUILayout.BeginArea(new Rect(10 + 310 * i, 10, 300, 800)); crtList[i] = DrawNoiseArea(i); GUILayout.EndArea(); } GUILayout.BeginArea(new Rect(10 + 310 * NoiseTexGenerator.NOISE_NUM, 10, 550, 800)); CustomRenderTexture noiseTex = NoiseTexGenerator.t_Blend3D; for (int i = 0; i < NoiseTexGenerator.NOISE_NUM; i++) { noiseTex.material.SetTexture("_MainTex" + i, crtList[i]); } if (true) { PreviewTex3dMat[NoiseTexGenerator.NOISE_NUM].SetTexture("_Volume", noiseTex); Rect rect = new Rect(texShowerRect.x + 300 * NoiseTexGenerator.NOISE_NUM, texShowerRect.y, texShowerRect.width, texShowerRect.height); Texture t = DrawTexture3DPreview(noiseTex, rect, BackgroundGuiStyle, PreviewTex3dMat[NoiseTexGenerator.NOISE_NUM]); GUI.DrawTexture(texShowerRect, t, ScaleMode.ScaleToFit, false); } GUILayout.BeginArea(new Rect(10, 300, 280, 500)); tex3DBlend_Z = EditorGUILayout.Slider("Z:", tex3DBlend_Z, -2, 2); PreviewTex3dMat[NoiseTexGenerator.NOISE_NUM].SetFloat("_Z", tex3DBlend_Z); blendMaterial = EditorGUILayout.ObjectField(blendMaterial, typeof(Material), false) as Material; if (blendMaterial != null) { noiseTex.material = blendMaterial; } else { blendMaterial = noiseTex.material; } EditorGUILayout.ObjectField(noiseTex, typeof(CustomRenderTexture)); EditorGUILayout.LabelField("-------------------------------------------EXPORT------------------------------------------"); width = EditorGUILayout.IntField("Width: ", width); height = EditorGUILayout.IntField("Height: ", height); if (true) { depth = EditorGUILayout.IntSlider("Depth: ", depth, 1, Mathf.FloorToInt(SystemInfo.maxTextureSize / (float)height)); } if (true) { if (GUILayout.Button("Export Tex3D(large memory!)")) { EditorCoroutineRunner.StartEditorCoroutine(ExportTex3D(false)); } if (GUILayout.Button("Export PNG")) { EditorCoroutineRunner.StartEditorCoroutine(ExportTex3D(true)); } } else { if (GUILayout.Button("Export PNG")) { EditorCoroutineRunner.StartEditorCoroutine(Export()); } } GUILayout.EndArea(); GUILayout.EndArea(); }
public void OnGUI() { if (GUILayout.Button("reset noise")) { NoiseTexGenerator.Init(); } CustomRenderTexture noiseTex = NoiseTexGenerator_Single.GetPreViewNoiseRT(t); if (t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D || t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D_ZLoop) { PreviewTexdMat.SetTexture("_Volume", noiseTex); Texture t = DrawTexture3DPreview(noiseTex, texShowerRect, BackgroundGuiStyle); GUI.DrawTexture(texShowerRect, t, ScaleMode.ScaleToFit, false); } else { GUI.DrawTexture(texShowerRect, noiseTex, ScaleMode.ScaleToFit, false); } for (int i = 0; i < 48; i++) { EditorGUILayout.Space(); } if (t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D || t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D_ZLoop) { tex3D_Z = EditorGUILayout.Slider("Z:", tex3D_Z, -2, 2); PreviewTexdMat.SetFloat("_Z", tex3D_Z); } else { for (int i = 0; i < 5; i++) { EditorGUILayout.Space(); } } EditorGUILayout.LabelField("--------------NoiseParam---------------"); t = (NoiseTexGenerator_Single.NoiseType)EditorGUILayout.EnumPopup("Noise Tpye: ", t); scale = EditorGUILayout.FloatField("Scale: ", scale); noiseTex.material.SetFloat("_Scale", scale); EditorGUILayout.ObjectField(noiseTex, typeof(CustomRenderTexture)); //_previewTex3dMat2 = (Material)EditorGUILayout.ObjectField(_previewTex3dMat2, typeof(Material),false); useFBM = EditorGUILayout.Toggle("Use FBM:", useFBM); if (useFBM) { noiseTex.material.EnableKeyword("_USEFBM"); octaves = EditorGUILayout.IntSlider("Octaves:", octaves, 1, 10); lacunarity = EditorGUILayout.FloatField("Lacunarity:", lacunarity); gain = EditorGUILayout.FloatField("Gain:", gain); amplitude0 = EditorGUILayout.FloatField("Amplitude0:", amplitude0); frequency0 = EditorGUILayout.FloatField("Frequency0:", frequency0); noiseTex.material.SetInt("_Octaves", octaves); noiseTex.material.SetFloat("_Lacunarity", lacunarity); noiseTex.material.SetFloat("_Gain", gain); noiseTex.material.SetFloat("_Amplitude0", amplitude0); noiseTex.material.SetFloat("_Frequency0", frequency0); } else { noiseTex.material.DisableKeyword("_USEFBM"); } //distance = EditorGUILayout.FloatField("Distance: ", distance); EditorGUILayout.LabelField("--------------EXPORT---------------"); width = EditorGUILayout.IntField("Width: ", width); height = EditorGUILayout.IntField("Height: ", height); if (t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D || t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D_ZLoop) { depth = EditorGUILayout.IntSlider("Depth: ", depth, 1, Mathf.FloorToInt(SystemInfo.maxTextureSize / (float)height)); } if (t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D || t == NoiseTexGenerator_Single.NoiseType.PerilinNoise3D_ZLoop) { if (GUILayout.Button("Export Tex3D(large memory!)")) { EditorCoroutineRunner.StartEditorCoroutine(ExportTex3D(false)); } if (GUILayout.Button("Export PNG")) { EditorCoroutineRunner.StartEditorCoroutine(ExportTex3D(true)); } } else { if (GUILayout.Button("Export PNG")) { EditorCoroutineRunner.StartEditorCoroutine(Export()); } } }
protected bool UpdateTempRenderTexture(ref CustomRenderTexture target, bool hasMips = false, bool autoGenerateMips = false) { if (graph.outputTexture == null) { return(false); } int outputWidth = rtSettings.GetWidth(graph); int outputHeight = rtSettings.GetHeight(graph); int outputDepth = rtSettings.GetDepth(graph); GraphicsFormat targetFormat = rtSettings.GetGraphicsFormat(graph); TextureDimension dimension = rtSettings.GetTextureDimension(graph); if (dimension == TextureDimension.Cube) { outputHeight = outputDepth = outputWidth; // we only use the width for cubemaps } if (targetFormat == GraphicsFormat.None) { targetFormat = graph.outputTexture.graphicsFormat; } if (dimension == TextureDimension.None) { dimension = TextureDimension.Tex2D; } if (target == null) { target = new CustomRenderTexture(outputWidth, outputHeight, targetFormat) { volumeDepth = Math.Max(1, outputDepth), dimension = dimension, name = $"Mixture Temp {name}", updateMode = CustomRenderTextureUpdateMode.OnDemand, doubleBuffered = rtSettings.doubleBuffered, wrapMode = rtSettings.wrapMode, filterMode = rtSettings.filterMode, useMipMap = hasMips, autoGenerateMips = autoGenerateMips, }; target.Create(); return(true); } // TODO: check if format is supported by current system // Warning: here we use directly the settings from the if (target.width != outputWidth || target.height != outputHeight || target.graphicsFormat != targetFormat || target.dimension != dimension || target.volumeDepth != outputDepth || target.filterMode != graph.outputTexture.filterMode || target.doubleBuffered != rtSettings.doubleBuffered || target.wrapMode != rtSettings.wrapMode || target.filterMode != rtSettings.filterMode || target.useMipMap != hasMips || target.autoGenerateMips != autoGenerateMips) { target.Release(); target.width = Math.Max(1, outputWidth); target.height = Math.Max(1, outputHeight); target.graphicsFormat = (GraphicsFormat)targetFormat; target.dimension = (TextureDimension)dimension; target.volumeDepth = outputDepth; target.doubleBuffered = rtSettings.doubleBuffered; target.wrapMode = rtSettings.wrapMode; target.filterMode = rtSettings.filterMode; target.useMipMap = hasMips; target.autoGenerateMips = autoGenerateMips; target.Create(); } return(false); }
private void Start() { _splatMap = (CustomRenderTexture)_snowTracksMaterial.GetTexture("_SplatMap"); _snowFallMat.SetTexture("_SplatMap", _splatMap); }
public void UpdateRenderInformation(CustomRenderTexture cTexture, Material wave) { mCrTexture = cTexture; mWaveMat = wave; }
public void UpdateRenderInformation(CustomRenderTexture cTexture, Material wave, Material show) { mCrTexture = cTexture; mWaveMat = wave; mSurfaceMat = show; }
private static void SaveToDisk(MenuCommand command) { CustomRenderTexture customRenderTexture = command.context as CustomRenderTexture; int width = customRenderTexture.width; int height = customRenderTexture.height; int volumeDepth = customRenderTexture.volumeDepth; bool flag = RenderTextureEditor.IsHDRFormat(customRenderTexture.format); bool flag2 = customRenderTexture.format == RenderTextureFormat.ARGBFloat || customRenderTexture.format == RenderTextureFormat.RFloat; TextureFormat format = (!flag) ? TextureFormat.RGBA32 : TextureFormat.RGBAFloat; int width2 = width; if (customRenderTexture.dimension == TextureDimension.Tex3D) { width2 = width * volumeDepth; } else if (customRenderTexture.dimension == TextureDimension.Cube) { width2 = width * 6; } Texture2D texture2D = new Texture2D(width2, height, format, false); if (customRenderTexture.dimension == TextureDimension.Tex2D) { Graphics.SetRenderTarget(customRenderTexture); texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); texture2D.Apply(); } else if (customRenderTexture.dimension == TextureDimension.Tex3D) { int num = 0; for (int i = 0; i < volumeDepth; i++) { Graphics.SetRenderTarget(customRenderTexture, 0, CubemapFace.Unknown, i); texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), num, 0); texture2D.Apply(); num += width; } } else { int num2 = 0; for (int j = 0; j < 6; j++) { Graphics.SetRenderTarget(customRenderTexture, 0, (CubemapFace)j); texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), num2, 0); texture2D.Apply(); num2 += width; } } byte[] bytes; if (flag) { bytes = texture2D.EncodeToEXR(Texture2D.EXRFlags.CompressZIP | ((!flag2) ? Texture2D.EXRFlags.None : Texture2D.EXRFlags.OutputAsFloat)); } else { bytes = texture2D.EncodeToPNG(); } UnityEngine.Object.DestroyImmediate(texture2D); string extension = (!flag) ? "png" : "exr"; string directoryName = Path.GetDirectoryName(AssetDatabase.GetAssetPath(customRenderTexture.GetInstanceID())); string text = EditorUtility.SaveFilePanel("Save Custom Texture", directoryName, customRenderTexture.name, extension); if (!string.IsNullOrEmpty(text)) { File.WriteAllBytes(text, bytes); AssetDatabase.Refresh(); } }
protected virtual void FixedUpdate() { if (texSize > .5f) { int newTexWidth = Mathf.FloorToInt(m_StartingTexSize.x * texSize); int newTexHeight = Mathf.FloorToInt(m_StartingTexSize.y * texSize); if (newTexWidth != m_TexWidth && newTexHeight != m_TexHeight) { m_TexWidth = newTexWidth; m_TexHeight = newTexHeight; CustomRenderTexture crt = new CustomRenderTexture(newTexWidth, newTexHeight, texture.format); crt.material = m_SimMaterial; crt.updateMode = texture.updateMode; crt.doubleBuffered = texture.doubleBuffered; crt.initializationMode = texture.initializationMode; crt.initializationSource = CustomRenderTextureInitializationSource.TextureAndColor; crt.initializationTexture = texture; crt.Initialize(); crt.initializationSource = texture.initializationSource; if (crt.initializationSource == CustomRenderTextureInitializationSource.Material) { crt.initializationMaterial = texture.initializationMaterial; } texture = crt; displayMaterial.mainTexture = texture; } } if (next != 0) { m_CurrentIndex = m_CurrentIndex + next; next = 0; if (m_CurrentIndex >= 16) { m_CurrentIndex = 0; } if (m_CurrentIndex < 0) { m_CurrentIndex = 15; } if (tex32 == null) { tex32 = new Texture2D(32, 32); tex32.filterMode = FilterMode.Point; presets8Colors = presets8.GetPixels(); } Color[] tex32Colors = new Color[32 * 32]; for (int i = 0; i < presets8Colors.Length; i++) { tex32Colors [i] = Color.black; } int corner = 10; for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { int ni = m_CurrentIndex; int sourceY = 31 - (ni / 4) * 8 + y; int sourceX = (ni % 4) * 8 + x; if ((x == 0 && y == 0) || (x == 7 && y == 7)) { Debug.LogFormat("{0}, {1} x {2}", m_CurrentIndex, sourceX, sourceY); } int colorIndex = (y + corner) * 32 + x + corner; tex32Colors [colorIndex] = presets8.GetPixel(sourceX, sourceY); } } tex32.SetPixels(tex32Colors); byte[] png = tex32.EncodeToPNG( ); string pngPath = "Assets/tex32.jpg"; System.IO.File.WriteAllBytes(pngPath, png); AssetDatabase.Refresh(); if (texture.initializationSource != CustomRenderTextureInitializationSource.TextureAndColor) { texture.initializationSource = CustomRenderTextureInitializationSource.TextureAndColor; } texture.initializationTexture = ( Texture2D )AssetDatabase.LoadMainAssetAtPath(pngPath);; texture.Initialize(); frameDelay = .5f; } }
/// <summary> /// Add a CRT that is not yet tracked by the manager because of the frame of delay. /// </summary> /// <param name="crt"></param> public static void RegisterNewCustomRenderTexture(CustomRenderTexture crt) { OnCRTLoaded(crt); }
void DisplayUpdateGUI() { EditorGUILayout.IntPopup(m_UpdateMode, styles.updateModeStrings, styles.updateModeValues, styles.updateMode); EditorGUI.indentLevel++; if (m_UpdateMode.intValue == (int)CustomRenderTextureUpdateMode.Realtime) { EditorGUILayout.PropertyField(m_UpdatePeriod, styles.updatePeriod); } EditorGUILayout.PropertyField(m_DoubleBuffered, styles.doubleBuffered); EditorGUILayout.PropertyField(m_WrapUpdateZones, styles.wrapUpdateZones); bool isCubemap = true; foreach (Object o in targets) { CustomRenderTexture customRenderTexture = o as CustomRenderTexture; if (customRenderTexture != null && customRenderTexture.dimension != UnityEngine.Rendering.TextureDimension.Cube) { isCubemap = false; } } if (isCubemap) { int newFaceMask = 0; int currentFaceMask = m_CubeFaceMask.intValue; var AllRects = GUILayoutUtility.GetRect(0, EditorGUIUtility.singleLineHeight * 3 + EditorGUIUtility.standardVerticalSpacing * 2); EditorGUI.BeginProperty(AllRects, GUIContent.none, m_CubeFaceMask); Rect toggleRect = AllRects; toggleRect.width = kToggleWidth; toggleRect.height = EditorGUIUtility.singleLineHeight; int faceIndex = 0; { Rect labelRect = AllRects; EditorGUI.LabelField(labelRect, styles.cubemapFacesLabel); EditorGUI.BeginChangeCheck(); for (int i = 0; i < 3; ++i) { toggleRect.x = AllRects.x + EditorGUIUtility.labelWidth - kIndentSize; { for (int j = 0; j < 2; ++j) { bool value = EditorGUI.ToggleLeft(toggleRect, styles.cubemapFaces[faceIndex], (currentFaceMask & (1 << faceIndex)) != 0); if (value) { newFaceMask |= (int)(1 << faceIndex); } faceIndex++; toggleRect.x += kToggleWidth; } } toggleRect.y += EditorGUIUtility.singleLineHeight; } if (EditorGUI.EndChangeCheck()) { m_CubeFaceMask.intValue = newFaceMask; } } EditorGUI.EndProperty(); } EditorGUILayout.IntPopup(m_UpdateZoneSpace, styles.updateZoneSpaceStrings, styles.updateZoneSpaceValues, styles.updateZoneSpace); if (!multipleEditing) { Rect listRect = GUILayoutUtility.GetRect(0.0f, m_RectList.GetHeight() + kRListAddButtonOffset, GUILayout.ExpandWidth(true)); // kRListAddButtonOffset because reorderable list does not take the +/- button at the bottom when computing its Rects making it half occulted by other GUI elements. // Reorderable list seems to not take indentLevel into account properly. float indentSize = kIndentSize; listRect.x += indentSize; listRect.width -= indentSize; m_RectList.DoList(listRect); } else { EditorGUILayout.HelpBox("Update Zones cannot be changed while editing multiple Custom Textures.", MessageType.Info); } EditorGUI.indentLevel--; }
static void InitializeCustomRenderTexture(CustomRenderTexture crt) { // Debug.Log("Load: " + crt + " | " + crt.updateMode); }
// CustomRenderTexture.Initialize have been called by the user static void OnInitializeCalled(CustomRenderTexture crt) => needsInitialization.Add(crt);
// Update one custom render texture. public static void UpdateCustomRenderTexture(CommandBuffer cmd, CustomRenderTexture crt) { bool firstPass = crt.updateCount == 0; // Handle initialization here too: if (crt.initializationMode == CustomRenderTextureUpdateMode.Realtime || needsInitialization.Contains(crt) || (firstPass && crt.initializationMode == CustomRenderTextureUpdateMode.OnLoad)) { switch (crt.initializationSource) { case CustomRenderTextureInitializationSource.Material: // TODO break; case CustomRenderTextureInitializationSource.TextureAndColor: // TODO break; } needsInitialization.Remove(crt); } needsUpdate.TryGetValue(crt, out int updateCount); if (crt.material != null && CustomRenderTextureNeedsUpdate(crt, updateCount, firstPass)) { #if CUSTOM_TEXTURE_PROFILING customRenderTextureSamplers.TryGetValue(crt, out var sampler); if (sampler == null) { sampler = customRenderTextureSamplers[crt] = CustomSampler.Create($"{crt.name} - {crt.GetInstanceID()}", true); sampler.GetRecorder().enabled = true; } cmd.BeginSample(sampler); #endif onBeforeCustomTextureUpdated?.Invoke(cmd, crt); // using (new ProfilingScope(cmd, new ProfilingSampler($"Update {crt.name}"))) { updateCount = Mathf.Max(updateCount, 1); crtExecInfo.TryGetValue(crt, out var execInfo); if (execInfo != null && execInfo.runOnAllMips) { for (int mipLevel = 0; mipLevel < crt.mipmapCount; mipLevel++) { UpdateCustomRenderTexture(cmd, crt, updateCount, mipLevel: mipLevel); } } else { UpdateCustomRenderTexture(cmd, crt, updateCount); } needsUpdate.Remove(crt); } #if CUSTOM_TEXTURE_PROFILING cmd.EndSample(sampler); #endif crt.IncrementUpdateCount(); onAfterCustomTextureUpdated?.Invoke(cmd, crt); } }
static void OnCRTUnloaded(CustomRenderTexture crt) => customRenderTextures.Remove(crt);
public static CustomSampler GetCustomTextureProfilingSampler(CustomRenderTexture crt) { customRenderTextureSamplers.TryGetValue(crt, out var sampler); return(sampler); }
// Returns user facing texture info static Vector4 GetTextureInfos(CustomRenderTexture crt, int sliceIndex) => new Vector4((float)crt.width, (float)crt.height, crt.volumeDepth, (float)sliceIndex);
private static RenderTexture Copy3DSliceToRenderTexture(int layer, int w, int h, int d, CustomRenderTexture rt3D) { RenderTexture render = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32); render.dimension = UnityEngine.Rendering.TextureDimension.Tex2D; render.enableRandomWrite = true; render.wrapMode = TextureWrapMode.Clamp; render.Create(); int kernelIndex = m_Tex3DSlices.FindKernel("CSMain"); m_Tex3DSlices.SetTexture(kernelIndex, "noise", rt3D); m_Tex3DSlices.SetInt("layer", layer); m_Tex3DSlices.SetTexture(kernelIndex, "Result", render); m_Tex3DSlices.Dispatch(kernelIndex, w, h, 1); return(render); }
// Update one custom render texture. public static void UpdateCustomRenderTexture(CommandBuffer cmd, CustomRenderTexture crt) { bool firstPass = crt.updateCount == 0; // Handle initialization here too: if (crt.initializationMode == CustomRenderTextureUpdateMode.Realtime || needsInitialization.Contains(crt) || (firstPass && crt.initializationMode == CustomRenderTextureUpdateMode.OnLoad)) { switch (crt.initializationSource) { case CustomRenderTextureInitializationSource.Material: // TODO break; case CustomRenderTextureInitializationSource.TextureAndColor: // TODO break; } needsInitialization.Remove(crt); } needsUpdate.TryGetValue(crt, out int updateCount); if (crt.material != null && (crt.updateMode == CustomRenderTextureUpdateMode.Realtime || updateCount > 0 || (firstPass && crt.updateMode == CustomRenderTextureUpdateMode.OnLoad))) { onBeforeCustomTextureUpdated?.Invoke(cmd, crt); #if CUSTOM_TEXTURE_PROFILING customRenderTextureSamplers.TryGetValue(crt, out var sampler); if (sampler == null) { sampler = customRenderTextureSamplers[crt] = CustomSampler.Create($"{crt.name} - {crt.GetInstanceID()}", true); sampler.GetRecorder().enabled = true; } cmd.BeginSample(sampler); #endif using (new ProfilingScope(cmd, new ProfilingSampler($"Update {crt.name}"))) { // Prepare "self" texture for reading in the shader for double buffered custom textures RenderTexture textureSelf2D = null; RenderTexture textureSelf3D = null; RenderTexture textureSelfCube = null; if (crt.doubleBuffered) { if (crt.dimension == TextureDimension.Tex2D) { textureSelf2D = crt; } if (crt.dimension == TextureDimension.Cube) { textureSelfCube = crt; } if (crt.dimension == TextureDimension.Tex3D) { textureSelf3D = crt; } } if (crt.doubleBuffered) { // Update the internal double buffered render texture (resize / alloc / ect.) crt.EnsureDoubleBufferConsistency(); } MaterialPropertyBlock block = new MaterialPropertyBlock(); // If the user didn't called the update on CRT, we still process it because it's realtime updateCount = Mathf.Max(updateCount, 1); for (int i = 0; i < updateCount; i++) { // TODO: cache everything List <CustomRenderTextureUpdateZone> updateZones = new List <CustomRenderTextureUpdateZone>(); crt.GetUpdateZones(updateZones); if (updateZones.Count == 0) { updateZones.Add(new CustomRenderTextureUpdateZone { needSwap = false, updateZoneCenter = new Vector3(0.5f, 0.5f, 0.5f), updateZoneSize = Vector3.one, rotation = 0, passIndex = 0 }); } foreach (var zone in updateZones) // int sliceCount = GetSliceCount(crt); // for (int slice = 0; slice < sliceCount; slice++) { var zoneCenters = updateZones.Select(z => new Vector4(z.updateZoneCenter.x, z.updateZoneCenter.y, z.updateZoneCenter.z, 0)).ToList(); var zoneSizesAndRotation = updateZones.Select(z => new Vector4(z.updateZoneSize.x, z.updateZoneSize.y, z.updateZoneSize.z, z.rotation)).ToList(); var zonePrimitiveIDs = Enumerable.Range(0, updateZones.Count).Select(j => (float)j).ToList();// updateZones.Select(z => 0.0f).ToList(); int sliceCount = GetSliceCount(crt); // Copy all the slices in case the texture is double buffered if (zone.needSwap) { var doubleBuffer = crt.GetDoubleBufferRenderTexture(); if (doubleBuffer != null) { // For now, it's just a copy, once we actually do the swap of pointer, be careful to reset the Active Render Texture for (int slice = 0; slice < sliceCount; slice++) { cmd.CopyTexture(doubleBuffer, slice, crt, slice); } } } // foreach (var zone in updateZones) for (int slice = 0; slice < sliceCount; slice++) { RenderTexture renderTexture = crt.doubleBuffered ? crt.GetDoubleBufferRenderTexture() : crt; cmd.SetRenderTarget(renderTexture, 0, (crt.dimension == TextureDimension.Cube) ? (CubemapFace)slice : 0, (crt.dimension == TextureDimension.Tex3D) ? slice : 0); cmd.SetViewport(new Rect(0, 0, crt.width, crt.height)); block.SetVector(kCustomRenderTextureInfo, GetTextureInfos(crt, slice)); block.SetVector(kCustomRenderTextureParameters, GetTextureParameters(crt, slice)); if (textureSelf2D != null) { block.SetTexture(kSelf2D, textureSelf2D); } if (textureSelf3D != null) { block.SetTexture(kSelf3D, textureSelf3D); } if (textureSelfCube != null) { block.SetTexture(kSelfCube, textureSelfCube); } int passIndex = zone.passIndex == -1 ? 0 : zone.passIndex; block.SetVectorArray(kUpdateDataCenters, zoneCenters); block.SetVectorArray(kUpdateDataSizesAndRotation, zoneSizesAndRotation); block.SetFloatArray(kUpdateDataPrimitiveIDs, zonePrimitiveIDs); cmd.DrawProcedural(Matrix4x4.identity, crt.material, passIndex, MeshTopology.Triangles, 6 * updateZones.Count, 1, block); } } } needsUpdate.Remove(crt); } #if CUSTOM_TEXTURE_PROFILING cmd.EndSample(sampler); #endif crt.IncrementUpdateCount(); } }
public static Texture2D SaveToPNG(CustomRenderTexture texture) { int width = texture.width; int height = texture.height; int depth = texture.volumeDepth; // This has its TextureFormat helper equivalent in C++ but since we are going to try to refactor TextureFormat/RenderTextureFormat into a single type so let's not bloat Scripting APIs with stuff that will get useless soon(tm). bool isFormatHDR = IsHDRFormat(texture.format); bool isFloatFormat = (texture.format == RenderTextureFormat.ARGBFloat || texture.format == RenderTextureFormat.RFloat); TextureFormat format = isFormatHDR ? TextureFormat.RGBAFloat : TextureFormat.RGBA32; int finalWidth = width; if (texture.dimension == UnityEngine.Rendering.TextureDimension.Tex3D) { finalWidth = width * depth; } else if (texture.dimension == UnityEngine.Rendering.TextureDimension.Cube) { finalWidth = width * 6; } Texture2D tex = new Texture2D(finalWidth, height, format, false); // Read screen contents into the texture if (texture.dimension == UnityEngine.Rendering.TextureDimension.Tex2D) { Graphics.SetRenderTarget(texture); tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); } else if (texture.dimension == UnityEngine.Rendering.TextureDimension.Tex3D) { int offset = 0; for (int i = 0; i < depth; ++i) { Graphics.SetRenderTarget(texture, 0, CubemapFace.Unknown, i); tex.ReadPixels(new Rect(0, 0, width, height), offset, 0); tex.Apply(); offset += width; } } else { int offset = 0; for (int i = 0; i < 6; ++i) { Graphics.SetRenderTarget(texture, 0, (CubemapFace)i); tex.ReadPixels(new Rect(0, 0, width, height), offset, 0); tex.Apply(); offset += width; } } // Encode texture into PNG byte[] bytes = null; if (isFormatHDR) { bytes = tex.EncodeToEXR(Texture2D.EXRFlags.CompressZIP | (isFloatFormat ? Texture2D.EXRFlags.OutputAsFloat : 0)); } else { bytes = tex.EncodeToPNG(); } Object.DestroyImmediate(tex); var extension = isFormatHDR ? "exr" : "png"; var directory = Application.dataPath; string assetPath = EditorUtility.SaveFilePanel("Save Custom Render Texture", directory, texture.name, extension); if (!string.IsNullOrEmpty(assetPath)) { File.WriteAllBytes(assetPath, bytes); AssetDatabase.Refresh(); } return(tex); }
public override void BlitB() { updateMat.SetTexture("_MainTex", buffer1); buffer0.Update(); currentBuffer = buffer0; }