public Texture3D Generate() { if (mesh == null) { throw new System.ArgumentException("Mesh must have been assigned"); } // Create the voxel texture. Texture3D voxels = new Texture3D(resolution, resolution, resolution, TextureFormat.RGBAHalf, false); voxels.anisoLevel = 1; voxels.filterMode = FilterMode.Bilinear; voxels.wrapMode = TextureWrapMode.Clamp; // Get an array of pixels from the voxel texture, create a buffer to // hold them, and upload the pixels to the buffer. Color[] pixelArray = voxels.GetPixels(0); ComputeBuffer pixelBuffer = new ComputeBuffer(pixelArray.Length, sizeof(float) * 4); pixelBuffer.SetData(pixelArray); // Get an array of triangles from the mesh. Vector3[] meshVertices = mesh.vertices; int[] meshTriangles = mesh.GetTriangles(subMeshIndex); Triangle[] triangleArray = new Triangle[meshTriangles.Length / 3]; for (int t = 0; t < triangleArray.Length; t++) { triangleArray[t].a = meshVertices[meshTriangles[3 * t + 0]]; // - mesh.bounds.center; triangleArray[t].b = meshVertices[meshTriangles[3 * t + 1]]; // - mesh.bounds.center; triangleArray[t].c = meshVertices[meshTriangles[3 * t + 2]]; // - mesh.bounds.center; } // Create a buffer to hold the triangles, and upload them to the buffer. ComputeBuffer triangleBuffer = new ComputeBuffer(triangleArray.Length, sizeof(float) * 3 * 3); triangleBuffer.SetData(triangleArray); // Instantiate the compute shader from resources. ComputeShader compute = Instantiate(Resources.Load("GenerateSDF")) as ComputeShader; int kernel = compute.FindKernel("CSMain"); // Upload the pixel buffer to the GPU. compute.SetBuffer(kernel, "pixelBuffer", pixelBuffer); compute.SetInt("pixelBufferSize", pixelArray.Length); // Upload the triangle buffer to the GPU. compute.SetBuffer(kernel, "triangleBuffer", triangleBuffer); compute.SetInt("triangleBufferSize", triangleArray.Length); // Calculate and upload the other necessary parameters. compute.SetInt("textureSize", resolution); Vector3 minExtents = Vector3.zero; Vector3 maxExtents = Vector3.zero; foreach (Vector3 v in mesh.vertices) { for (int i = 0; i < 3; i++) { minExtents[i] = Mathf.Min(minExtents[i], v[i]); maxExtents[i] = Mathf.Max(maxExtents[i], v[i]); } } compute.SetVector("minExtents", minExtents - Vector3.one*padding); compute.SetVector("maxExtents", maxExtents + Vector3.one*padding); // Compute the SDF. compute.Dispatch(kernel, pixelArray.Length / 256 + 1, 1, 1); // Destroy the compute shader and release the triangle buffer. DestroyImmediate(compute); triangleBuffer.Release(); // Retrieve the pixel buffer and reapply it to the voxels texture. pixelBuffer.GetData(pixelArray); pixelBuffer.Release(); voxels.SetPixels(pixelArray, 0); voxels.Apply(); // Return the voxel texture. return voxels; }
void RunShader() { _kernelHandle = myComputeShader.FindKernel("CSMain"); _myParticles = new Particle[0]; }
/// <summary> /// Finally, we provide the actual implementation of the precomputation algorithm /// described in Algorithm 4.1 of /// <a href="https://hal.inria.fr/inria-00288758/en">our paper</a>. Each step is /// explained by the inline comments below. /// </summary> void Precompute( ComputeShader compute, TextureBuffer buffer, double[] lambdas, double[] luminance_from_radiance, bool blend, int num_scattering_orders) { int BLEND = blend ? 1 : 0; int NUM_THREADS = CONSTANTS.NUM_THREADS; BindToCompute(compute, lambdas, luminance_from_radiance); int compute_transmittance = compute.FindKernel("ComputeTransmittance"); int compute_direct_irradiance = compute.FindKernel("ComputeDirectIrradiance"); int compute_single_scattering = compute.FindKernel("ComputeSingleScattering"); int compute_scattering_density = compute.FindKernel("ComputeScatteringDensity"); int compute_indirect_irradiance = compute.FindKernel("ComputeIndirectIrradiance"); int compute_multiple_scattering = compute.FindKernel("ComputeMultipleScattering"); // Compute the transmittance, and store it in transmittance_texture compute.SetTexture(compute_transmittance, "transmittanceWrite", buffer.TransmittanceArray[WRITE]); compute.SetVector("blend", new Vector4(0, 0, 0, 0)); compute.Dispatch(compute_transmittance, CONSTANTS.TRANSMITTANCE_WIDTH / NUM_THREADS, CONSTANTS.TRANSMITTANCE_HEIGHT / NUM_THREADS, 1); Swap(buffer.TransmittanceArray); // Compute the direct irradiance, store it in delta_irradiance_texture and, // depending on 'blend', either initialize irradiance_texture_ with zeros or // leave it unchanged (we don't want the direct irradiance in // irradiance_texture_, but only the irradiance from the sky). compute.SetTexture(compute_direct_irradiance, "deltaIrradianceWrite", buffer.DeltaIrradianceTexture); //0 compute.SetTexture(compute_direct_irradiance, "irradianceWrite", buffer.IrradianceArray[WRITE]); //1 compute.SetTexture(compute_direct_irradiance, "irradianceRead", buffer.IrradianceArray[READ]); compute.SetTexture(compute_direct_irradiance, "transmittanceRead", buffer.TransmittanceArray[READ]); compute.SetVector("blend", new Vector4(0, BLEND, 0, 0)); compute.Dispatch(compute_direct_irradiance, CONSTANTS.IRRADIANCE_WIDTH / NUM_THREADS, CONSTANTS.IRRADIANCE_HEIGHT / NUM_THREADS, 1); Swap(buffer.IrradianceArray); // Compute the rayleigh and mie single scattering, store them in // delta_rayleigh_scattering_texture and delta_mie_scattering_texture, and // either store them or accumulate them in scattering_texture_ and // optional_single_mie_scattering_texture_. compute.SetTexture(compute_single_scattering, "deltaRayleighScatteringWrite", buffer.DeltaRayleighScatteringTexture); //0 compute.SetTexture(compute_single_scattering, "deltaMieScatteringWrite", buffer.DeltaMieScatteringTexture); //1 compute.SetTexture(compute_single_scattering, "scatteringWrite", buffer.ScatteringArray[WRITE]); //2 compute.SetTexture(compute_single_scattering, "scatteringRead", buffer.ScatteringArray[READ]); compute.SetTexture(compute_single_scattering, "singleMieScatteringWrite", buffer.OptionalSingleMieScatteringArray[WRITE]); //3 compute.SetTexture(compute_single_scattering, "singleMieScatteringRead", buffer.OptionalSingleMieScatteringArray[READ]); compute.SetTexture(compute_single_scattering, "transmittanceRead", buffer.TransmittanceArray[READ]); compute.SetVector("blend", new Vector4(0, 0, BLEND, BLEND)); for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer) { compute.SetInt("layer", layer); compute.Dispatch(compute_single_scattering, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1); } Swap(buffer.ScatteringArray); Swap(buffer.OptionalSingleMieScatteringArray); // Compute the 2nd, 3rd and 4th order of scattering, in sequence. for (int scattering_order = 2; scattering_order <= num_scattering_orders; ++scattering_order) { // Compute the scattering density, and store it in // delta_scattering_density_texture. compute.SetTexture(compute_scattering_density, "deltaScatteringDensityWrite", buffer.DeltaScatteringDensityTexture); //0 compute.SetTexture(compute_scattering_density, "transmittanceRead", buffer.TransmittanceArray[READ]); compute.SetTexture(compute_scattering_density, "singleRayleighScatteringRead", buffer.DeltaRayleighScatteringTexture); compute.SetTexture(compute_scattering_density, "singleMieScatteringRead", buffer.DeltaMieScatteringTexture); compute.SetTexture(compute_scattering_density, "multipleScatteringRead", buffer.DeltaMultipleScatteringTexture); compute.SetTexture(compute_scattering_density, "irradianceRead", buffer.DeltaIrradianceTexture); compute.SetInt("scatteringOrder", scattering_order); compute.SetVector("blend", new Vector4(0, 0, 0, 0)); for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer) { compute.SetInt("layer", layer); compute.Dispatch(compute_scattering_density, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1); } // Compute the indirect irradiance, store it in delta_irradiance_texture and // accumulate it in irradiance_texture_. compute.SetTexture(compute_indirect_irradiance, "deltaIrradianceWrite", buffer.DeltaIrradianceTexture); //0 compute.SetTexture(compute_indirect_irradiance, "irradianceWrite", buffer.IrradianceArray[WRITE]); //1 compute.SetTexture(compute_indirect_irradiance, "irradianceRead", buffer.IrradianceArray[READ]); compute.SetTexture(compute_indirect_irradiance, "singleRayleighScatteringRead", buffer.DeltaRayleighScatteringTexture); compute.SetTexture(compute_indirect_irradiance, "singleMieScatteringRead", buffer.DeltaMieScatteringTexture); compute.SetTexture(compute_indirect_irradiance, "multipleScatteringRead", buffer.DeltaMultipleScatteringTexture); compute.SetInt("scatteringOrder", scattering_order - 1); compute.SetVector("blend", new Vector4(0, 1, 0, 0)); compute.Dispatch(compute_indirect_irradiance, CONSTANTS.IRRADIANCE_WIDTH / NUM_THREADS, CONSTANTS.IRRADIANCE_HEIGHT / NUM_THREADS, 1); Swap(buffer.IrradianceArray); // Compute the multiple scattering, store it in // delta_multiple_scattering_texture, and accumulate it in // scattering_texture_. compute.SetTexture(compute_multiple_scattering, "deltaMultipleScatteringWrite", buffer.DeltaMultipleScatteringTexture); //0 compute.SetTexture(compute_multiple_scattering, "scatteringWrite", buffer.ScatteringArray[WRITE]); //1 compute.SetTexture(compute_multiple_scattering, "scatteringRead", buffer.ScatteringArray[READ]); compute.SetTexture(compute_multiple_scattering, "transmittanceRead", buffer.TransmittanceArray[READ]); compute.SetTexture(compute_multiple_scattering, "deltaScatteringDensityRead", buffer.DeltaScatteringDensityTexture); compute.SetVector("blend", new Vector4(0, 1, 0, 0)); for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer) { compute.SetInt("layer", layer); compute.Dispatch(compute_multiple_scattering, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1); } Swap(buffer.ScatteringArray); } return; }
void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount) { // Fetch the required resources var settings = hdCamera.volumeStack.GetComponent <GlobalIllumination>(); BlueNoise blueNoise = GetBlueNoiseManager(); // Fetch all the settings LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent <LightCluster>(); RayTracingSettings rtSettings = hdCamera.volumeStack.GetComponent <RayTracingSettings>(); ComputeShader indirectDiffuseCS = m_Asset.renderPipelineRayTracingResources.indirectDiffuseRaytracingCS; // Request the intermediate texture we will be using RTHandle directionBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.Direction); RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingIntegrateIndirectDiffuse))) { // Fetch the new sample kernel int currentKernel = indirectDiffuseCS.FindKernel(settings.fullResolution ? "RaytracingIndirectDiffuseFullRes" : "RaytracingIndirectDiffuseHalfRes"); // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); // Bind all the required textures cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); // Bind the output buffers cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); // Texture dimensions int texWidth = settings.fullResolution ? hdCamera.actualWidth : hdCamera.actualWidth / 2; int texHeight = settings.fullResolution ? hdCamera.actualHeight : hdCamera.actualHeight / 2; // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesXHR = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (texHeight + (areaTileSize - 1)) / areaTileSize; // Compute the directions cmd.DispatchCompute(indirectDiffuseCS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Prepare the components for the deferred lighting DeferredLightingRTParameters deferredParamters = PrepareIndirectDiffuseDeferredLightingRTParameters(hdCamera); DeferredLightingRTResources deferredResources = PrepareDeferredLightingRTResources(hdCamera, directionBuffer, m_IndirectDiffuseBuffer0); // Evaluate the deferred lighting RenderRaytracingDeferredLighting(cmd, deferredParamters, deferredResources); } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingFilterIndirectDiffuse))) { // Fetch the right filter to use int currentKernel = indirectDiffuseCS.FindKernel(settings.fullResolution ? "IndirectDiffuseIntegrationUpscaleFullRes" : "IndirectDiffuseIntegrationUpscaleHalfRes"); // Inject all the parameters for the compute cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._IndirectDiffuseTexture, m_IndirectDiffuseBuffer0); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._BlueNoiseTexture, blueNoise.textureArray16RGB); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._UpscaledIndirectDiffuseTextureRW, intermediateBuffer1); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex); cmd.SetComputeIntParam(indirectDiffuseCS, HDShaderIDs._SpatialFilterRadius, settings.upscaleRadius); // Texture dimensions int texWidth = hdCamera.actualWidth; int texHeight = hdCamera.actualHeight; // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesXHR = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (texHeight + (areaTileSize - 1)) / areaTileSize; // Compute the texture cmd.DispatchCompute(indirectDiffuseCS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Copy the data back to the right buffer HDUtils.BlitCameraTexture(cmd, intermediateBuffer1, m_IndirectDiffuseBuffer0); // Denoise if required if (settings.denoise) { DenoiseIndirectDiffuseBuffer(hdCamera, cmd, settings); } } }
bool SetNoiseCS_3D(NoiseModule _noise, ComputeBuffer _res) { if (_noise == null || _res == null) { return(false); } string path = string.Empty; string kanel = string.Empty; RandomTable randFunc = null; if (GetComputerShader_3D(_noise.eType, out path, out kanel, out randFunc) == false) { return(false); } ComputeShader cs = Resources.Load <ComputeShader>(path); if (cs == null) { return(false); } int kID = cs.FindKernel(kanel); ComputeBuffer rtBuffer = null; if (randFunc != null) { rtBuffer = randFunc.Invoke(cs, kID, _noise.fRandomSeed); } cs.SetInt("Octaves", _noise.bFBM ? _noise.iOctaves : 1); cs.SetFloat("Persistence", _noise.fPersistence); cs.SetFloat("Scale", _noise.fScale); cs.SetFloat("Period", _noise.iPeriod); cs.SetInt("TexWidth", mTexSize); cs.SetInt("TexHeight", mTexSize); cs.SetInt("TexDepth", mTexSize); cs.SetBuffer(kID, "Result", _res); uint sizeX, sizeY, sizeZ; cs.GetKernelThreadGroupSizes( kID, out sizeX, out sizeY, out sizeZ ); cs.Dispatch(kID, mTexSize / (int)sizeX, mTexSize / (int)sizeY, mTexSize / (int)sizeZ); if (rtBuffer != null) { rtBuffer.Release(); rtBuffer = null; } return(true); }
private void Update() { if (Input.GetKeyDown(KeyCode.C)) { //RenderTexture tex = new RenderTexture(256, 256, 24); //tex.enableRandomWrite = true; //tex.Create(); // Get all ray march colliders. RMCollider[] _colliders = (RMCollider[])FindObjectsOfType(typeof(RMCollider)); // Extract all collider info, and pack into float array. ColliderInfo[] colliderInfos = new ColliderInfo[_colliders.Length]; Matrix4x4[] invModelMats = new Matrix4x4[_colliders.Length]; int[] primitiveTypes = new int[_colliders.Length]; Vector4[] combineOps = new Vector4[_colliders.Length]; Vector4[] primitiveGeoInfo = new Vector4[_colliders.Length]; ColliderInfo colInfo; GameObject obj; for (int i = 0; i < _colliders.Length; ++i) { obj = _colliders[i].gameObject; colInfo.pos = obj.transform.position; colInfo.geoInfo = obj.GetComponent <RMPrimitive>().GeoInfo; colInfo.colliding = -1; colliderInfos[i] = colInfo; invModelMats[i] = obj.transform.localToWorldMatrix.inverse; primitiveTypes[i] = (int)obj.GetComponent <RMPrimitive>().PrimitiveType; combineOps[i] = obj.GetComponent <RMPrimitive>().CombineOp; primitiveGeoInfo[i] = obj.GetComponent <RMPrimitive>().GeoInfo; } int kernel = _collisionCompute.FindKernel("CSMain"); // Create a compute buffer. ComputeBuffer buffer = new ComputeBuffer(colliderInfos.Length, (sizeof(float) * 7) + sizeof(int)); buffer.SetData(colliderInfos); _collisionCompute.SetBuffer(kernel, "_colliderInfo", buffer); //_collisionCompute.SetTexture(0, "Result", tex); _collisionCompute.SetMatrixArray("_invModelMats", invModelMats); _collisionCompute.SetInts("_primitiveTypes", primitiveTypes); _collisionCompute.SetVectorArray("_combineOps", combineOps); _collisionCompute.SetVectorArray("_primitiveGeoInfo", primitiveGeoInfo); int numThreadGroups = _colliders.Length; _collisionCompute.Dispatch(kernel, 1, 1, 1); //_collisionCompute.Dispatch(0, 256/8, 256/8, 1); buffer.GetData(colliderInfos); Debug.Log("Dist: " + colliderInfos[0].geoInfo.w); if (colliderInfos[0].colliding == 1) { Debug.Log("Colliding"); _colliders[0].gameObject.transform.position = colliderInfos[0].pos; } //Graphics.CopyTexture(tex, _computeTex); buffer.Release(); //tex.Release(); } }
public Boundary() { CS = Resources.Load <ComputeShader>("WaterSimulationForGames/Boundary"); K_CONVERT = CS.FindKernel("Convert"); }
public void initShaderKernels() { if (shader != null) { // save shaders and kernels AbsKernel = shader.FindKernel("Abs"); AbsKernel_ = shader.FindKernel("Abs_"); AddScalarKernel_ = shader.FindKernel("AddScalar_"); AddElemKernel_ = shader.FindKernel("AddElem_"); AddScalarKernel = shader.FindKernel("AddScalar"); AddElemKernel = shader.FindKernel("AddElem"); AddMMKernel_ = shader.FindKernel("AddMM_"); CeilKernel = shader.FindKernel("Ceil"); CosKernel = shader.FindKernel("Cos"); CosKernel_ = shader.FindKernel("Cos_"); CoshKernel = shader.FindKernel("Cosh"); CoshKernel_ = shader.FindKernel("Cosh_"); DivScalarKernel_ = shader.FindKernel("DivScalar_"); DivElemKernel_ = shader.FindKernel("DivElem_"); DivScalarKernel = shader.FindKernel("DivScalar"); DivElemKernel = shader.FindKernel("DivElem"); FloorKernel_ = shader.FindKernel("Floor_"); MulScalarKernel_ = shader.FindKernel("MulScalar_"); MulElemKernel_ = shader.FindKernel("MulElem_"); MulScalarKernel = shader.FindKernel("MulScalar"); MulElemKernel = shader.FindKernel("MulElem"); NegateKernel = shader.FindKernel("Negate"); PowKernel = shader.FindKernel("Pow"); PowKernel_ = shader.FindKernel("Pow_"); SigmoidKernel_ = shader.FindKernel("Sigmoid_"); SqrtKernel = shader.FindKernel("Sqrt"); SubScalarKernel_ = shader.FindKernel("SubScalar_"); SubElemKernel_ = shader.FindKernel("SubElem_"); SubScalarKernel = shader.FindKernel("SubScalar"); SubElemKernel = shader.FindKernel("SubElem"); TanhKernel = shader.FindKernel("Tanh"); SinhKernel = shader.FindKernel("Sinh"); SinhKernel_ = shader.FindKernel("Sinh_"); TriuKernel_ = shader.FindKernel("Triu_"); TruncKernel = shader.FindKernel("Trunc"); ZeroKernel_ = shader.FindKernel("Zero_"); } }
public void RenderReflections(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle outputTexture, ScriptableRenderContext renderContext, uint frameCount) { // First thing to check is: Do we have a valid ray-tracing environment? HDRaytracingEnvironment rtEnvironement = m_RaytracingManager.CurrentEnvironment(); BlueNoise blueNoise = m_RaytracingManager.GetBlueNoiseManager(); ComputeShader bilateralFilter = m_PipelineAsset.renderPipelineResources.shaders.reflectionBilateralFilterCS; RaytracingShader reflectionShader = m_PipelineAsset.renderPipelineResources.shaders.reflectionRaytracing; bool invalidState = rtEnvironement == null || blueNoise == null || bilateralFilter == null || reflectionShader == null || m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null; // If no acceleration structure available, end it now if (invalidState) { return; } // Grab the acceleration structures and the light cluster to use RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(rtEnvironement.reflLayerMask); HDRaytracingLightCluster lightCluster = m_RaytracingManager.RequestLightCluster(rtEnvironement.reflLayerMask); // Compute the actual resolution that is needed base on the quality string targetRayGen = ""; switch (rtEnvironement.reflQualityMode) { case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes: { targetRayGen = m_RayGenHalfResName; }; break; case HDRaytracingEnvironment.ReflectionsQuality.Integration: { targetRayGen = m_RayGenIntegrationName; }; break; } // Define the shader pass to use for the reflection pass cmd.SetRaytracingShaderPass(reflectionShader, "ReflectionDXR"); // Set the acceleration structure for the pass cmd.SetRaytracingAccelerationStructure(reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray-tracing sampling data cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex); cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex); // Global reflection parameters cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingIntensityClamp, rtEnvironement.reflClampValue); cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingReflectionMinSmoothness, rtEnvironement.reflMinSmoothness); cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingReflectionMaxDistance, rtEnvironement.reflBlendDistance); // Inject the ray generation data cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtEnvironement.rayBias); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, rtEnvironement.reflRayLength); cmd.SetRaytracingIntParams(reflectionShader, HDShaderIDs._RaytracingNumSamples, rtEnvironement.reflNumMaxSamples); int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)frameCount % 8; cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Set the data for the ray generation cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrLightingTextureRW, m_LightingTexture); cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrHitPointTexture, m_HitPdfTexture); cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); // Set ray count tex cmd.SetRaytracingIntParam(reflectionShader, HDShaderIDs._RayCountEnabled, m_RaytracingManager.rayCountManager.RayCountIsEnabled()); cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._RayCountTexture, m_RaytracingManager.rayCountManager.rayCountTexture); // Compute the pixel spread value float pixelSpreadAngle = Mathf.Atan(2.0f * Mathf.Tan(hdCamera.camera.fieldOfView * Mathf.PI / 360.0f) / Mathf.Min(hdCamera.actualWidth, hdCamera.actualHeight)); cmd.SetRaytracingFloatParam(reflectionShader, HDShaderIDs._RaytracingPixelSpreadAngle, pixelSpreadAngle); // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas()); cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos()); cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos()); cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, rtEnvironement.maxNumLightsPercell); cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount()); cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount()); // Evaluate the clear coat mask texture based on the lit shader mode RenderTargetIdentifier clearCoatMaskTexture = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffersRTI()[2] : Texture2D.blackTexture; cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture); // Set the data for the ray miss cmd.SetRaytracingTextureParam(reflectionShader, m_MissShaderName, HDShaderIDs._SkyTexture, m_SkyManager.skyReflection); // Compute the actual resolution that is needed base on the quality uint widthResolution = 1, heightResolution = 1; switch (rtEnvironement.reflQualityMode) { case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes: { widthResolution = (uint)hdCamera.actualWidth / 2; heightResolution = (uint)hdCamera.actualHeight / 2; }; break; case HDRaytracingEnvironment.ReflectionsQuality.Integration: { widthResolution = (uint)hdCamera.actualWidth; heightResolution = (uint)hdCamera.actualHeight; }; break; } // Force to disable specular lighting cmd.SetGlobalInt(HDShaderIDs._EnableSpecularLighting, 0); // Run the calculus cmd.DispatchRays(reflectionShader, targetRayGen, widthResolution, heightResolution, 1); // Restore the previous state of specular lighting cmd.SetGlobalInt(HDShaderIDs._EnableSpecularLighting, hdCamera.frameSettings.IsEnabled(FrameSettingsField.SpecularLighting) ? 0 : 1); using (new ProfilingSample(cmd, "Filter Reflection", CustomSamplerId.RaytracingFilterReflection.GetSampler())) { switch (rtEnvironement.reflQualityMode) { case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes: { // Fetch the right filter to use int currentKernel = bilateralFilter.FindKernel("RaytracingReflectionFilter"); // Inject all the parameters for the compute cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrLightingTextureRW, m_LightingTexture); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrHitPointTexture, m_HitPdfTexture); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_NoiseTexture", blueNoise.textureArray16RGB); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_VarianceTexture", m_VarianceBuffer); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MinColorRangeTexture", m_MinBoundBuffer); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MaxColorRangeTexture", m_MaxBoundBuffer); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_RaytracingReflectionTexture", outputTexture); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex); cmd.SetComputeIntParam(bilateralFilter, HDShaderIDs._SpatialFilterRadius, rtEnvironement.reflSpatialFilterRadius); // Texture dimensions int texWidth = outputTexture.rt.width; int texHeight = outputTexture.rt.width; // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesXHR = (texWidth / 2 + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (texHeight / 2 + (areaTileSize - 1)) / areaTileSize; // Bind the right texture for clear coat support cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture); // Compute the texture cmd.DispatchCompute(bilateralFilter, currentKernel, numTilesXHR, numTilesYHR, 1); int numTilesXFR = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYFR = (texHeight + (areaTileSize - 1)) / areaTileSize; RTHandleSystem.RTHandle history = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedReflection) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedReflection, ReflectionHistoryBufferAllocatorFunction, 1); // Fetch the right filter to use currentKernel = bilateralFilter.FindKernel("TemporalAccumulationFilter"); cmd.SetComputeFloatParam(bilateralFilter, HDShaderIDs._TemporalAccumuationWeight, rtEnvironement.reflTemporalAccumulationWeight); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._AccumulatedFrameTexture, history); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._CurrentFrameTexture, outputTexture); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MinColorRangeTexture", m_MinBoundBuffer); cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MaxColorRangeTexture", m_MaxBoundBuffer); cmd.DispatchCompute(bilateralFilter, currentKernel, numTilesXFR, numTilesYFR, 1); } break; case HDRaytracingEnvironment.ReflectionsQuality.Integration: { HDUtils.BlitCameraTexture(cmd, hdCamera, m_LightingTexture, outputTexture); } break; } } }
void Start() { foregroundFilterShader = Resources.Load("ForegroundFiltDistShader") as ComputeShader; foregroundFilterKernel = foregroundFilterShader != null?foregroundFilterShader.FindKernel("FgFiltDist") : -1; }
private void ErodeHelper(Vector3 terrainScale, Rect domainRect, Vector2 texelSize, bool invertEffect, bool lowRes) { ComputeShader hydraulicCS = GetHydraulicCS(); ComputeShader thermalCS = GetThermalCS(); //this one is mandatory if (!inputTextures.ContainsKey("Height")) { throw (new Exception("No input heightfield specified!")); } int[] numWorkGroups = { 8, 8, 1 }; //figure out what size we need our render targets to be Vector2Int domainRes = new Vector2Int(inputTextures["Height"].width, inputTextures["Height"].height); int rx = domainRes.x - (numWorkGroups[0] * (domainRes.x / numWorkGroups[0])); int ry = domainRes.y - (numWorkGroups[1] * (domainRes.y / numWorkGroups[1])); domainRes.x += numWorkGroups[0] - rx; domainRes.y += numWorkGroups[1] - ry; if (lowRes) { domainRes.x /= 2; domainRes.y /= 2; } //maybe rebuild the render textures if (m_RTSize.x != domainRes.x || m_RTSize.y != domainRes.y) { ReleaseRenderTextures(); CreateRenderTextures(new Vector2Int(domainRes.x, domainRes.y)); } RenderTexture rt = RenderTexture.active; Graphics.Blit(inputTextures["Height"], m_HeightmapRT[0]); Graphics.Blit(inputTextures["Height"], m_HeightmapRT[1]); if (inputTextures.ContainsKey("Hardness")) { Graphics.Blit(inputTextures["Hardness"], m_HardnessRT); } else { Graphics.Blit(Texture2D.blackTexture, m_HardnessRT); } RenderTexture.active = rt; ClearRenderTextures(); int sedimentKernelIdx = hydraulicCS.FindKernel("HydraulicErosion"); int flowKernelIdx = hydraulicCS.FindKernel("SimulateWaterFlow"); int thermalKernelIdx = thermalCS.FindKernel("ThermalErosion"); float precipRate = 0.00001f * m_ErosionSettings.m_PrecipRate.value; float evaporationRate = 0.00001f * m_ErosionSettings.m_EvaporationRate.value; float flowRate = 0.0001f * m_ErosionSettings.m_FlowRate.value; float sedimentCap = 0.1f * m_ErosionSettings.m_SedimentCapacity.value; float sedimentDissolveRate = 0.0001f * m_ErosionSettings.m_SedimentDissolveRate.value; float sedimentDepositRate = 0.0001f * m_ErosionSettings.m_SedimentDepositRate.value; float simScale = 0.001f * Mathf.Max(m_ErosionSettings.m_SimScale.value, 0.000001f); float dx = (float)texelSize.x * simScale; float dy = (float)texelSize.y * simScale; float dxdy = Mathf.Sqrt(dx * dx + dy * dy); float effectScalar = m_ErosionSettings.m_IterationBlendScalar.value; //constants for both kernels hydraulicCS.SetFloat("EffectScalar", invertEffect ? effectScalar : -effectScalar); hydraulicCS.SetFloat("DT", m_ErosionSettings.m_HydroTimeDelta.value); hydraulicCS.SetVector("dxdy", new Vector4(dx, dy, 1.0f / dx, 1.0f / dy)); hydraulicCS.SetVector("WaterTransportScalars", new Vector4(m_ErosionSettings.m_WaterLevelScale, precipRate, flowRate * m_ErosionSettings.m_GravitationalConstant, evaporationRate)); hydraulicCS.SetVector("SedimentScalars", new Vector4(m_ErosionSettings.m_SedimentScale, sedimentCap, sedimentDissolveRate, sedimentDepositRate)); hydraulicCS.SetVector("RiverBedScalars", new Vector4(m_ErosionSettings.m_RiverBedDissolveRate.value, m_ErosionSettings.m_RiverBedDepositRate.value, m_ErosionSettings.m_RiverBankDissolveRate.value, m_ErosionSettings.m_RiverBankDepositRate.value)); hydraulicCS.SetVector("terrainDim", new Vector4(terrainScale.x, terrainScale.y, terrainScale.z)); hydraulicCS.SetVector("texDim", new Vector4((float)domainRes.x, (float)domainRes.y, 0.0f, 0.0f)); if (m_ErosionSettings.m_DoThermal) { //thermal kernel inputs Vector2 thermal_m = new Vector2(Mathf.Tan((float)m_ErosionSettings.m_ThermalReposeAngle * Mathf.Deg2Rad), Mathf.Tan((float)m_ErosionSettings.m_ThermalReposeAngle * Mathf.Deg2Rad)); thermalCS.SetFloat("dt", m_ErosionSettings.m_ThermalTimeDelta * m_ErosionSettings.m_HydroTimeDelta.value); thermalCS.SetFloat("EffectScalar", invertEffect ? effectScalar : -effectScalar); thermalCS.SetVector("angleOfRepose", new Vector4(thermal_m.x, thermal_m.y, 0.0f, 0.0f)); thermalCS.SetVector("dxdy", new Vector4(dx, dy, 1.0f / dx, 1.0f / dy)); thermalCS.SetFloat("InvDiagMag", 1.0f / Mathf.Sqrt(dx * dx + dy * dy)); thermalCS.SetVector("terrainDim", new Vector4(terrainScale.x, terrainScale.y, terrainScale.z)); thermalCS.SetVector("texDim", new Vector4((float)domainRes.x, (float)domainRes.y, 0.0f, 0.0f)); thermalCS.SetTexture(thermalKernelIdx, "TerrainHeightPrev", m_HeightmapRT[0]); thermalCS.SetTexture(thermalKernelIdx, "TerrainHeight", m_HeightmapRT[1]); thermalCS.SetTexture(thermalKernelIdx, "SedimentPrev", m_SedimentRT[0]); thermalCS.SetTexture(thermalKernelIdx, "Sediment", m_SedimentRT[1]); //thermalCS.SetTexture(thermalKernelIdx, "Collision", inputTextures["Collision"]); } int pingPongIdx = 0; for (int i = 0; i < (lowRes ? m_ErosionSettings.m_HydroLowResIterations : m_ErosionSettings.m_HydroIterations.value); i++) { int a = pingPongIdx; int b = (a + 1) % 2; #region Water Velocity Step //flow kernel textures hydraulicCS.SetTexture(flowKernelIdx, "TerrainHeightPrev", m_HeightmapRT[a]); hydraulicCS.SetTexture(flowKernelIdx, "WaterPrev", m_WaterRT[a]); hydraulicCS.SetTexture(flowKernelIdx, "Water", m_WaterRT[b]); hydraulicCS.SetTexture(flowKernelIdx, "WaterVelPrev", m_WaterVelRT[a]); hydraulicCS.SetTexture(flowKernelIdx, "WaterVel", m_WaterVelRT[b]); hydraulicCS.SetTexture(flowKernelIdx, "FluxPrev", m_FluxRT[a]); hydraulicCS.SetTexture(flowKernelIdx, "Flux", m_FluxRT[b]); hydraulicCS.Dispatch(flowKernelIdx, domainRes.x / numWorkGroups[0], domainRes.y / numWorkGroups[1], numWorkGroups[2]); #endregion #region Sediment Transport Step //sediment kernel textures hydraulicCS.SetTexture(sedimentKernelIdx, "TerrainHeightPrev", m_HeightmapRT[a]); hydraulicCS.SetTexture(sedimentKernelIdx, "TerrainHeight", m_HeightmapRT[b]); hydraulicCS.SetTexture(sedimentKernelIdx, "Water", m_WaterRT[a]); hydraulicCS.SetTexture(sedimentKernelIdx, "WaterPrev", m_WaterRT[b]); hydraulicCS.SetTexture(sedimentKernelIdx, "WaterVel", m_WaterVelRT[b]); hydraulicCS.SetTexture(sedimentKernelIdx, "Flux", m_FluxRT[b]); hydraulicCS.SetTexture(sedimentKernelIdx, "SedimentPrev", m_SedimentRT[a]); hydraulicCS.SetTexture(sedimentKernelIdx, "Sediment", m_SedimentRT[b]); hydraulicCS.SetTexture(sedimentKernelIdx, "Hardness", m_HardnessRT); hydraulicCS.SetTexture(sedimentKernelIdx, "Eroded", m_ErodedRT); hydraulicCS.Dispatch(sedimentKernelIdx, domainRes.x / numWorkGroups[0], domainRes.y / numWorkGroups[1], numWorkGroups[2]); #endregion #region Thermal Smoothing //now do a few thermal iterations to let things settle int thermalPingPongIdx = 0; for (int j = 0; m_ErosionSettings.m_DoThermal && (j < m_ErosionSettings.m_ThermalIterations); j++) { int ta = thermalPingPongIdx; int tb = (ta + 1) % 2; thermalCS.SetTexture(thermalKernelIdx, "TerrainHeightPrev", m_HeightmapRT[ta]); thermalCS.SetTexture(thermalKernelIdx, "TerrainHeight", m_HeightmapRT[tb]); thermalCS.SetTexture(thermalKernelIdx, "Hardness", m_HardnessRT); thermalCS.Dispatch(thermalKernelIdx, domainRes.x / numWorkGroups[0], domainRes.y / numWorkGroups[1], numWorkGroups[2]); thermalPingPongIdx = (thermalPingPongIdx + 1) % 2; } #endregion pingPongIdx = (pingPongIdx + 1) % 2; } // set up the output render textures outputTextures["Height"] = m_HeightmapRT[1]; outputTextures["Sediment"] = m_SedimentRT[1]; outputTextures["Water Level"] = m_WaterRT[1]; outputTextures["Water Velocity"] = m_WaterVelRT[1]; outputTextures["Water Flux"] = m_FluxRT[1]; outputTextures["Eroded Sediment"] = m_ErodedRT; }
/// <summary> /// Batch update. Reconstruct all meshes needed by running GPU based Marching Cubes /// </summary> private void BatchUpdate() { if (_nextUpdateblocks.Count == 0) { return; } //In order to also recompute the normals of vertices, we need to also sample "one more layer" in adjacent cells //"argumented block size" int ag1BlockSize = blockSize + 1; int ag2BlockSize = blockSize + 2; //the array that hold samples in order to send them to GPU float[] samples = new float[_nextUpdateblocks.Count * (ag2BlockSize) * (ag2BlockSize) * (ag2BlockSize)]; for (int blockNum = 0; blockNum < _nextUpdateblocks.Count; blockNum++) { var blockIdx = _nextUpdateblocks[blockNum]; int x = blockIdx._x; int y = blockIdx._y; int z = blockIdx._z; for (int ix = 0; ix < ag2BlockSize; ix++) { for (int iy = 0; iy < ag2BlockSize; iy++) { for (int iz = 0; iz < ag2BlockSize; iz++) { var queryX = x * blockSize + ix; var queryY = y * blockSize + iy; var queryZ = z * blockSize + iz; //store value samples[ix + iy * (ag2BlockSize) + iz * (ag2BlockSize) * (ag2BlockSize) + blockNum * (ag2BlockSize) * (ag2BlockSize) * (ag2BlockSize)] = _voxelSamples[queryX, queryY, queryZ]; } } } } //float startTime = Time.realtimeSinceStartup; ////rebuild normals int nrmKernel = _shaderNormal.FindKernel("SampleNormal"); if (nrmKernel < 0) { throw new UnityException("Fail to find kernel of shader: " + _shaderNormal.name); } ComputeBuffer bufferSamples = new ComputeBuffer(_nextUpdateblocks.Count * (ag2BlockSize) * (ag2BlockSize) * (ag2BlockSize), sizeof(float)); bufferSamples.SetData(samples); _shaderNormal.SetBuffer(nrmKernel, "_Samples", bufferSamples); ComputeBuffer bufferNormals = new ComputeBuffer(_nextUpdateblocks.Count * (ag1BlockSize) * (ag1BlockSize) * (ag1BlockSize), sizeof(float) * 3); _shaderNormal.SetBuffer(nrmKernel, "_Normals", bufferNormals); //dispatch compute shader _shaderNormal.Dispatch(nrmKernel, _nextUpdateblocks.Count, 1, 1); //marching-cube //STAGE I: collect triangle number int ctnKernel = _shaderCollectTriNum.FindKernel("CollectTriNum"); if (ctnKernel < 0) { throw new UnityException("Fail to find kernel of shader: " + _shaderCollectTriNum.name); } ComputeBuffer bufferTriNum = new ComputeBuffer(1, sizeof(int)); bufferTriNum.SetData(new int[] { 0 }); ComputeBuffer bufferCornerFlags = new ComputeBuffer(_nextUpdateblocks.Count * blockSize * blockSize * blockSize, sizeof(int)); _shaderCollectTriNum.SetBuffer(ctnKernel, "_Samples", bufferSamples); _shaderCollectTriNum.SetBuffer(ctnKernel, "_CornerToTriNumTable", _bufferCornerToTriNumTable); _shaderCollectTriNum.SetBuffer(ctnKernel, "_TriNum", bufferTriNum); _shaderCollectTriNum.SetBuffer(ctnKernel, "_CornerFlags", bufferCornerFlags); _shaderCollectTriNum.Dispatch(ctnKernel, _nextUpdateblocks.Count, 1, 1); int[] triNum = new int[1]; bufferTriNum.GetData(triNum); if (triNum[0] == 0) { //no triangles, early exit bufferNormals.Release(); bufferSamples.Release(); bufferTriNum.Release(); bufferCornerFlags.Release(); return; } //Debug.Log("triangles count " + triNum[0]); //STAGE II: do marching cube int mcKernel = _shaderMarchingCube.FindKernel("MarchingCube"); if (mcKernel < 0) { throw new UnityException("Fail to find kernel of shader: " + _shaderMarchingCube.name); } ComputeBuffer bufferMeshes = new ComputeBuffer(triNum[0], CSTriangle.stride); ComputeBuffer bufferTriEndIndex = new ComputeBuffer(1, sizeof(int)); bufferTriEndIndex.SetData(new int[] { 0 }); _shaderMarchingCube.SetBuffer(mcKernel, "_Samples", bufferSamples); _shaderMarchingCube.SetBuffer(mcKernel, "_Normals", bufferNormals); _shaderMarchingCube.SetBuffer(mcKernel, "_CornerFlags", bufferCornerFlags); _shaderMarchingCube.SetBuffer(mcKernel, "_CornerToEdgeTable", _bufferCornerToEdgeTable); _shaderMarchingCube.SetBuffer(mcKernel, "_CornerToVertTable", _bufferCornerToVertTable); _shaderMarchingCube.SetBuffer(mcKernel, "_Meshes", bufferMeshes); _shaderMarchingCube.SetBuffer(mcKernel, "_TriEndIndex", bufferTriEndIndex); //dispatch compute shader _shaderMarchingCube.Dispatch(mcKernel, _nextUpdateblocks.Count, 1, 1); //split bufferMeshes to meshes for individual blocks CSTriangle[] csTriangles = new CSTriangle[triNum[0]];//triNum[0] is the counter bufferMeshes.GetData(csTriangles); List <Vector3>[] vertices = new List <Vector3> [_nextUpdateblocks.Count]; List <Vector3>[] normals = new List <Vector3> [_nextUpdateblocks.Count]; for (int i = 0; i < _nextUpdateblocks.Count; i++) { vertices[i] = new List <Vector3>(); normals[i] = new List <Vector3>(); } foreach (var vt in csTriangles) { vertices[vt._block].Add(vt._position0 * _voxelScale); vertices[vt._block].Add(vt._position1 * _voxelScale); vertices[vt._block].Add(vt._position2 * _voxelScale); normals[vt._block].Add(vt._normal0); normals[vt._block].Add(vt._normal1); normals[vt._block].Add(vt._normal2); } for (int i = 0; i < _nextUpdateblocks.Count; i++) { var x = _nextUpdateblocks[i]._x; var y = _nextUpdateblocks[i]._y; var z = _nextUpdateblocks[i]._z; _blocks[x, y, z].GetComponent <MeshFilter>().mesh.Clear(); var mesh = new Mesh(); mesh.vertices = vertices[i].ToArray(); var idx = Enumerable.Range(0, vertices[i].Count).ToArray(); mesh.SetTriangles(idx, 0); mesh.normals = normals[i].ToArray(); mesh.Optimize(); mesh.RecalculateBounds(); _blocks[x, y, z].GetComponent <MeshFilter>().mesh = mesh; _blocks[x, y, z].GetComponent <MeshRenderer>().material = _material; _blocks[x, y, z].GetComponent <MeshCollider>().sharedMesh = mesh; } //Debug.Log("Time taken: " + (Time.realtimeSinceStartup - startTime) * 1000.0f); bufferNormals.Release(); bufferSamples.Release(); bufferTriNum.Release(); bufferCornerFlags.Release(); bufferMeshes.Release(); bufferTriEndIndex.Release(); }
public virtual void FindKernel() { kernel = shader.FindKernel(kernelName); }
private bool CreateCoordMapperShader(KinectInterop.SensorData sensorData, bool bColor2Depth) { if (_depthCameraIntrinsics == null || _colorCameraIntrinsics == null || _coordinateMapper == null) { return(false); } System.Numerics.Matrix4x4?matrix = !bColor2Depth ? _coordinateMapper.DepthToColorMatrix : _coordinateMapper.ColorToDepthMatrix; if (_coordMapperShader == null) { _coordMapperShader = matrix.HasValue ? Resources.Load("CoordMapper") as ComputeShader : null; } if (_coordMapperShader) { _depth2colorKernel = _coordMapperShader.FindKernel("MapDepthFrame2ColorFrame"); _color2depthKernel = _coordMapperShader.FindKernel("MapColorSpace2DepthFrame"); float[] depthFocalLength = new float[] { _depthCameraIntrinsics.FocalLengthX, _depthCameraIntrinsics.FocalLengthY }; float[] depthPrincipalPoint = new float[] { _depthCameraIntrinsics.PrincipalPointX, _depthCameraIntrinsics.PrincipalPointY }; float[] depthRadialDistortion = new float[] { _depthCameraIntrinsics.RadialDistortionSecondOrder, _depthCameraIntrinsics.RadialDistortionFourthOrder, _depthCameraIntrinsics.RadialDistortionSixthOrder }; _coordMapperShader.SetFloats("depthFocalLength", depthFocalLength); _coordMapperShader.SetFloats("depthPrincipalPoint", depthPrincipalPoint); _coordMapperShader.SetFloats("depthRadialDistortion", depthRadialDistortion); float[] colorFocalLength = new float[] { _colorCameraIntrinsics.FocalLengthX, _colorCameraIntrinsics.FocalLengthY }; float[] colorPrincipalPoint = new float[] { _colorCameraIntrinsics.PrincipalPointX, _colorCameraIntrinsics.PrincipalPointY }; float[] colorRadialDistortion = new float[] { _colorCameraIntrinsics.RadialDistortionSecondOrder, _colorCameraIntrinsics.RadialDistortionFourthOrder, _colorCameraIntrinsics.RadialDistortionSixthOrder }; _coordMapperShader.SetFloats("colorFocalLength", colorFocalLength); _coordMapperShader.SetFloats("colorPrincipalPoint", colorPrincipalPoint); _coordMapperShader.SetFloats("colorRadialDistortion", colorRadialDistortion); float[] space2spaceMat = new float[] { matrix.Value.M11, matrix.Value.M12, matrix.Value.M13, matrix.Value.M14, matrix.Value.M21, matrix.Value.M22, matrix.Value.M23, matrix.Value.M24, matrix.Value.M31, matrix.Value.M32, matrix.Value.M33, matrix.Value.M34, matrix.Value.M41, matrix.Value.M42, matrix.Value.M43, matrix.Value.M44 }; if (!bColor2Depth) { _coordMapperShader.SetFloats("depth2colorMat", space2spaceMat); } else { _coordMapperShader.SetFloats("color2depthMat", space2spaceMat); } // compute buffers int depthImageLength = sensorData.depthImageWidth * sensorData.depthImageHeight; if (_depthDepthValuesBuf == null) { _depthDepthValuesBuf = new ComputeBuffer(depthImageLength, sizeof(int)); _coordMapperShader.SetBuffer(_depth2colorKernel, "depthDepthValues", _depthDepthValuesBuf); } if (!bColor2Depth) { _depthPlaneCoordsBuf = new ComputeBuffer(depthImageLength, 2 * sizeof(float)); _colorPlaneCoordsBuf = new ComputeBuffer(depthImageLength, 2 * sizeof(float)); // set plane coords Vector2[] depthPlaneCoords = new Vector2[depthImageLength]; for (int dy = 0, di = 0; dy < sensorData.depthImageHeight; dy++) { for (int dx = 0; dx < sensorData.depthImageWidth; dx++) { depthPlaneCoords[di] = new Vector2(dx, dy); di++; } } _depthPlaneCoordsBuf.SetData(depthPlaneCoords); _coordMapperShader.SetBuffer(_depth2colorKernel, "depthPlaneCoords", _depthPlaneCoordsBuf); _coordMapperShader.SetBuffer(_depth2colorKernel, "colorPlaneCoords", _colorPlaneCoordsBuf); } else { int colorImageLength = sensorData.colorImageWidth * sensorData.colorImageHeight; _colorSpaceCoordsBuf = new ComputeBuffer(colorImageLength, 3 * sizeof(float)); _colorDepthCoordsBuf = new ComputeBuffer(colorImageLength, 2 * sizeof(float)); _coordMapperShader.SetBuffer(_color2depthKernel, "colorSpaceCoords", _colorSpaceCoordsBuf); _coordMapperShader.SetBuffer(_color2depthKernel, "colorDepthCoords", _colorDepthCoordsBuf); } } return(_coordMapperShader != null); }
void Start() { _updateAgentsKernel = SlimeCompute.FindKernel("UpdateAgents"); _diffuseKernel = SlimeCompute.FindKernel("Diffuse"); _particleKernel = SlimeCompute.FindKernel("CreateAgentParticles"); _trailKernel = SlimeCompute.FindKernel("UpdateTrailPoints"); _geometryKernel = SlimeCompute.FindKernel("CreateTrailGeometry"); _accumulationTexture = new RenderTexture(TextureSize, TextureSize, 1, RenderTextureFormat.RFloat); _accumulationTexture.enableRandomWrite = true; _previousAccumulationTexture = new RenderTexture(TextureSize, TextureSize, 1, RenderTextureFormat.RFloat); _previousAccumulationTexture.enableRandomWrite = true; AccumulationMaterial.SetTexture("_MainTex", _accumulationTexture); _agentsBuffer = new ComputeBuffer(AgentCount, Marshal.SizeOf(typeof(Agent))); var agents = new Agent[AgentCount]; for (var i = 0; i < agents.Length; i++) { agents[i] = new Agent { Position = Random.insideUnitCircle * ZoneRadius, Angle = Random.value * Mathf.PI * 2 }; } _agentsBuffer.SetData(agents); _parameterBuffer = new ComputeBuffer(1, Marshal.SizeOf(typeof(SlimeSettings))); _spawnBuffer = new ComputeBuffer(1, Marshal.SizeOf(typeof(Vector2))); _spawnBuffer.SetData(new [] { Vector2.zero }); _trailBuffer = new ComputeBuffer(ParticleCount * TrailPoints, Marshal.SizeOf(typeof(Vector3))); _trailPreviousBuffer = new ComputeBuffer(ParticleCount * TrailPoints, Marshal.SizeOf(typeof(Vector3))); var trailData = Enumerable.Repeat(Vector3.zero, _trailBuffer.count).ToArray(); _trailBuffer.SetData(trailData); _trailPreviousBuffer.SetData(trailData); _particlesBuffer = new ComputeBuffer(ParticleCount, Marshal.SizeOf(typeof(Particle))); _vertexBuffer = new ComputeBuffer(ParticleCount * 2 * TrailPoints, Marshal.SizeOf(typeof(Vertex))); var indexData = new int[IndexBufferSize]; var index = 0; for (int iTrail = 0; iTrail < ParticleCount; iTrail++) { var trailOffset = iTrail * TrailPoints * 2; for (int iTrailPoint = 0; iTrailPoint < TrailPoints - 1; iTrailPoint++) { var offset = trailOffset + iTrailPoint * 2; indexData[index++] = 0 + offset; indexData[index++] = 1 + offset; indexData[index++] = 2 + offset; indexData[index++] = 2 + offset; indexData[index++] = 1 + offset; indexData[index++] = 3 + offset; } } _indexBuffer = new ComputeBuffer(indexData.Length, Marshal.SizeOf(typeof(uint))); // 1 trail point to 2 triangles (6 vertices) _indexBuffer.SetData(indexData); }
public Uploader() { cs = Resources.Load <ComputeShader>(PATH); K_UPLOAD_FLOAT = cs.FindKernel("UploadFloat"); K_UPLOAD_INT = cs.FindKernel("UploadInt"); }
public Clear() { cs = Resources.Load <ComputeShader>(PATH); K_CLEAR_FLOAT = cs.FindKernel("ClearFloat"); K_CLEAR_INT = cs.FindKernel("ClearInt"); }
public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle outputTexture, ScriptableRenderContext renderContext, int frameCount) { // Let's check all the resources HDRaytracingEnvironment rtEnvironment = m_RaytracingManager.CurrentEnvironment(); ComputeShader aoFilter = m_PipelineRayTracingResources.raytracingAOFilterCS; RaytracingShader aoShader = m_PipelineRayTracingResources.aoRaytracing; var aoSettings = VolumeManager.instance.stack.GetComponent <AmbientOcclusion>(); // Check if the state is valid for evaluating ambient occlusion bool invalidState = rtEnvironment == null || aoFilter == null || aoShader == null || m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null; // If any of the previous requirements is missing, the effect is not requested or no acceleration structure, set the default one and leave right away if (invalidState) { SetDefaultAmbientOcclusionTexture(cmd); return; } // Grab the acceleration structure for the target camera RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(rtEnvironment.aoLayerMask); // Define the shader pass to use for the reflection pass cmd.SetRaytracingShaderPass(aoShader, "VisibilityDXR"); // Set the acceleration structure for the pass cmd.SetRaytracingAccelerationStructure(aoShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray-tracing sampling data cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex); cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex); // Inject the ray generation data cmd.SetRaytracingFloatParams(aoShader, HDShaderIDs._RaytracingRayBias, rtEnvironment.rayBias); cmd.SetRaytracingFloatParams(aoShader, HDShaderIDs._RaytracingRayMaxLength, aoSettings.rayLength.value); cmd.SetRaytracingIntParams(aoShader, HDShaderIDs._RaytracingNumSamples, aoSettings.numSamples.value); // Set the data for the ray generation cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)frameCount % 8; cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Value used to scale the ao intensity cmd.SetRaytracingFloatParam(aoShader, HDShaderIDs._RaytracingAOIntensity, aoSettings.intensity.value); cmd.SetRaytracingIntParam(aoShader, HDShaderIDs._RayCountEnabled, m_RaytracingManager.rayCountManager.RayCountIsEnabled()); cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._RayCountTexture, m_RaytracingManager.rayCountManager.rayCountTexture); // Set the output textures cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._AmbientOcclusionTextureRW, m_IntermediateBuffer); cmd.SetRaytracingTextureParam(aoShader, HDShaderIDs._RaytracingVSNormalTexture, m_ViewSpaceNormalBuffer); // Run the computation cmd.DispatchRays(aoShader, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1); using (new ProfilingSample(cmd, "Filter Reflection", CustomSamplerId.RaytracingAmbientOcclusion.GetSampler())) { if (aoSettings.enableFilter.value) { // Grab the history buffer RTHandleSystem.RTHandle ambientOcclusionHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion, AmbientOcclusionHistoryBufferAllocatorFunction, 1); // Texture dimensions int texWidth = hdCamera.actualWidth; int texHeight = hdCamera.actualHeight; // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesX = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesY = (texHeight + (areaTileSize - 1)) / areaTileSize; m_KernelFilter = aoFilter.FindKernel("AOApplyTAA"); // Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel var historyScale = new Vector2(hdCamera.actualWidth / (float)ambientOcclusionHistory.rt.width, hdCamera.actualHeight / (float)ambientOcclusionHistory.rt.height); cmd.SetComputeVectorParam(aoFilter, HDShaderIDs._RTHandleScaleHistory, historyScale); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_IntermediateBuffer); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._AOHistorybuffer, ambientOcclusionHistory); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, m_ViewSpaceNormalBuffer); cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1); // Output the new history m_KernelFilter = aoFilter.FindKernel("AOCopyHistory"); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_ViewSpaceNormalBuffer); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, ambientOcclusionHistory); cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1); m_KernelFilter = aoFilter.FindKernel("AOBilateralFilterH"); // Horizontal pass of the bilateral filter cmd.SetComputeIntParam(aoFilter, HDShaderIDs._RaytracingDenoiseRadius, aoSettings.filterRadius.value); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_ViewSpaceNormalBuffer); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, m_IntermediateBuffer); cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1); m_KernelFilter = aoFilter.FindKernel("AOBilateralFilterV"); // Horizontal pass of the bilateral filter cmd.SetComputeIntParam(aoFilter, HDShaderIDs._RaytracingDenoiseRadius, aoSettings.filterRadius.value); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_IntermediateBuffer); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, outputTexture); cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1); } else { HDUtils.BlitCameraTexture(cmd, m_IntermediateBuffer, outputTexture); } } // Bind the textures and the params cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture); cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(0f, 0f, 0f, VolumeManager.instance.stack.GetComponent <AmbientOcclusion>().directLightingStrength.value)); // TODO: All the push-debug stuff should be centralized somewhere (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.SSAO); }
void Start() { Application.targetFrameRate = 300; // Create initial positions total = x * y * z; m_matrices = new Matrix4x4[total]; positionArray = new Vector3[total]; quaternionArray = new Quaternion[total]; rigidBodyVelocitiesArray = new Vector3[total]; m_cubeScale = new Vector3(scale, scale, scale); m_deltaTimeShaderProperty = Shader.PropertyToID("deltaTime"); rigidBodyInertialTensors = new float[total * 9]; int particlesPerEdgeMinusOne = particlesPerEdge - 2; int particlesPerBody = particlesPerEdge * particlesPerEdge * particlesPerEdge - particlesPerEdgeMinusOne * particlesPerEdgeMinusOne * particlesPerEdgeMinusOne; int n_particles = particlesPerBody * total; int numGridCells = gridX * gridY * gridZ; float particleDiameter = scale / particlesPerEdge; particleForcesArray = new Vector3[n_particles]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { positionArray[IDX(i, j, k)] = new Vector3(i * scale, j * scale, k * scale) + new Vector3(0.5f * scale, 0.5f * scale, 0.5f * scale); quaternionArray[IDX(i, j, k)] = Quaternion.identity; rigidBodyVelocitiesArray[IDX(i, j, k)] = Vector3.zero; } } } // rigid body velocities positionArray[IDX(0, y - 1, 0)] = m_firstCubeLocation; rigidBodyVelocitiesArray[IDX(0, y - 1, 0)] = m_firstCubeVelocity; quaternionArray[IDX(0, y - 1, 0)] = Quaternion.Euler(m_firstCubeRotation); particleVelocities = new Vector3[n_particles]; particlePositions = new Vector3[n_particles]; particleRelativePositions = new Vector3[n_particles]; debugParticleIds = new int[debug_particle_id_count]; voxelGridArray = new int[numGridCells * 4]; particleVoxelPositionsArray = new int[n_particles * 3]; // Get Kernels m_kernel_generateParticleValues = m_computeShader.FindKernel("GenerateParticleValues"); m_kernel_clearGrid = m_computeShader.FindKernel("ClearGrid"); m_kernel_populateGrid = m_computeShader.FindKernel("PopulateGrid"); m_kernel_collisionDetection = m_computeShader.FindKernel("CollisionDetection"); m_kernel_computeMomenta = m_computeShader.FindKernel("ComputeMomenta"); m_kernel_computePositionAndRotation = m_computeShader.FindKernel("ComputePositionAndRotation"); m_kernelSavePreviousPositionAndRotation = m_computeShader.FindKernel("SavePreviousPositionAndRotation"); // Count Thread Groups m_threadGroupsPerRigidBody = Mathf.CeilToInt(total / 8.0f); m_threadGroupsPerParticle = Mathf.CeilToInt(n_particles / 8f); m_threadGroupsPerGridCell = Mathf.CeilToInt((gridX * gridY * gridZ) / 8f); // Create initial buffers const int floatThree = 3 * sizeof(float); const int floatFour = 4 * sizeof(float); const int intFour = 4 * sizeof(int); const int intThree = 3 * sizeof(int); const int floatNine = 9 * sizeof(float); m_rigidBodyPositions = new ComputeBuffer(total, floatThree); m_previousRigidBodyPositions = new ComputeBuffer(total, floatThree); m_rigidBodyQuaternions = new ComputeBuffer(total, floatFour); m_previousRigidBodyQuaternions = new ComputeBuffer(total, floatFour); m_rigidBodyAngularVelocities = new ComputeBuffer(total, floatThree); m_rigidBodyVelocities = new ComputeBuffer(total, floatThree); m_rigidBodyInertialTensors = new ComputeBuffer(total, floatNine); m_particleInitialRelativePositions = new ComputeBuffer(n_particles, floatThree); m_particlePositions = new ComputeBuffer(n_particles, floatThree); m_particleRelativePositions = new ComputeBuffer(n_particles, floatThree); m_particleVelocities = new ComputeBuffer(n_particles, floatThree); m_particleForces = new ComputeBuffer(n_particles, floatThree); m_voxelCollisionGrid = new ComputeBuffer(numGridCells, intFour); m_debugParticleVoxelPositions = new ComputeBuffer(n_particles, intThree); m_debugParticleIds = new ComputeBuffer(debug_particle_id_count, sizeof(int)); Debug.Log("nparticles: " + n_particles); // initialize constants int[] gridDimensions = new int[] { gridX, gridY, gridZ }; m_computeShader.SetInts("gridDimensions", gridDimensions); m_computeShader.SetInt("gridMax", numGridCells); m_computeShader.SetInt("particlesPerRigidBody", particlesPerBody); m_computeShader.SetFloat("particleDiameter", particleDiameter); m_computeShader.SetFloat("springCoefficient", springCoefficient); m_computeShader.SetFloat("dampingCoefficient", dampingCoefficient); m_computeShader.SetFloat("frictionCoefficient", frictionCoefficient); m_computeShader.SetFloat("angularFrictionCoefficient", angularFrictionCoefficient); m_computeShader.SetFloat("gravityCoefficient", gravityCoefficient); m_computeShader.SetFloat("tangentialCoefficient", tangentialCoefficient); m_computeShader.SetFloat("angularForceScalar", angularForceScalar); m_computeShader.SetFloat("linearForceScalar", linearForceScalar); m_computeShader.SetFloat("particleMass", m_cubeMass / particlesPerBody); m_computeShader.SetFloats("gridStartPosition", new float[] { gridStartPosition.x, gridStartPosition.y, gridStartPosition.z }); // Inertial tensor of a cube formula taken from textbook: // "Essential Mathematics for Games and Interactive Applications" // by James Van Verth and Lars Bishop float twoDimSq = 2.0f * (scale * scale); float inertialTensorFactor = m_cubeMass * 1.0f / 12.0f * twoDimSq; float[] inertialTensor = { inertialTensorFactor, 0.0f, 0.0f, 0.0f, inertialTensorFactor, 0.0f, 0.0f, 0.0f, inertialTensorFactor }; float[] inverseInertialTensor; GPUPhysics.Invert(ref inertialTensor, out inverseInertialTensor); float[] quickInverseInertialTensor = { 1.0f / inertialTensorFactor, 0.0f, 0.0f, 0.0f, 1.0f / inertialTensorFactor, 0.0f, 0.0f, 0.0f, 1.0f / inertialTensorFactor }; m_computeShader.SetFloats("inertialTensor", inertialTensor); m_computeShader.SetFloats("inverseInertialTensor", quickInverseInertialTensor); // initialize buffers // initial relative positions // super dependent on 8/rigid body particleInitialRelativePositions = new Vector3[n_particles]; Vector3[] particleInitialsSmall = new Vector3[particlesPerBody]; int initialRelativePositionIterator = 0; float centerer = scale * -0.5f + particleDiameter * 0.5f; Vector3 centeringOffset = new Vector3(centerer, centerer, centerer); for (int xIter = 0; xIter < particlesPerEdge; xIter++) { for (int yIter = 0; yIter < particlesPerEdge; yIter++) { for (int zIter = 0; zIter < particlesPerEdge; zIter++) { if (xIter == 0 || xIter == (particlesPerEdge - 1) || yIter == 0 || yIter == (particlesPerEdge - 1) || zIter == 0 || zIter == (particlesPerEdge - 1)) { particleInitialsSmall[initialRelativePositionIterator] = centeringOffset + new Vector3(xIter * particleDiameter, yIter * particleDiameter, zIter * particleDiameter); initialRelativePositionIterator++; } } } } for (int i = 0; i < particleInitialRelativePositions.Length; i++) { particleInitialRelativePositions[i] = particleInitialsSmall[i % particlesPerBody]; } m_particleInitialRelativePositions.SetData(particleInitialRelativePositions); // rigid body positions m_rigidBodyPositions.SetData(positionArray); // rigid body quaternions m_rigidBodyQuaternions.SetData(quaternionArray); m_rigidBodyVelocities.SetData(rigidBodyVelocitiesArray); // Set matricies to initial positions SetMatrices(positionArray, quaternionArray); // Bind buffers // kernel 0 GenerateParticleValues m_computeShader.SetBuffer(m_kernel_generateParticleValues, "rigidBodyPositions", m_rigidBodyPositions); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "rigidBodyQuaternions", m_rigidBodyQuaternions); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "rigidBodyAngularVelocities", m_rigidBodyAngularVelocities); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "rigidBodyVelocities", m_rigidBodyVelocities); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "particleInitialRelativePositions", m_particleInitialRelativePositions); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "particlePositions", m_particlePositions); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "particleRelativePositions", m_particleRelativePositions); m_computeShader.SetBuffer(m_kernel_generateParticleValues, "particleVelocities", m_particleVelocities); //m_computeShader.SetBuffer(m_kernel_generateParticleValues, "debugParticleIds", m_debugParticleIds); // kernel 1 ClearGrid m_computeShader.SetBuffer(m_kernel_clearGrid, "voxelCollisionGrid", m_voxelCollisionGrid); // kernel 2 Populate Grid m_computeShader.SetBuffer(m_kernel_populateGrid, "debugParticleVoxelPositions", m_debugParticleVoxelPositions); m_computeShader.SetBuffer(m_kernel_populateGrid, "voxelCollisionGrid", m_voxelCollisionGrid); m_computeShader.SetBuffer(m_kernel_populateGrid, "particlePositions", m_particlePositions); //m_computeShader.SetBuffer(m_kernel_populateGrid, "debugParticleIds", m_debugParticleIds); // kernel 3 Collision Detection m_computeShader.SetBuffer(m_kernel_collisionDetection, "particlePositions", m_particlePositions); m_computeShader.SetBuffer(m_kernel_collisionDetection, "particleVelocities", m_particleVelocities); m_computeShader.SetBuffer(m_kernel_collisionDetection, "voxelCollisionGrid", m_voxelCollisionGrid); m_computeShader.SetBuffer(m_kernel_collisionDetection, "particleForces", m_particleForces); // kernel 4 Computation of Momenta m_computeShader.SetBuffer(m_kernel_computeMomenta, "particleForces", m_particleForces); m_computeShader.SetBuffer(m_kernel_computeMomenta, "particleRelativePositions", m_particleRelativePositions); m_computeShader.SetBuffer(m_kernel_computeMomenta, "rigidBodyAngularVelocities", m_rigidBodyAngularVelocities); m_computeShader.SetBuffer(m_kernel_computeMomenta, "rigidBodyVelocities", m_rigidBodyVelocities); m_computeShader.SetBuffer(m_kernel_computeMomenta, "debugParticleIds", m_debugParticleIds); m_computeShader.SetBuffer(m_kernel_computeMomenta, "rigidBodyQuaternions", m_rigidBodyQuaternions); // kernel 5 Compute Position and Rotation m_computeShader.SetBuffer(m_kernel_computePositionAndRotation, "rigidBodyVelocities", m_rigidBodyVelocities); m_computeShader.SetBuffer(m_kernel_computePositionAndRotation, "rigidBodyAngularVelocities", m_rigidBodyAngularVelocities); m_computeShader.SetBuffer(m_kernel_computePositionAndRotation, "rigidBodyPositions", m_rigidBodyPositions); m_computeShader.SetBuffer(m_kernel_computePositionAndRotation, "rigidBodyQuaternions", m_rigidBodyQuaternions); m_computeShader.SetBuffer(m_kernel_computePositionAndRotation, "inverseInertialMatrices", m_rigidBodyInertialTensors); // kernel 6 Save Previous Position and Rotation m_computeShader.SetBuffer(m_kernelSavePreviousPositionAndRotation, "rigidBodyPositions", m_rigidBodyPositions); m_computeShader.SetBuffer(m_kernelSavePreviousPositionAndRotation, "rigidBodyQuaternions", m_rigidBodyQuaternions); m_computeShader.SetBuffer(m_kernelSavePreviousPositionAndRotation, "previousRigidBodyPositions", m_previousRigidBodyPositions); m_computeShader.SetBuffer(m_kernelSavePreviousPositionAndRotation, "previousRigidBodyQuaternions", m_previousRigidBodyQuaternions); // Setup Indirect Renderer uint[] sphereArgs = new uint[] { sphereMesh.GetIndexCount(0), (uint)n_particles, 0, 0, 0 }; m_bufferWithSphereArgs = new ComputeBuffer(1, sphereArgs.Length * sizeof(uint), ComputeBufferType.IndirectArguments); m_bufferWithSphereArgs.SetData(sphereArgs); uint[] lineArgs = new uint[] { lineMesh.GetIndexCount(0), (uint)n_particles, 0, 0, 0 }; m_bufferWithLineArgs = new ComputeBuffer(1, lineArgs.Length * sizeof(uint), ComputeBufferType.IndirectArguments); m_bufferWithLineArgs.SetData(lineArgs); cubeMaterial.SetBuffer("positions", m_rigidBodyPositions); cubeMaterial.SetBuffer("previousPositions", m_previousRigidBodyPositions); cubeMaterial.SetBuffer("quaternions", m_rigidBodyQuaternions); cubeMaterial.SetBuffer("previousQuaternions", m_previousRigidBodyQuaternions); sphereMaterial.SetBuffer("positions", m_particlePositions); sphereMaterial.SetVector("scale", new Vector4(particleDiameter * 0.5f, particleDiameter * 0.5f, particleDiameter * 0.5f, 1.0f)); lineMaterial.SetBuffer("positions", m_particlePositions); lineMaterial.SetBuffer("vectors", m_particleVelocities); // Setup Command Buffer m_commandBuffer = new CommandBuffer(); m_commandBuffer.BeginSample("GenerateParticleValues"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_generateParticleValues, m_threadGroupsPerRigidBody, 1, 1); m_commandBuffer.EndSample("GenerateParticleValues"); m_commandBuffer.BeginSample("ClearGrid"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_clearGrid, m_threadGroupsPerGridCell, 1, 1); m_commandBuffer.EndSample("ClearGrid"); m_commandBuffer.BeginSample("PopulateGrid"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_populateGrid, m_threadGroupsPerParticle, 1, 1); m_commandBuffer.EndSample("PopulateGrid"); m_commandBuffer.BeginSample("CollisionDetection"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_collisionDetection, m_threadGroupsPerParticle, 1, 1); m_commandBuffer.EndSample("CollisionDetection"); m_commandBuffer.BeginSample("ComputeMomenta"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_computeMomenta, m_threadGroupsPerRigidBody, 1, 1); m_commandBuffer.EndSample("ComputeMomenta"); m_commandBuffer.BeginSample("ComputePositions"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernel_computePositionAndRotation, m_threadGroupsPerRigidBody, 1, 1); m_commandBuffer.EndSample("ComputePositions"); m_commandBuffer.BeginSample("SavePreviousPositionAndRotation"); m_commandBuffer.DispatchCompute(m_computeShader, m_kernelSavePreviousPositionAndRotation, m_threadGroupsPerRigidBody, 1, 1); m_commandBuffer.EndSample("SavePreviousPositionAndRotation"); // rendering in command buffer - doesnt work for now seems like a unity bug #if !(UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX) // Command Buffer DrawMeshInstancedIndirect doesnt work on my mac // rendering from command buffer via update isnt working so disabling this is necessary for delta time use // m_commandBuffer.BeginSample("DrawMeshInstancedIndirect"); // m_commandBuffer.DrawMeshInstancedIndirect(cubeMesh, 0, cubeMaterial, 0, m_bufferWithArgs); // m_commandBuffer.EndSample("DrawMeshInstancedIndirect"); #endif // Camera.main.AddCommandBuffer(CameraEvent.AfterSkybox, m_commandBuffer); }
void OnEnable() { if (!IVS) { return; } cam.forceIntoRenderTexture = true; var data = IVS.Points; stippleCount = data.Length; Debug.Assert(stippleCount == (1024 * 1024)); points = new ComputeBuffer(stippleCount, 2 * sizeof(float), ComputeBufferType.Default); particles = new ComputeBuffer(stippleCount, 3 * sizeof(float), ComputeBufferType.Append); args = new ComputeBuffer(5, sizeof(uint), ComputeBufferType.IndirectArguments); points.SetData(data); quad = new Mesh(); quad.name = "Quad"; quad.vertices = new Vector3[] { new Vector3(-1.0f, -1.0f, 0.0f), new Vector3(1.0f, -1.0f, 0.0f), new Vector3(-1.0f, 1.0f, 0.0f), new Vector3(1.0f, 1.0f, 0.0f), }; quad.uv = new Vector2[] { new Vector2(0.0f, 0.0f), new Vector2(1.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 1.0f), }; quad.triangles = new int[] { 0, 1, 2, 1, 3, 2, }; args.SetData(new uint[] { (uint)quad.GetIndexCount(0), (uint)0, (uint)quad.GetIndexStart(0), (uint)quad.GetBaseVertex(0), (uint)0, }); blitMat = new Material(Shader.Find("Hidden/BlitFlip")); stipplingMat = new Material(Shader.Find("Hidden/Stippling")); SetShaderParams(); stipplingMat.SetBuffer("_Particles", particles); uint gx, gy, gz; var kernel = VoronoiCompute.FindKernel("StreamStipples"); VoronoiCompute.GetKernelThreadGroupSizes(kernel, out gx, out gy, out gz); var dispatch = 1 + (((uint)stippleCount - 1) / gx); commands = new CommandBuffer(); commands.name = "StipplingEffect"; var texId = Shader.PropertyToID("_ScreenTexture"); commands.GetTemporaryRT(texId, -1, -1, 0); commands.Blit(BuiltinRenderTextureType.CameraTarget, texId); commands.SetComputeTextureParam(VoronoiCompute, kernel, "_ScreenTexture", texId); commands.SetComputeBufferParam(VoronoiCompute, kernel, "_Points", points); commands.SetComputeBufferParam(VoronoiCompute, kernel, "_Particles", particles); commands.DispatchCompute(VoronoiCompute, kernel, (int)dispatch, 1, 1); commands.ReleaseTemporaryRT(texId); commands.ClearRenderTarget(true, true, Color.white); commands.CopyCounterValue(particles, args, 4); commands.DrawMeshInstancedIndirect(quad, 0, stipplingMat, -1, args, 0); cam.AddCommandBuffer(CameraEvent.AfterEverything, commands); }
// Use this for initialization void Start() { kernelID = computeShaderA.FindKernel("CSMainGrid"); material = new Material(pointShaderA); InitializeBuffers(); }
public Color[] GenerateBitmap(out int sdfResolution, out float sdfScale) { var distance = new float[resolution * resolution * resolution]; if (useGpu) { if (bakerCs == null) { bakerCs = (ComputeShader)Resources.Load("SDFBaker"); } var meshFilter = GetComponent <MeshFilter> (); if (meshFilter == null) { Debug.LogError("SDFSampler GPU mode need MeshFilter to load mesh data"); } var mesh = meshFilter.sharedMesh; var vertices = mesh.vertices; var triangles = mesh.triangles; var kernal = bakerCs.FindKernel("SDFBaking"); var verticesBuffer = new ComputeBuffer(vertices.Length, 12); var trianglesBuffer = new ComputeBuffer(triangles.Length, 4); var distancesBuffer = new ComputeBuffer(distance.Length, 4); verticesBuffer.SetData(vertices); trianglesBuffer.SetData(triangles); bakerCs.SetBuffer(kernal, "vertices", verticesBuffer); bakerCs.SetBuffer(kernal, "triangles", trianglesBuffer); bakerCs.SetBuffer(kernal, "distances", distancesBuffer); bakerCs.SetInt("triangleCount", triangles.Length / 3); bakerCs.SetInt("resolution", resolution); bakerCs.SetFloat("scale", scale); var group = Mathf.CeilToInt(1f * resolution / groupSize); bakerCs.Dispatch(kernal, group, group, group); distancesBuffer.GetData(distance); verticesBuffer.Release(); trianglesBuffer.Release(); distancesBuffer.Release(); } else { for (var xi = 0; xi < resolution; xi++) { for (var yi = 0; yi < resolution; yi++) { for (var zi = 0; zi < resolution; zi++) { var x = 1f * xi / (resolution - 1) - 0.5f; var y = 1f * yi / (resolution - 1) - 0.5f; var z = 1f * zi / (resolution - 1) - 0.5f; var pos = new Vector3(x, y, z) * scale; pos = transform.TransformPoint(pos); var dist = SearchDistance(pos) / scale; distance[GetIndex(xi, yi, zi)] = dist; } } } } var colors = new Color[distance.Length]; var s = (resolution - 1) * 0.5f; for (var xi = 0; xi < resolution; xi++) { for (var yi = 0; yi < resolution; yi++) { for (var zi = 0; zi < resolution; zi++) { var d = distance[GetIndex(xi, yi, zi)]; var dx = distance[GetIndex(xi + 1, yi, zi)] - distance[GetIndex(xi - 1, yi, zi)]; var dy = distance[GetIndex(xi, yi + 1, zi)] - distance[GetIndex(xi, yi - 1, zi)]; var dz = distance[GetIndex(xi, yi, zi + 1)] - distance[GetIndex(xi, yi, zi - 1)]; colors[GetIndex(xi, yi, zi)] = new Color( dx * s + 0.5f, dy * s + 0.5f, dz * s + 0.5f, d * 0.5f + 0.5f ); } } } sdfResolution = resolution; sdfScale = scale; return(colors); }
public PointCloudKernels(ComputeShader cs) { Setup = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SetupCopy.KernelName); SkyBlend = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelName); SkyBlendDepth = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelNameDepth); SkyBlendDepthSkip = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelNameDepthSkip); SkyBlendHorizon = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelNameHorizon); SkyBlendHorizonSkip = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelNameHorizonSkip); SkyBlendSkip = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SkyBlend.KernelNameSkip); FillRoughDepth = cs.FindKernel(PointCloudShaderIDs.SolidCompute.FillRoughHoles.KernelName); Downsample = cs.FindKernel(PointCloudShaderIDs.SolidCompute.FillRoughHoles.KernelName); Downsample = cs.FindKernel(PointCloudShaderIDs.SolidCompute.Downsample.KernelName); RemoveHidden = cs.FindKernel(PointCloudShaderIDs.SolidCompute.RemoveHidden.KernelName); RemoveHiddenDebug = cs.FindKernel(PointCloudShaderIDs.SolidCompute.RemoveHidden.DebugKernelName); RemoveHiddenDepthPrepass = cs.FindKernel(PointCloudShaderIDs.SolidCompute.RemoveHidden.DepthPrepassKernelName); Pull = cs.FindKernel(PointCloudShaderIDs.SolidCompute.PullKernel.KernelName); Push = cs.FindKernel(PointCloudShaderIDs.SolidCompute.PushKernel.KernelName); CalculateNormals = cs.FindKernel(PointCloudShaderIDs.SolidCompute.CalculateNormals.KernelName); SmoothNormals = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SmoothNormals.KernelName); SmoothNormalsDebug = cs.FindKernel(PointCloudShaderIDs.SolidCompute.SmoothNormals.DebugKernelName); }
/// <summary> /// Compute XYZ and colors datas by generating rendertextures /// Uses a compute shader TextureGPUGenerator /// Fills XYZRenderTexture and ColorRenderTexture /// </summary> private void ComputePointCloudData() { if (_isInitialized && _cameraSpace != null && _colorSpace != null) { // Initialize compute buffers if needed if (inputPositionBuffer == null) { lock (_cameraSpace) { inputPositionBuffer = new ComputeBuffer(_cameraSpace.Length, 3 * sizeof(float)); } } if (inputUVBuffer == null) { lock (_colorSpace) { inputUVBuffer = new ComputeBuffer(_colorSpace.Length, 2 * sizeof(float)); } } if (inputColorBuffer == null) { lock (_colorData) { inputColorBuffer = new ComputeBuffer(_colorData.Length / 4, sizeof(uint)); } } // Initialize rendertexture if needed if (vertexRenderTexture == null) { vertexRenderTexture = new RenderTexture(KinectDepthMapWidth, KinectDepthMapHeight, 0, RenderTextureFormat.ARGBFloat); vertexRenderTexture.enableRandomWrite = true; vertexRenderTexture.useMipMap = false; vertexRenderTexture.filterMode = FilterMode.Point; vertexRenderTexture.Create(); vertexTexture = (Texture)vertexRenderTexture; } if (colorRenderTexture == null) { colorRenderTexture = new RenderTexture(KinectColorMapWidth, KinectColorMapHeight, 0, RenderTextureFormat.BGRA32); colorRenderTexture.enableRandomWrite = true; colorRenderTexture.useMipMap = false; colorRenderTexture.Create(); colorTexture = (Texture)colorRenderTexture; } // Vertex generator vertexTextureGeneratorKernelId = TextureGenerator.FindKernel("VertexGenerator"); TextureGenerator.SetBuffer(vertexTextureGeneratorKernelId, "Input_positionData", inputPositionBuffer); lock (_cameraSpace) { inputPositionBuffer.SetData(_cameraSpace); } TextureGenerator.SetBuffer(colorTextureGeneratorKernelId, "Input_uvData", inputUVBuffer); lock (_colorSpace) { inputUVBuffer.SetData(_colorSpace); } TextureGenerator.SetInt("depthWidth", KinectDepthMapWidth); TextureGenerator.SetInt("depthHeight", KinectDepthMapHeight); TextureGenerator.SetInt("colorWidth", KinectColorMapWidth); TextureGenerator.SetInt("colorHeight", KinectColorMapHeight); // output TextureGenerator.SetTexture(vertexTextureGeneratorKernelId, "Output_vertexTexture", vertexRenderTexture); // Color generator colorTextureGeneratorKernelId = TextureGenerator.FindKernel("ColorGenerator"); TextureGenerator.SetBuffer(colorTextureGeneratorKernelId, "Input_colorData", inputColorBuffer); lock (_colorData) { inputColorBuffer.SetData(_colorData); } // output TextureGenerator.SetTexture(colorTextureGeneratorKernelId, "Output_colorTexture", colorTexture); TextureGenerator.Dispatch(vertexTextureGeneratorKernelId, KinectDepthMapWidth, KinectDepthMapHeight, 1); TextureGenerator.Dispatch(colorTextureGeneratorKernelId, KinectColorMapWidth, KinectColorMapHeight, 1); // Texture filled. } }
void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle colorBufferRT, RTHandle diffuseBufferRT, RTHandle depthStencilBufferRT, RTHandle depthTextureRT) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) { return; } BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); var settings = hdCamera.volumeStack.GetComponent <SubSurfaceScattering>(); // If ray tracing is enabled for the camera, if the volume override is active and if the RAS is built, we want to do ray traced SSS if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value && GetRayTracingState()) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering))) { // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesXHR = (hdCamera.actualWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (hdCamera.actualHeight + (areaTileSize - 1)) / areaTileSize; // Clear the integration texture first cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, HDShaderIDs._RaytracedShadowIntegration, diffuseBufferRT); cmd.DispatchCompute(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Fetch the volume overrides that we shall be using RayTracingShader subSurfaceShader = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracing; RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent <RayTracingSettings>(); ComputeShader deferredRayTracing = m_Asset.renderPipelineRayTracingResources.deferredRaytracingCS; // Fetch all the intermediate buffers that we need RTHandle intermediateBuffer0 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA0); RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); RTHandle intermediateBuffer2 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA2); RTHandle intermediateBuffer3 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA3); RTHandle directionBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.Direction); // Grab the acceleration structure for the target camera RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(subSurfaceShader, "SubSurfaceDXR"); // Set the acceleration structure for the pass cmd.SetRayTracingAccelerationStructure(subSurfaceShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray-tracing sampling data BlueNoise blueNoise = GetBlueNoiseManager(); blueNoise.BindDitheredRNGData8SPP(cmd); // For every sample that we need to process for (int sampleIndex = 0; sampleIndex < settings.sampleCount.value; ++sampleIndex) { // Inject the ray generation data cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIndex); int frameIndex = RayTracingFrameIndex(hdCamera); cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalBufferTexture, sharedRTManager.GetNormalBuffer()); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._SSSBufferTexture, m_SSSColor); cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, sharedRTManager.GetDepthStencilBuffer(), RenderTextureSubElement.Stencil); // Set the output textures cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalTextureRW, intermediateBuffer1); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._PositionTextureRW, intermediateBuffer2); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DirectionTextureRW, directionBuffer); // Run the computation cmd.DispatchRays(subSurfaceShader, m_RayGenSubSurfaceShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount); // Now let's do the deferred shading pass on the samples // TODO: Do this only once in the init pass int currentKernel = deferredRayTracing.FindKernel("RaytracingDiffuseDeferred"); // Bind the lightLoop data HDRaytracingLightCluster lightCluster = RequestLightCluster(); lightCluster.BindLightClusterData(cmd); // Bind the input textures cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._NormalTextureRW, intermediateBuffer1); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._PositionTextureRW, intermediateBuffer2); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DirectionTextureRW, directionBuffer); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3); // Bind the output texture (it is used for accumulation read and write) cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._RaytracingLitBufferRW, diffuseBufferRT); // Compute the Lighting cmd.DispatchCompute(deferredRayTracing, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); } // Grab the history buffer RTHandle subsurfaceHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface, SubSurfaceHistoryBufferAllocatorFunction, 1); // Check if we need to invalidate the history float historyValidity = 1.0f; #if UNITY_HDRP_DXR_TESTS_DEFINE if (Application.isPlaying) { historyValidity = 0.0f; } else #endif // We need to check if something invalidated the history buffers historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; // Apply temporal filtering to the buffer HDTemporalFilter temporalFilter = GetTemporalFilter(); temporalFilter.DenoiseBuffer(cmd, hdCamera, diffuseBufferRT, subsurfaceHistory, intermediateBuffer0, singleChannel: false, historyValidity: historyValidity); // Push this version of the texture for debug PushFullScreenDebugTexture(hdCamera, cmd, intermediateBuffer0, FullScreenDebugMode.RayTracedSubSurface); // Combine it with the rest of the lighting m_CombineLightingPass.SetTexture(HDShaderIDs._IrradianceSource, intermediateBuffer0); HDUtils.DrawFullScreen(cmd, m_CombineLightingPass, colorBufferRT, depthStencilBufferRT, shaderPassId: 1); } } else { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering))) { var parameters = PrepareSubsurfaceScatteringParameters(hdCamera); var resources = new SubsurfaceScatteringResources(); resources.colorBuffer = colorBufferRT; resources.diffuseBuffer = diffuseBufferRT; resources.depthStencilBuffer = depthStencilBufferRT; resources.depthTexture = depthTextureRT; resources.cameraFilteringBuffer = m_SSSCameraFilteringBuffer; resources.coarseStencilBuffer = parameters.coarseStencilBuffer; resources.sssBuffer = m_SSSColor; // For Jimenez we always need an extra buffer, for Disney it depends on platform if (parameters.needTemporaryBuffer) { // Clear the SSS filtering target using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ClearSSSFilteringTarget))) { CoreUtils.SetRenderTarget(cmd, m_SSSCameraFilteringBuffer, ClearFlag.Color, Color.clear); } } RenderSubsurfaceScattering(parameters, resources, cmd); } } }
private void ErodeHelper(Vector3 terrainScale, Rect domainRect, Vector2 texelSize, bool invertEffect, bool lowRes) { ComputeShader cs = GetComputeShader(); RenderTexture tmpRT = UnityEngine.RenderTexture.active; int[] numWorkGroups = { 8, 8, 1 }; //this one is mandatory if (!inputTextures.ContainsKey("Height")) { throw (new Exception("No input heightfield specified!")); } //figure out what size we need our render targets to be int xRes = (int)inputTextures["Height"].width; int yRes = (int)inputTextures["Height"].height; int rx = xRes - (numWorkGroups[0] * (xRes / numWorkGroups[0])); int ry = yRes - (numWorkGroups[1] * (yRes / numWorkGroups[1])); xRes += numWorkGroups[0] - rx; yRes += numWorkGroups[1] - ry; RenderTexture heightmapRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture heightmapPrevRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture sedimentRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture hardnessRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture reposeAngleRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture collisionRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); heightmapRT.enableRandomWrite = true; heightmapPrevRT.enableRandomWrite = true; sedimentRT.enableRandomWrite = true; hardnessRT.enableRandomWrite = true; reposeAngleRT.enableRandomWrite = true; collisionRT.enableRandomWrite = true; //clear the render textures Graphics.Blit(Texture2D.blackTexture, sedimentRT); Graphics.Blit(Texture2D.blackTexture, hardnessRT); Graphics.Blit(inputTextures["Height"], heightmapPrevRT); Graphics.Blit(inputTextures["Height"], heightmapRT); Graphics.Blit(Texture2D.blackTexture, reposeAngleRT); Graphics.Blit(Texture2D.blackTexture, collisionRT); int thermalKernelIdx = cs.FindKernel("ThermalErosion"); //precompute some values on the CPU (constants in the shader) float dx = (float)texelSize.x; float dy = (float)texelSize.y; float dxdy = Mathf.Sqrt(dx * dx + dy * dy); cs.SetFloat("dt", m_dt); cs.SetVector("dxdy", new Vector4(dx, dy, dxdy)); cs.SetVector("terrainDim", new Vector4(terrainScale.x, terrainScale.y, terrainScale.z)); cs.SetVector("texDim", new Vector4((float)xRes, (float)yRes, 0.0f, 0.0f)); cs.SetTexture(thermalKernelIdx, "TerrainHeightPrev", heightmapPrevRT); cs.SetTexture(thermalKernelIdx, "TerrainHeight", heightmapRT); cs.SetTexture(thermalKernelIdx, "Sediment", sedimentRT); cs.SetTexture(thermalKernelIdx, "ReposeMask", reposeAngleRT); cs.SetTexture(thermalKernelIdx, "Collision", collisionRT); cs.SetTexture(thermalKernelIdx, "Hardness", hardnessRT); for (int i = 0; i < m_ThermalIterations; i++) { //jitter tau (want a new value each iteration) Vector2 jitteredTau = m_AngleOfRepose + new Vector2(0.9f * (float)m_ReposeJitter * (UnityEngine.Random.value - 0.5f), 0.9f * (float)m_ReposeJitter * (UnityEngine.Random.value - 0.5f)); jitteredTau.x = Mathf.Clamp(jitteredTau.x, 0.0f, 89.9f); jitteredTau.y = Mathf.Clamp(jitteredTau.y, 0.0f, 89.9f); Vector2 m = new Vector2(Mathf.Tan(jitteredTau.x * Mathf.Deg2Rad), Mathf.Tan(jitteredTau.y * Mathf.Deg2Rad)); cs.SetVector("angleOfRepose", new Vector4(m.x, m.y, 0.0f, 0.0f)); cs.Dispatch(thermalKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(heightmapRT, heightmapPrevRT); } Graphics.Blit(heightmapRT, outputTextures["Height"]); //reset the active render texture so weird stuff doesn't happen (Blit overwrites this) UnityEngine.RenderTexture.active = tmpRT; RenderTexture.ReleaseTemporary(heightmapRT); RenderTexture.ReleaseTemporary(heightmapPrevRT); RenderTexture.ReleaseTemporary(sedimentRT); RenderTexture.ReleaseTemporary(hardnessRT); RenderTexture.ReleaseTemporary(reposeAngleRT); }
/// <summary> /// The Init method precomputes the atmosphere textures. It first allocates the /// temporary resources it needs, then calls Precompute to do the /// actual precomputations, and finally destroys the temporary resources. /// /// Note that there are two precomputation modes here, depending on whether we /// want to store precomputed irradiance or illuminance values: /// /// In precomputed irradiance mode, we simply need to call /// Precompute with the 3 wavelengths for which we want to precompute /// irradiance, namely kLambdaR, kLambdaG, kLambdaB(with the identity matrix for /// luminance_from_radiance, since we don't want any conversion from radiance to luminance). /// /// In precomputed illuminance mode, we need to precompute irradiance for /// num_precomputed_wavelengths, and then integrate the results, /// multiplied with the 3 CIE xyz color matching functions and the XYZ to sRGB /// matrix to get sRGB illuminance values. /// A naive solution would be to allocate temporary textures for the /// intermediate irradiance results, then perform the integration from irradiance /// to illuminance and store the result in the final precomputed texture. In /// pseudo-code (and assuming one wavelength per texture instead of 3): /// /// create n temporary irradiance textures /// for each wavelength lambda in the n wavelengths: /// precompute irradiance at lambda into one of the temporary textures /// initializes the final illuminance texture with zeros /// for each wavelength lambda in the n wavelengths: /// accumulate in the final illuminance texture the product of the /// precomputed irradiance at lambda (read from the temporary textures) /// with the value of the 3 sRGB color matching functions at lambda /// (i.e. the product of the XYZ to sRGB matrix with the CIE xyz color matching functions). /// /// However, this be would waste GPU memory. Instead, we can avoid allocating /// temporary irradiance textures, by merging the two above loops: /// /// for each wavelength lambda in the n wavelengths: /// accumulate in the final illuminance texture (or, for the first /// iteration, set this texture to) the product of the precomputed /// irradiance at lambda (computed on the fly) with the value of the 3 /// sRGB color matching functions at lambda. /// /// This is the method we use below, with 3 wavelengths per iteration instead /// of 1, using Precompute to compute 3 irradiances values per /// iteration, and luminance_from_radiance to multiply 3 irradiances /// with the values of the 3 sRGB color matching functions at 3 different /// wavelengths (yielding a 3x3 matrix). /// /// This yields the following implementation: /// </summary> public void Init(ComputeShader compute, int num_scattering_orders) { // The precomputations require temporary textures, in particular to store the // contribution of one scattering order, which is needed to compute the next // order of scattering (the final precomputed textures store the sum of all // the scattering orders). We allocate them here, and destroy them at the end // of this method. TextureBuffer buffer = new TextureBuffer(HalfPrecision); buffer.Clear(compute); // The actual precomputations depend on whether we want to store precomputed // irradiance or illuminance values. if (NumPrecomputedWavelengths <= 3) { Precompute(compute, buffer, null, null, false, num_scattering_orders); } else { int num_iterations = (NumPrecomputedWavelengths + 2) / 3; double dlambda = (kLambdaMax - kLambdaMin) / (3.0 * num_iterations); for (int i = 0; i < num_iterations; ++i) { double[] lambdas = new double[] { kLambdaMin + (3 * i + 0.5) * dlambda, kLambdaMin + (3 * i + 1.5) * dlambda, kLambdaMin + (3 * i + 2.5) * dlambda }; double[] luminance_from_radiance = new double[] { Coeff(lambdas[0], 0) * dlambda, Coeff(lambdas[1], 0) * dlambda, Coeff(lambdas[2], 0) * dlambda, Coeff(lambdas[0], 1) * dlambda, Coeff(lambdas[1], 1) * dlambda, Coeff(lambdas[2], 1) * dlambda, Coeff(lambdas[0], 2) * dlambda, Coeff(lambdas[1], 2) * dlambda, Coeff(lambdas[2], 2) * dlambda }; bool blend = i > 0; Precompute(compute, buffer, lambdas, luminance_from_radiance, blend, num_scattering_orders); } // After the above iterations, the transmittance texture contains the // transmittance for the 3 wavelengths used at the last iteration. But we // want the transmittance at kLambdaR, kLambdaG, kLambdaB instead, so we // must recompute it here for these 3 wavelengths: int compute_transmittance = compute.FindKernel("ComputeTransmittance"); BindToCompute(compute, null, null); compute.SetTexture(compute_transmittance, "transmittanceWrite", buffer.TransmittanceArray[WRITE]); compute.SetVector("blend", new Vector4(0, 0, 0, 0)); int NUM = CONSTANTS.NUM_THREADS; compute.Dispatch(compute_transmittance, CONSTANTS.TRANSMITTANCE_WIDTH / NUM, CONSTANTS.TRANSMITTANCE_HEIGHT / NUM, 1); Swap(buffer.TransmittanceArray); } //Grab ref to textures and mark as null in buffer so they are not released. TransmittanceTexture = buffer.TransmittanceArray[READ]; buffer.TransmittanceArray[READ] = null; ScatteringTexture = buffer.ScatteringArray[READ]; buffer.ScatteringArray[READ] = null; IrradianceTexture = buffer.IrradianceArray[READ]; buffer.IrradianceArray[READ] = null; if (CombineScatteringTextures) { OptionalSingleMieScatteringTexture = null; } else { OptionalSingleMieScatteringTexture = buffer.OptionalSingleMieScatteringArray[READ]; buffer.OptionalSingleMieScatteringArray[READ] = null; } // Delete the temporary resources allocated at the begining of this method. buffer.Release(); }
// creates the shader for depth2color coordinate mapping private bool CreateCoordMapperShader(KinectInterop.SensorData sensorData, bool bAstraPro, bool bColor2Depth) { if (_coordMapperShader == null) { _coordMapperShader = Resources.Load("AstraCoordMapper") as ComputeShader; } if (_coordMapperShader) { //bAstraPro = false; // don't use NN _depth2colorKernel = _coordMapperShader.FindKernel("MapDepth2ColorPP"); //_color2depthKernel = !bAstraPro ? _coordMapperShader.FindKernel("MapColor2DepthPP") : _coordMapperShader.FindKernel("MapColor2DepthNN"); // float[] space2spaceMat = new float[] { // matCamD2C.m00, matCamD2C.m01, matCamD2C.m02, matCamD2C.m03, // matCamD2C.m10, matCamD2C.m11, matCamD2C.m12, matCamD2C.m13 // }; int depthImageLength = sensorData.depthImageWidth * sensorData.depthImageHeight; int colorImageLength = sensorData.colorImageWidth * sensorData.colorImageHeight; _coordMapperShader.SetFloat("depthResX", (float)sensorData.depthImageWidth); _coordMapperShader.SetFloat("depthResY", (float)sensorData.depthImageHeight); _coordMapperShader.SetInt("depthImageLen", depthImageLength); _coordMapperShader.SetFloat("colorResX", (float)sensorData.colorImageWidth); _coordMapperShader.SetFloat("colorResY", (float)sensorData.colorImageHeight); //if (!bColor2Depth) { _coordMapperShader.SetVector("d2cMat0", new Vector4(matCamD2C.m00, matCamD2C.m01, matCamD2C.m02, matCamD2C.m03)); _coordMapperShader.SetVector("d2cMat1", new Vector4(matCamD2C.m10, matCamD2C.m11, matCamD2C.m12, matCamD2C.m13)); // Debug.Log("Shader d2cMat0: " + new Vector4 (matCamD2C.m00, matCamD2C.m01, matCamD2C.m02, matCamD2C.m03)); // Debug.Log("Shader d2cMat1: " + new Vector4 (matCamD2C.m10, matCamD2C.m11, matCamD2C.m12, matCamD2C.m13)); } // else // { // _coordMapperShader.SetFloats("color2depthMat", space2spaceMat); // } // compute buffers if (_depthDepthValuesBuf == null) { _depthDepthValuesBuf = new ComputeBuffer(depthImageLength, sizeof(float)); _coordMapperShader.SetBuffer(_depth2colorKernel, "depthDepthValues", _depthDepthValuesBuf); } //if (!bColor2Depth) { _depthPlaneCoordsBuf = new ComputeBuffer(depthImageLength, 2 * sizeof(float)); _colorPlaneCoordsBuf = new ComputeBuffer(!bColor2Depth ? depthImageLength : colorImageLength, 2 * sizeof(float)); // set plane coords Vector2[] depthPlaneCoords = new Vector2[depthImageLength]; for (int dy = 0, di = 0; dy < sensorData.depthImageHeight; dy++) { for (int dx = 0; dx < sensorData.depthImageWidth; dx++) { depthPlaneCoords[di] = new Vector2(dx, dy); di++; } } _depthPlaneCoordsBuf.SetData(depthPlaneCoords); _coordMapperShader.SetBuffer(_depth2colorKernel, "depthPlaneCoords", _depthPlaneCoordsBuf); _coordMapperShader.SetBuffer(_depth2colorKernel, "colorPlaneCoords", _colorPlaneCoordsBuf); } // else // { // int colorImageLength = sensorData.colorImageWidth * sensorData.colorImageHeight; // // _colorSpaceCoordsBuf = new ComputeBuffer(colorImageLength, 3 * sizeof(float)); // _colorDepthCoordsBuf = new ComputeBuffer(colorImageLength, 2 * sizeof(float)); // // _coordMapperShader.SetBuffer(_color2depthKernel, "colorSpaceCoords", _colorSpaceCoordsBuf); // _coordMapperShader.SetBuffer(_color2depthKernel, "colorDepthCoords", _colorDepthCoordsBuf); // } } return(_coordMapperShader != null); }
public void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex, DensityVolumeList densityVolumes) { if (!hdCamera.frameSettings.enableVolumetrics) { return; } var visualEnvironment = VolumeManager.instance.stack.GetComponent <VisualEnvironment>(); if (visualEnvironment.fogType.value != FogType.Volumetric) { return; } using (new ProfilingSample(cmd, "Volume Voxelization")) { int numVisibleVolumes = m_VisibleVolumeBounds.Count; bool highQuality = preset == VolumetricLightingPreset.High; bool enableClustered = hdCamera.frameSettings.lightLoopSettings.enableTileAndCluster; int kernel; if (highQuality) { kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredHQ" : "VolumeVoxelizationBruteforceHQ"); } else { kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredMQ" : "VolumeVoxelizationBruteforceMQ"); } var frameParams = hdCamera.vBufferParams[0]; Vector4 resolution = frameParams.resolution; float vFoV = hdCamera.camera.fieldOfView * Mathf.Deg2Rad; // Compose the matrix which allows us to compute the world space view direction. Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, hdCamera.viewMatrix, false); Texture3D volumeAtlas = DensityVolumeManager.manager.volumeAtlas.volumeAtlas; Vector4 volumeAtlasDimensions = new Vector4(0.0f, 0.0f, 0.0f, 0.0f); if (volumeAtlas != null) { volumeAtlasDimensions.x = (float)volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures volumeAtlasDimensions.y = volumeAtlas.width; volumeAtlasDimensions.z = volumeAtlas.depth; volumeAtlasDimensions.w = Mathf.Log(volumeAtlas.width, 2); // Max LoD } else { volumeAtlas = CoreUtils.blackVolumeTexture; } cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle); cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeBounds, s_VisibleVolumeBoundsBuffer); cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeData, s_VisibleVolumeDataBuffer); cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeMaskAtlas, volumeAtlas); // TODO: set the constant buffer data only once. cmd.SetComputeMatrixParam(m_VolumeVoxelizationCS, HDShaderIDs._VBufferCoordToViewDirWS, transform); cmd.SetComputeIntParam(m_VolumeVoxelizationCS, HDShaderIDs._NumVisibleDensityVolumes, numVisibleVolumes); cmd.SetComputeVectorParam(m_VolumeVoxelizationCS, HDShaderIDs._VolumeMaskDimensions, volumeAtlasDimensions); int w = (int)resolution.x; int h = (int)resolution.y; // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(m_VolumeVoxelizationCS, kernel, (w + 7) / 8, (h + 7) / 8, 1); } }
private void Awake() { patternShader = Resources.Load <ComputeShader>("NodeShaders/DomainWarpPattern"); patternKernel = patternShader.FindKernel("PatternKernel"); InitializeRenderTexture(); }