Become a Unity Shaders Guru by Mina Pêcheux

Become a Unity Shaders Guru by Mina Pêcheux

Author:Mina Pêcheux
Language: eng
Format: epub
Publisher: Packt Publishing Pvt Ltd
Published: 2023-06-14T00:00:00+00:00


Updating our C# class

At this point, our RaymarchingSphere.compute shader is already able to give us some pixel colors and compute an image. However, we have to call this RaymarchingSphere.compute shader properly from the CPU side, and in particular, we need to pass it all the required variables and buffers in our ComputeRaymarchingSphere C# class.

In a nutshell, the point will be to use the Render method in this C# script to extend the logic from the parent URPComputeAsset abstract class and compute some additional information. We will then store all this data in the CommandBuffer instance we are given so that URPComputeFeature can retrieve it later on and use it as the current context during the compute shader dispatch.

Here is the updated version of our ComputeRaymarchingSphere class:

public class ComputeRaymarchingSphere : URPComputeAsset { public Color surfaceColor = Color.white; public override void Render( CommandBuffer commandBuffer, int kernelHandle) { Camera camera = Camera.main; commandBuffer.SetComputeMatrixParam(shader, "CameraToWorld", camera.cameraToWorldMatrix); commandBuffer.SetComputeMatrixParam(shader, "CameraInverseProjection", camera.projectionMatrix.inverse); commandBuffer.SetComputeVectorParam(shader, "SurfaceColor", new Vector3(surfaceColor.r, surfaceColor.g, surfaceColor.b)); } }

As you can see, my script contains a public variable for the surface color that can be set easily in the Inspector, and it then does a series of set operations on the CommandBuffer instance during the Render process to assign the required parameters. More specifically, we want to grab our current main camera and extract from it the two space conversion matrices, CameraToWorld and CameraInverseProjection, and then we want to pass in the r, g, and b components of the surfaceColor variable.

If we come back to the Unity editor, we now see two things:

First of all, there is a large disc in the middle of our game view.

Secondly, if we select our ComputeRaymarchingSphere ScriptableObject asset, its Inspector shows us an input for the color of the surface (see Figure 8.10). As we change this value, the color of the disc changes accordingly: our compute shader context is properly populated by the Render logic of our C# class!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.