public void Init(int propertyCount, MStringBuilder msb, ClusterMatResources resources) { this.resources = resources; sb = msb; this.propertyCount = propertyCount; state = State.Unloaded; }
public void GenerateAsync(bool listCommand = true) { clusterBuffer = new NativeArray <CullBox>(property.clusterCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); pointsBuffer = new NativeArray <Point>(property.clusterCount * PipelineBaseBuffer.CLUSTERCLIPCOUNT, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); indicesBuffer = new NativeArray <int>(property.clusterCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); NativeList <ulong> pointerContainer = SceneController.pointerContainer; pointerContainer.AddCapacityTo(pointerContainer.Length + indicesBuffer.Length); CullBox * clusterData = clusterBuffer.Ptr(); Point * verticesData = pointsBuffer.Ptr(); const string infosPath = "Assets/BinaryData/MapInfos/"; const string pointsPath = "Assets/BinaryData/MapPoints/"; MStringBuilder sb = new MStringBuilder(pointsPath.Length + property.name.Length + ".txt".Length); allStrings[0] = infosPath; allStrings[1] = property.name; allStrings[2] = ".txt"; sb.Combine(allStrings); using (BinaryReader reader = new BinaryReader(File.Open(sb.str, FileMode.Open))) { byte[] bytes = reader.ReadBytes((int)reader.BaseStream.Length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(clusterData, b, bytes.Length); } } allStrings[0] = pointsPath; sb.Combine(allStrings); using (BinaryReader reader = new BinaryReader(File.Open(sb.str, FileMode.Open))) { byte[] bytes = reader.ReadBytes((int)reader.BaseStream.Length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(verticesData, b, bytes.Length); } } int *indicesPtr = indicesBuffer.Ptr(); LoadingCommandQueue commandQueue = SceneController.commandQueue; for (int i = 0; i < indicesBuffer.Length; ++i) { indicesPtr[i] = pointerContainer.Length; pointerContainer.Add((ulong)(indicesPtr + i)); } LoadTextures(); propertiesPool = SceneController.commonData.GetPropertyIndex(property.properties.Length); uint *poolPtr = propertiesPool.Ptr(); for (int i = 0; i < pointsBuffer.Length; ++i) { verticesData[i].objIndex = poolPtr[verticesData[i].objIndex]; } if (listCommand) { lock (commandQueue) { commandQueue.Queue(GenerateRun()); } } }
public void Init(TextureStreaming streamer, int streamingIndex, RenderTextureFormat format, MStringBuilder msb) { this.msb = msb; this.streamer = streamer; this.streamingIndex = streamingIndex; rt = new RenderTexture(new RenderTextureDescriptor { width = streamer.fixedLoadSize, height = streamer.fixedLoadSize, volumeDepth = maximumPoolCapacity, dimension = TextureDimension.Tex2DArray, depthBufferBits = 0, colorFormat = format, msaaSamples = 1, enableRandomWrite = true }); rt.filterMode = FilterMode.Bilinear; rt.wrapMode = TextureWrapMode.Repeat; rt.Create(); indexPool = new NativeList <int>(maximumPoolCapacity, maximumPoolCapacity, Allocator.Persistent); for (int i = 0; i < maximumPoolCapacity; ++i) { indexPool[i] = i; } usageCount = new NativeArray <int>(maximumPoolCapacity, Allocator.Persistent, NativeArrayOptions.ClearMemory); guidToIndex = new Dictionary <string, int>(maximumPoolCapacity); }
public static void WriteTexture(string path, string saveName, Texture rt, int2 blendTarget) { string direct = path + "/" + saveName; if (!Directory.Exists(direct)) { Directory.CreateDirectory(direct); } ComputeBuffer buffer = new ComputeBuffer(rt.width * rt.height, sizeof(float4)); ComputeShader cs = Resources.Load <ComputeShader>("ReadRTData"); cs.SetBuffer(0, "_TextureDatas", buffer); cs.SetTexture(0, "_TargetTexture", rt); cs.SetInt("_Width", rt.width); cs.SetInt("_Height", rt.height); cs.Dispatch(0, rt.width / 8, rt.height / 8, 1); MStringBuilder msb = new MStringBuilder(direct.Length + 25); msb.Add(direct); msb.Add('/'); msb.Add(blendTarget.x.ToString()); msb.Add('_'); msb.Add(blendTarget.y.ToString()); msb.Add(".bytes"); Color[] cols = new Color[buffer.count]; buffer.GetData(cols); byte[] bytes = new byte[cols.Length]; for (int i = 0; i < cols.Length; ++i) { bytes[i] = (byte)(cols[i].r * 255.99999); } File.WriteAllBytes(msb.str, bytes); }
public SceneStreaming(ClusterProperty property, int propertyCount, MStringBuilder msb, ClusterMatResources resources) { this.resources = resources; sb = msb; this.propertyCount = propertyCount; state = State.Unloaded; this.property = property; }
public void Init(MStringBuilder msb, ClusterMatResources resources) { this.resources = resources; sb = msb; state = State.Unloaded; propertyCount = propertyStaticCount; propertyStaticCount++; }
public void GenerateAsync(bool listCommand = true) { clusterBuffer = new NativeArray <CullBox>(property.clusterCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); pointsBuffer = new NativeArray <float3>(property.clusterCount * PipelineBaseBuffer.CLUSTERCLIPCOUNT, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); indicesBuffer = new NativeArray <int>(property.clusterCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); NativeList <ulong> pointerContainer = SceneController.pointerContainer; pointerContainer.AddCapacityTo(pointerContainer.Length + indicesBuffer.Length); CullBox * clusterData = clusterBuffer.Ptr(); float3 * verticesData = pointsBuffer.Ptr(); const string infosPath = "Assets/BinaryData/MapInfos/"; const string pointsPath = "Assets/BinaryData/MapPoints/"; MStringBuilder sb = new MStringBuilder(pointsPath.Length + property.name.Length + ".mpipe".Length); allStrings[0] = infosPath; allStrings[1] = property.name; allStrings[2] = ".mpipe"; sb.Combine(allStrings); // FileStream fileStream = new FileStream(sb.str, FileMode.Open, FileAccess.Read); using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(clusterData, b, length); } } allStrings[0] = pointsPath; sb.Combine(allStrings); using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(verticesData, b, length); } } int *indicesPtr = indicesBuffer.Ptr(); LoadingCommandQueue commandQueue = LoadingThread.commandQueue; for (int i = 0; i < indicesBuffer.Length; ++i) { indicesPtr[i] = pointerContainer.Length; pointerContainer.Add((ulong)(indicesPtr + i)); } if (listCommand) { lock (commandQueue) { commandQueue.Queue(GenerateRun()); } } }
//TODO public void LoadTextures() { PropertyValue[] values = property.properties; if (property.texPaths.Length > 3) { Debug.LogError("Scene: " + property.name + "'s texture type count is larger than 3! That is illegal!"); return; } for (int i = 0; i < values.Length; ++i) { ref PropertyValue value = ref values[i]; int *indexPtr = (int *)UnsafeUtility.AddressOf(ref value.textureIndex); for (int a = 0; a < property.texPaths.Length; ++a) { string texName = property.texPaths[a].instancingIDs[i]; MStringBuilder sb = new MStringBuilder(texName.Length + 50); allStrings[0] = "Assets/BinaryData/Textures/"; allStrings[1] = texName; allStrings[2] = ".txt"; sb.Combine(allStrings); string texType = property.texPaths[a].texName; bool alreadyContained; indexPtr[a] = SceneController.commonData.GetIndex(texName, out alreadyContained); if (indexPtr[a] >= 0) { if (alreadyContained) { allTextureDatas.Add(new TextureInfos { array = new NativeArray <Color32>(), index = indexPtr[a], texGUID = texName, texType = texType }); } using (BinaryReader reader = new BinaryReader(File.Open(sb.str, FileMode.Open))) { byte[] bytes = reader.ReadBytes((int)reader.BaseStream.Length); int res = SceneController.resolution; NativeArray <Color32> allColors = new NativeArray <Color32>(res * res, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); fixed(byte *source = bytes) { UnsafeUtility.MemCpy(allColors.GetUnsafePtr(), source, Mathf.Min(allColors.Length * sizeof(Color32), bytes.Length)); } allTextureDatas.Add(new TextureInfos { array = allColors, index = indexPtr[a], texGUID = texName, texType = texType }); } } } }
public void Awake() { if (!sb.isCreated) { sb = new MStringBuilder(100); } state = State.Unloaded; propertyCount = propertyStaticCount; propertyStaticCount++; originPos = transform.position; textureLoadingFlags = new NativeList <bool>(50, Allocator.Persistent); }
public void Init(PipelineResources res) { blitNormalMat = new Material(res.shaders.blitNormalShader); msbForCluster = new MStringBuilder(100); for (int i = 0; i < clusterProperties.Count; ++i) { var cur = clusterProperties[i]; cur.Init(i, msbForCluster, this); } rgbaPool.Init(0, RenderTextureFormat.ARGB32, (int)fixedTextureSize, this, false); normalPool.Init(1, RenderTextureFormat.RGHalf, (int)fixedTextureSize, this, true); emissionPool.Init(2, RenderTextureFormat.ARGBHalf, (int)fixedTextureSize, this, false); heightPool.Init(3, RenderTextureFormat.R8, (int)fixedTextureSize, this, true); vmManager = new VirtualMaterialManager(materialPoolSize, maximumMaterialCount, res.shaders.streamingShader); }
public void GenerateAsync(bool listCommand = true) { clusterBuffer = new NativeArray <Cluster>(property.clusterCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); pointsBuffer = new NativeArray <Point>(property.clusterCount * PipelineBaseBuffer.CLUSTERCLIPCOUNT, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); Cluster * clusterData = clusterBuffer.Ptr(); Point * verticesData = pointsBuffer.Ptr(); const string infosPath = "Assets/BinaryData/MapInfos/"; const string pointsPath = "Assets/BinaryData/MapPoints/"; MStringBuilder sb = new MStringBuilder(pointsPath.Length + property.name.Length + ".mpipe".Length); allStrings[0] = infosPath; allStrings[1] = property.name; allStrings[2] = ".mpipe"; sb.Combine(allStrings); // FileStream fileStream = new FileStream(sb.str, FileMode.Open, FileAccess.Read); using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(clusterData, b, length); } } allStrings[0] = pointsPath; sb.Combine(allStrings); using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); fixed(byte *b = bytes) { UnsafeUtility.MemCpy(verticesData, b, length); } } LoadingCommandQueue commandQueue = LoadingThread.commandQueue; if (listCommand) { lock (commandQueue) { commandQueue.Queue(GenerateRun()); } } }
public void Init(NativeArray <TextureFormat> allFormats, PipelineResources res) { initialized = true; mainThreadSyncEvent = new AutoResetEvent(false); commandEmptyEvent = new AutoResetEvent(false); loadedTex = new Texture2D[allFormats.Length]; for (int i = 0; i < allFormats.Length; ++i) { loadedTex[i] = new Texture2D(fixedLoadSize, fixedLoadSize / asyncFrameSlice, allFormats[i], false, true); } msb = new MStringBuilder(50); loadBytes = new byte[fixedLoadSize * fixedLoadSize * sizeof(half4)]; texStreamingThread = new Thread(() => { LoadThreadUpdate(); }); texStreamingThread.Start(); readRTShader = res.shaders.readRTData; }
public static void WriteGuide(string path, string saveName, NativeList <int2> blendTargets) { string direct = path + "/" + saveName + "/Guide.bytes"; if (!Directory.Exists(direct)) { Directory.CreateDirectory(direct); } MStringBuilder msb = new MStringBuilder(10 * blendTargets.Length); foreach (var i in blendTargets) { msb.Add(i.x.ToString()); msb.Add('_'); msb.Add(i.y.ToString()); msb.Add("\r\n"); } File.WriteAllText(direct, msb.str); }
public void Init(PipelineResources res) { allScenes = new List <SceneStreaming>(clusterProperties.Count); msbForCluster = new MStringBuilder(100); msbForTex = new MStringBuilder(100); for (int i = 0; i < clusterProperties.Count; ++i) { var cur = clusterProperties[i]; allScenes.Add(new SceneStreaming(cur, i, msbForCluster, this)); } NativeArray <TextureFormat> allFormats = new NativeArray <TextureFormat>(4, Allocator.Temp, NativeArrayOptions.UninitializedMemory); allFormats[0] = TextureFormat.RGBA32; allFormats[1] = TextureFormat.RGHalf; allFormats[2] = TextureFormat.RGBAHalf; allFormats[3] = TextureFormat.R8; texStreaming.Init(allFormats, res); rgbaPool.Init(texStreaming, 0, RenderTextureFormat.ARGB32, msbForTex); normalPool.Init(texStreaming, 1, RenderTextureFormat.RGHalf, msbForTex); emissionPool.Init(texStreaming, 2, RenderTextureFormat.ARGBHalf, msbForTex); heightPool.Init(texStreaming, 3, RenderTextureFormat.R8, msbForTex); vmManager = new VirtualMaterialManager(materialPoolSize, maximumMaterialCount, res.shaders.streamingShader); }
public void Init(PipelineResources res) { referenceCacheDict = new NativeDictionary <int4x4, int, Int4x4Equal>(200, Allocator.Persistent, new Int4x4Equal()); mipIDs = new NativeArray <int>(2, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); mipIDs[0] = Shader.PropertyToID("_Mip0"); mipIDs[1] = Shader.PropertyToID("_Mip1"); /*mipIDs[2] = Shader.PropertyToID("_Mip2"); * mipIDs[3] = Shader.PropertyToID("_Mip3"); * mipIDs[4] = Shader.PropertyToID("_Mip4"); * mipIDs[5] = Shader.PropertyToID("_Mip5");*/ msbForCluster = new MStringBuilder(100); for (int i = 0; i < clusterProperties.Count; ++i) { var cur = clusterProperties[i]; cur.Init(msbForCluster, this); } rgbaPool.Init(0, GraphicsFormat.R8G8B8A8_UNorm, (int)fixedTextureSize, this); emissionPool.Init(2, GraphicsFormat.R16G16B16A16_SFloat, (int)fixedTextureSize, this); heightPool.Init(3, GraphicsFormat.R8_UNorm, (int)fixedTextureSize, this); vmManager = new VirtualMaterialManager(materialPoolSize, maximumMaterialCount, res.shaders.streamingShader); }
private void OnEnable() { target = serializedObject.targetObject as PipelineCamera; msb = new MStringBuilder(50); }
public void GetString(MStringBuilder msb) { msb.Clear(); msb.Add((char *)ptr, CHAR_LENGTH); }
//TODO public void LoadTextures() { PropertyValue[] values = property.properties; if (property.texPaths.Length > 5) { Debug.LogError("Scene: " + property.name + "'s texture type count is larger than 5! That is illegal!"); return; } MStringBuilder sb = new MStringBuilder(150); allStrings[0] = "Assets/BinaryData/Lightmaps/"; allStrings[2] = ".mpipe"; for (int i = 0; i < property.lightmapGUIDs.Length; ++i) { LightmapPaths lightmapGUID = property.lightmapGUIDs[i]; allStrings[1] = lightmapGUID.name; sb.Combine(allStrings); bool alreadyContained; int index = SceneController.commonData.GetLightmapIndex(lightmapGUID.name, out alreadyContained); if (index >= 0) { if (alreadyContained) { allLightmapDatas.Add(new LightmapInfos { index = index, texGUID = lightmapGUID.name, size = 0 }); } else { using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { NativeArray <Color32> color; int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); color = new NativeArray <Color32>(length / sizeof(Color32), Allocator.Persistent, NativeArrayOptions.UninitializedMemory); fixed(byte *source = bytes) { UnsafeUtility.MemCpy(color.GetUnsafePtr(), source, Mathf.Min(color.Length * sizeof(Color32), length)); } allLightmapDatas.Add(new LightmapInfos { array = color, index = index, texGUID = lightmapGUID.name, size = lightmapGUID.size }); } } } } for (int i = 0; i < values.Length; ++i) { ref PropertyValue value = ref values[i]; int *indexPtr = (int *)UnsafeUtility.AddressOf(ref value.textureIndex); for (int a = 0; a < property.texPaths.Length; ++a) { string texName = property.texPaths[a].instancingIDs[i]; allStrings[0] = "Assets/BinaryData/Textures/"; allStrings[1] = texName; allStrings[2] = ".mpipe"; sb.Combine(allStrings); string texType = property.texPaths[a].texName; bool alreadyContained; indexPtr[a] = SceneController.commonData.GetIndex(texName, out alreadyContained); if (indexPtr[a] >= 0) { if (alreadyContained) { allTextureDatas.Add(new TextureInfos { array = new NativeArray <Color32>(), index = indexPtr[a], texGUID = texName, texType = texType }); } else { using (FileStream reader = new FileStream(sb.str, FileMode.Open, FileAccess.Read)) { int length = (int)reader.Length; byte[] bytes = GetByteArray(length); reader.Read(bytes, 0, length); int res = SceneController.resolution; NativeArray <Color32> allColors = new NativeArray <Color32>(res * res, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); fixed(byte *source = bytes) { UnsafeUtility.MemCpy(allColors.GetUnsafePtr(), source, Mathf.Min(allColors.Length * sizeof(Color32), length)); } allTextureDatas.Add(new TextureInfos { array = allColors, index = indexPtr[a], texGUID = texName, texType = texType }); } } } } }
protected override void OnEnableFunc() { if (current && current != this) { enabled = false; Debug.LogError("Only One Terrain allowed!"); return; } if (!terrainData) { enabled = false; Debug.LogError("No Data!"); return; } if (!cam || !decalCamera) { enabled = false; Debug.LogError("No Decal Camera!"); return; } initializing = true; lodOffset = terrainData.GetLodOffset(); largestChunkCount = (int)(0.1 + pow(2.0, lodOffset)); msb = new MStringBuilder(32); oneVTPixelWorldLength = terrainData.VTTexelLength(); textureShader = Resources.Load <ComputeShader>("ProceduralTexture"); shader = Resources.Load <ComputeShader>("TerrainCompute"); current = this; int indexMapSize = 1; for (int i = 1; i < terrainData.lodDistances.Length; ++i) { indexMapSize *= 2; } vtContainer = new NativeArray <int>(4, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); maskLoadList = new NativeQueue <MaskLoadCommand>(10, Allocator.Persistent); ComputeShader editShader = Resources.Load <ComputeShader>("TerrainEdit"); loadingThread = new MTerrainLoadingThread(10); maskLoader = new VirtualTextureLoader(terrainData.maskmapPath, editShader, largestChunkCount, MASK_RESOLUTION, false, loadingThread); heightLoader = new VirtualTextureLoader(terrainData.heightmapPath, editShader, largestChunkCount, MASK_RESOLUTION, true, loadingThread); loadDataList = new NativeQueue <TerrainLoadData>(100, Allocator.Persistent); initializeLoadList = new NativeQueue <TerrainLoadData>(100, Allocator.Persistent); NativeArray <uint> dispatchDraw = new NativeArray <uint>(5, Allocator.Temp, NativeArrayOptions.ClearMemory); dispatchDraw[0] = 6; VirtualTextureFormat *formats = stackalloc VirtualTextureFormat[] { new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, GraphicsFormat.R8G8B8A8_UNorm, "_VirtualMainTex", 2), new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, GraphicsFormat.R16G16_SNorm, "_VirtualBumpMap", 2), new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, GraphicsFormat.R8G8_UNorm, "_VirtualSMMap", 2), new VirtualTextureFormat((VirtualTextureSize)HEIGHT_RESOLUTION, HEIGHT_FORMAT, "_VirtualDisplacement", 0) }; mipIDs = new NativeArray <int>(2, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); mipIDs[0] = Shader.PropertyToID("_Mip0"); mipIDs[1] = Shader.PropertyToID("_Mip1"); chunkCount = (int)(pow(2.0, terrainData.lodDistances.Length - 1) + 0.1); vt = new VirtualTexture(terrainData.virtualTexCapacity, min(2048, chunkCount), formats, 4, "_TerrainVTIndexTex"); textureCapacity = terrainData.virtualTexCapacity; VirtualTextureFormat *maskFormats = stackalloc VirtualTextureFormat[] { new VirtualTextureFormat((VirtualTextureSize)MASK_RESOLUTION, GraphicsFormat.R8_UNorm, "_VirtualMaskmap"), new VirtualTextureFormat((VirtualTextureSize)MASK_RESOLUTION, GraphicsFormat.R16_UNorm, "_VirtualHeightmap"), }; maskVT = new VirtualTexture(terrainData.heightmapTexCapacity, largestChunkCount, maskFormats, 2, "_MaskIndexMap"); maskVT.GetTexture(0).filterMode = FilterMode.Point; maskVT.GetTexture(1).filterMode = FilterMode.Point; vt.GetTexture(0).filterMode = FilterMode.Trilinear; vt.GetTexture(1).filterMode = FilterMode.Trilinear; vt.GetTexture(2).filterMode = FilterMode.Trilinear; vt.GetTexture(3).filterMode = FilterMode.Bilinear; allLodLevles = new NativeList_Float(terrainData.lodDistances.Length, Allocator.Persistent); for (int i = 0; i < terrainData.lodDistances.Length; ++i) { allLodLevles.Add((float)min(terrainData.lodDistances[max(0, i - 1)], terrainData.lodDistances[i])); } allLodLevles[terrainData.lodDistances.Length] = 0; meshResolution = terrainData.GetMeshResolution(); cullingFlags = new RenderTexture(new RenderTextureDescriptor { graphicsFormat = GraphicsFormat.R8_UNorm, dimension = TextureDimension.Tex2D, width = meshResolution, height = meshResolution, volumeDepth = 1, enableRandomWrite = true, msaaSamples = 1, useMipMap = false }); cullingFlags.filterMode = FilterMode.Point; cullingFlags.Create(); albedoTex = new RenderTexture(new RenderTextureDescriptor { graphicsFormat = GraphicsFormat.R8G8B8A8_UNorm, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1, autoGenerateMips = false, useMipMap = true, mipCount = 6, }); albedoTex.Create(); normalTex = new RenderTexture(new RenderTextureDescriptor { graphicsFormat = GraphicsFormat.R16G16_SNorm, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, autoGenerateMips = false, useMipMap = true, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1, mipCount = 6, }); normalTex.Create(); smTex = new RenderTexture(new RenderTextureDescriptor { graphicsFormat = GraphicsFormat.R16G16_UNorm, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1, useMipMap = true, autoGenerateMips = false, mipCount = 6, depthBufferBits = 0, useDynamicScale = false }); smTex.Create(); /* heightTex = new RenderTexture(new RenderTextureDescriptor * { * graphicsFormat = GraphicsFormat.R8_UNorm, * dimension = TextureDimension.Tex2DArray, * width = COLOR_RESOLUTION, * height = COLOR_RESOLUTION, * volumeDepth = Mathf.Max(1, terrainData.textures.Length), * enableRandomWrite = true, * msaaSamples = 1, * useMipMap = true, * autoGenerateMips = false, * mipCount = 6, * depthBufferBits = 0, * useDynamicScale = false * });*/ heightloadingCacheRT = new RenderTexture(new RenderTextureDescriptor { width = COLOR_RESOLUTION + 2, height = COLOR_RESOLUTION + 2, volumeDepth = 1, enableRandomWrite = true, dimension = TextureDimension.Tex2D, graphicsFormat = GraphicsFormat.R16_UNorm, msaaSamples = 1, useMipMap = false, autoGenerateMips = false, mipCount = 0, depthBufferBits = 0, useDynamicScale = false, }); randomTileRT = new RenderTexture(256, 256, 0, GraphicsFormat.R16G16B16A16_SNorm, 0); randomTileRT.enableRandomWrite = true; randomTileRT.wrapMode = TextureWrapMode.Repeat; randomTileRT.filterMode = FilterMode.Point; randomTileRT.Create(); heightloadingCacheRT.Create(); // heightTex.Create(); smTex.wrapMode = TextureWrapMode.Repeat; normalTex.wrapMode = TextureWrapMode.Repeat; albedoTex.wrapMode = TextureWrapMode.Repeat; // heightTex.wrapMode = TextureWrapMode.Repeat; boundBoxLoadList = new NativeQueue <MaskLoadCommand>(10, Allocator.Persistent); boundingLoadStream = new FileStream(terrainData.boundPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); boundingDict = new NativeDictionary <int2, MTerrainBoundingTree, Int2Equal>(20, Allocator.Persistent, new Int2Equal()); InitializeMeshData(); allDrawCommand = new NativeList <TerrainDrawCommand>(20, Allocator.Persistent); materialBuffer = new ComputeBuffer(max(1, terrainData.allMaterials.Length), sizeof(MTerrainData.HeightBlendMaterial)); materialBuffer.SetData(terrainData.allMaterials); decalLayerOffset = max(0, terrainData.lodDistances.Length - terrainData.allDecalLayers.Length); tree = new TerrainQuadTree(-1, TerrainQuadTree.LocalPos.LeftDown, 0, 0, terrainData.largestChunkSize, double3(1, 0, 0), 0); StartCoroutine(AsyncLoader()); }
protected override void OnEnableFunc() { if (current && current != this) { enabled = false; Debug.LogError("Only One Terrain allowed!"); return; } if (!terrainData) { enabled = false; Debug.LogError("No Data!"); return; } msb = new MStringBuilder(32); textureShader = Resources.Load <ComputeShader>("ProceduralTexture"); shader = Resources.Load <ComputeShader>("TerrainCompute"); current = this; int indexMapSize = 1; for (int i = 1; i < terrainData.lodDistances.Length; ++i) { indexMapSize *= 2; } dispatchDrawBuffer = new ComputeBuffer(5, sizeof(int), ComputeBufferType.IndirectArguments); const int INIT_LENGTH = 500; culledResultsBuffer = new ComputeBuffer(INIT_LENGTH, sizeof(int)); loadedBuffer = new ComputeBuffer(INIT_LENGTH, sizeof(TerrainChunkBuffer)); loadedBufferList = new NativeList <TerrainChunkBuffer>(INIT_LENGTH, Allocator.Persistent); lodOffset = terrainData.lodDistances.Length - terrainData.renderingLevelCount; loader = new VirtualTextureLoader(lodOffset, terrainData.renderingLevelCount, terrainData.readWritePath, this); loadDataList = new NativeQueue <TerrainLoadData>(100, Allocator.Persistent); NativeArray <uint> dispatchDraw = new NativeArray <uint>(5, Allocator.Temp, NativeArrayOptions.ClearMemory); dispatchDraw[0] = 96; dispatchDrawBuffer.SetData(dispatchDraw); VirtualTextureFormat *formats = stackalloc VirtualTextureFormat[] { new VirtualTextureFormat((VirtualTextureSize)HEIGHT_RESOLUTION, RenderTextureFormat.R16, "_VirtualHeightmap"), new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, RenderTextureFormat.ARGB32, "_VirtualMainTex"), new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, RenderTextureFormat.RGHalf, "_VirtualBumpMap"), new VirtualTextureFormat((VirtualTextureSize)COLOR_RESOLUTION, RenderTextureFormat.RG16, "_VirtualSMMap") }; vt = new VirtualTexture(terrainData.virtualTexCapacity, min(2048, (int)(pow(2.0, terrainData.lodDistances.Length) + 0.1)), formats, 4, "_TerrainVTIndexTex"); allLodLevles = new NativeList_Float(terrainData.lodDistances.Length, Allocator.Persistent); for (int i = 0; i < terrainData.lodDistances.Length; ++i) { allLodLevles.Add(min(terrainData.lodDistances[max(0, i - 1)], terrainData.lodDistances[i])); } allLodLevles[terrainData.lodDistances.Length] = 0; albedoTex = new RenderTexture(new RenderTextureDescriptor { colorFormat = RenderTextureFormat.ARGB32, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1 }); albedoTex.Create(); normalTex = new RenderTexture(new RenderTextureDescriptor { colorFormat = RenderTextureFormat.RGHalf, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1 }); normalTex.Create(); smTex = new RenderTexture(new RenderTextureDescriptor { colorFormat = RenderTextureFormat.RG16, dimension = TextureDimension.Tex2DArray, width = COLOR_RESOLUTION, height = COLOR_RESOLUTION, volumeDepth = Mathf.Max(1, terrainData.textures.Length), enableRandomWrite = true, msaaSamples = 1 }); smTex.Create(); smTex.wrapMode = TextureWrapMode.Repeat; normalTex.wrapMode = TextureWrapMode.Repeat; albedoTex.wrapMode = TextureWrapMode.Repeat; mask = new RenderTexture(new RenderTextureDescriptor { colorFormat = RenderTextureFormat.R8, dimension = TextureDimension.Tex2D, width = MASK_RESOLUTION, height = MASK_RESOLUTION, volumeDepth = 1, enableRandomWrite = true, msaaSamples = 1 }); mask.Create(); textureBuffer = new ComputeBuffer(max(MASK_RESOLUTION * MASK_RESOLUTION / 4, HEIGHT_RESOLUTION * HEIGHT_RESOLUTION / 2), 4); tree = new TerrainQuadTree(-1, TerrainQuadTree.LocalPos.LeftDown, 0, terrainData.largestChunkSize); StartCoroutine(AsyncLoader()); } void UpdateBuffer() { if (!loadedBufferList.isCreated) { return; } if (loadedBufferList.Length > loadedBuffer.count) { loadedBuffer.Dispose(); culledResultsBuffer.Dispose(); loadedBuffer = new ComputeBuffer(loadedBufferList.Capacity, sizeof(TerrainChunkBuffer)); culledResultsBuffer = new ComputeBuffer(loadedBufferList.Capacity, sizeof(int)); } loadedBuffer.SetDataPtr(loadedBufferList.unsafePtr, loadedBufferList.Length); }
private void Awake() { if (!msb.isCreated) { msb = new MStringBuilder(30); } msb.Clear(); msb.Add("Assets/BinaryData/Irradiance/"); msb.Add(probeName); msb.Add(".mpipe"); if (!System.IO.File.Exists(msb.str)) { Debug.LogError("Probe: " + probeName + "read Error! "); Destroy(gameObject); return; } else { using (System.IO.FileStream fs = new System.IO.FileStream(msb.str, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] arr = GetByteArray(fs.Length); fs.Read(arr, 0, (int)fs.Length); int3 *res = (int3 *)arr.Ptr(); resolution = *res; if (resolution.x * resolution.y * resolution.z * sizeof(float3x3) != fs.Length - sizeof(int3)) { Debug.LogError("Data size incorrect!"); Destroy(gameObject); return; } NativeArray <float3x3> allDatas = new NativeArray <float3x3>(resolution.x * resolution.y * resolution.z, Allocator.Temp); UnsafeUtility.MemCpy(allDatas.GetUnsafePtr(), res + 1, sizeof(float3x3) * allDatas.Length); RenderTextureDescriptor desc = new RenderTextureDescriptor { colorFormat = RenderTextureFormat.ARGBHalf, dimension = TextureDimension.Tex3D, enableRandomWrite = true, width = resolution.x, height = resolution.y, volumeDepth = resolution.z, msaaSamples = 1 }; src0 = new RenderTexture(desc); src1 = new RenderTexture(desc); desc.colorFormat = RenderTextureFormat.RHalf; src2 = new RenderTexture(desc); shBuffer = new ComputeBuffer(allDatas.Length, sizeof(float3x3)); shBuffer.SetData(allDatas); ComputeShader shader = resources.shaders.occlusionProbeCalculate; int3 * arrPtr = (int3 *)resolutionArray.Ptr(); *arrPtr = resolution; shader.SetBuffer(2, "_SHBuffer", shBuffer); shader.SetTexture(2, "_Src0", src0); shader.SetTexture(2, "_Src1", src1); shader.SetTexture(2, "_Src2", src2); shader.SetInts("_Resolution", resolutionArray); shader.Dispatch(2, Mathf.CeilToInt(resolution.x / 4f), Mathf.CeilToInt(resolution.y / 4f), Mathf.CeilToInt(resolution.z / 4f)); shBuffer.Dispose(); allDatas.Dispose(); } } }
private static void PackHeightmap(Texture2D[,] allHeightmap, int textureSize, int lodLevel, string path, string terrainName) { ComputeShader shader = Resources.Load <ComputeShader>("MipmapCompute"); ComputeBuffer readBuffer = new ComputeBuffer(textureSize * textureSize, sizeof(float)); MStringBuilder sb = new MStringBuilder(path.Length + terrainName.Length + 15); sb.Add(path); if (path[path.Length - 1] != '/') { sb.Add("/"); } sb.Add(terrainName); path += terrainName; if (Directory.Exists(sb.str)) { Directory.Delete(sb.str); } Directory.CreateDirectory(sb.str); int pathLength = sb.str.Length; for (int i = 0; i < lodLevel; ++i) { sb.Resize(pathLength); sb.Add("/LOD" + i.ToString()); Directory.CreateDirectory(sb.str); } sb.Resize(pathLength); sb.Add("/LOD0"); for (int x = 0; x < allHeightmap.GetLength(0); ++x) { for (int y = 0; y < allHeightmap.GetLength(1); ++y) { Texture2D tex = allHeightmap[x, y]; if (tex.width != textureSize || tex.height != textureSize) { readBuffer.Dispose(); Resources.UnloadAsset(shader); throw new System.Exception("Texture " + tex.name + " setting is not right!(Width, Height, isReadable)"); } } } shader.SetBuffer(1, "_OutputBuffer", readBuffer); float[] result = new float[textureSize * textureSize]; void SaveTexture(StreamWriter writer, Texture tex) { shader.SetTexture(1, ShaderIDs._MainTex, tex); int kernelSize = Mathf.CeilToInt(textureSize / 8f); shader.Dispatch(1, kernelSize, kernelSize, 1); readBuffer.GetData(result); char[] chrArray = new char[result.Length * sizeof(half)]; half * arrPtr = (half *)chrArray.Ptr(); for (int i = 0; i < result.Length; ++i) { arrPtr[i] = (half)result[i]; } writer.Write(chrArray); } using (StreamWriter writer = new StreamWriter(sb.str)) { for (int x = 0; x < allHeightmap.GetLength(0); ++x) { for (int y = 0; y < allHeightmap.GetLength(1); ++y) { Texture2D tex = allHeightmap[x, y]; SaveTexture(writer, tex); } } } readBuffer.Dispose(); Resources.UnloadAsset(shader); }