Scripting Rendering

Right before rendering actors that have a mesh associated to them (cloth, ropes, or softbodies), Obi must first process their meshes to deform them according to current particle positions and orientations. This usually involves a very large amount of vertex data, so using multiple threads to speed it up is a must. Assigning one thread to each mesh works well, but the problem with this is that it only works if you have many meshes with few vertices each: if you only have a few large meshes, you can't parallelize as much - in the extreme case of having just one mesh, you can't parallelize at all.

Obi solves this by merging vertex data of all meshes of the same kind of actor into a single, large vertex buffer. Then, parallelization happens at vertex granularity. This way all available threads are busy and the amount of work is evenly distributed among them regarless of the amount of meshes to be processed or their vertex count. As a bonus this often allows to render multiple actors in a single drawcall, further improving performance.

Vertex data for individual actors is provided by subclasses of ObiActorRenderer, then merged into large vertex buffers and processed in parallel by a RenderSystem. This scheme means that modifying the mesh used by Unity's MeshFilter/SkinnedMeshRenderer components does not include any of the deformation calculated by Obi, as these live on separate vertex buffers. Read on if you want to bake the deformed meshes, or access post-deformation vertex data.

Baking meshes

Most render systems in Obi have a Bake() method that takes an actor renderer and a mesh reference as arguments. Calling it stores a "snapshot" of the current, possibly deformed state of the actor into the mesh passed as parameter. These are the renderers and associated render systems that expose a Bake() method:

  • ObiClothRenderer: solver.GetRenderSystem<ObiClothRenderer>() as ObiClothRenderSystem;
  • ObiTearableClothRenderer: solver.GetRenderSystem<ObiTearableClothRenderer>() as ObiClothRenderSystem;
  • ObiChainRopeRenderSystem: solver.GetRenderSystem<ObiRopeChainRenderer>() as ObiChainRopeRenderSystem;
  • ObiRopeExtrudedRenderer: solver.GetRenderSystem<ObiRopeExtrudedRenderer>() as ObiExtrudedRopeRenderSystem;
  • ObiRopeMeshRenderer: solver.GetRenderSystem<ObiRopeMeshRenderer>() as ObiMeshRopeRenderSystem;
  • ObiSoftbodySkinner: solver.GetRenderSystem<ObiSoftbodySkinner>() as ObiSoftbodyRenderSystem;
  • ObiFluidSurfaceMesher: solver.GetRenderSystem<ObiFluidSurfaceMesher>() as IFluidRenderSystem;

Here's an example that bakes the mesh generated by ObiFluidSurfaceMesher:

ObiFluidSurfaceMesher renderer = GetComponent<ObiFluidSurfaceMesher>();

if (renderer.actor.isLoaded)
{
	var system = renderer.actor.solver.GetRenderSystem<ObiFluidSurfaceMesher>() as IFluidRenderSystem;

	if (system != null)
	{
		var mesh = new Mesh();
		system.BakeMesh(renderer, ref mesh);

		// use mesh as you wish.
	}
}
			

Deforming meshes

Cloth, rope and softody renderers will look for a component that implements the IBurstMeshDeformer / IComputeMeshDeformer interfaces (depending on the backend in use by the solver) in the ObiActors being rendered. If it finds such component, it will call its Deform() method, passing relevant vertex batch and renderer data to it.

Here's the arguments of Deform()'s signature:

IMeshRenderBatch batch
Batched mesh data that contains this actor's renderer vertices.
RendererInfo info
Information about this actor's renderer: vertex and triangle index ranges in the IMeshRenderBatch where its data can be found.
IObiJobHandle inputDeps (Burst only)
input dependencies for the Burst backend.

Inside Deform(), you'd typically retrieve the vertex data buffer as batch.GetVertices() or batch.GetVertexBuffer(), then use info.vertexRange.start and info.vertexRange.count to access entries in the vertex buffer. GetVertices() returns a NativeArray - convenient for scheduling jobs in the Burst backend - and GetVertexBuffer() returns a GraphicsBuffer - convenient for passing to a compute shader in the Compute backend. The vertex format used to store vertices in these buffers varies depending on the kind of renderer you're dealing with:

  • Some actors take existing vertices and just modify them - that's the case of cloth, softbody and rope mesh renderers: vertex data is stored using the DynamicBatchVertex struct, with position, normal, tangent and color fields.

  • Some actors procedurally generate the entire mesh each frame - that's the case of rope extruded/line renderers: vertex data is stored using the ProceduralRopeVertex struct, with position, normal, tangent, color and uv fields.

Here's an example component that processes cloth vertices to add a sinusoiudal deformation to them in the Burst backend:

using UnityEngine;
using Unity.Burst;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Jobs;

namespace Obi.Testing
{
    public class WavyCloth : MonoBehaviour, IBurstMeshDeformer
    {
        public float amplitude = 0.5f;
        public float frequency = 10;
        public float scale = 3;

        public void Deform(IMeshRenderBatch batch, RendererInfo info, IObiJobHandle inputDeps)
        {
            var burstDeps = inputDeps as BurstJobHandle;

            if (burstDeps != null)
            {
                // use a job to iterate over all vertices in the batch that belong to this cloth:
                burstDeps.jobHandle = new WavyJob
                {
                    vertices = batch.GetVertices<DynamicBatchVertex>(),
                    vOffset = info.vertexRange.start,
                    time = Time.time,
                    amplitude = amplitude,
                    frequency = frequency,
                    scale = scale
                }.Schedule(info.vertexRange.count, 16, burstDeps.jobHandle);
            }
        }

        [BurstCompile]
        struct WavyJob : IJobParallelFor
        {
            [NativeDisableParallelForRestriction] public NativeArray<DynamicBatchVertex> vertices;
            [ReadOnly] public int vOffset;
            [ReadOnly] public float time;
            
            [ReadOnly]public float amplitude;
            [ReadOnly]public float frequency;
            [ReadOnly]public float scale;

            public void Execute(int i)
            {
                i += vOffset;

                var vertex = vertices[i];
                vertex.pos += new Vector3(0,math.sin(vertex.pos.x * scale + time * frequency) * amplitude,0);
                vertices[i] = vertex;
            }
        }
    }
}
			

Here's a similar component that does the same for ropes:

	using UnityEngine;
using Unity.Burst;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Jobs;

namespace Obi.Testing
{
    public class WavyRope : MonoBehaviour, IBurstMeshDeformer
    {
        public float amplitude = 0.5f;
        public float frequency = 10;
        public float scale = 3;

        public void Deform(IMeshRenderBatch batch, RendererInfo info, IObiJobHandle inputDeps)
        {
            var burstDeps = inputDeps as BurstJobHandle;

            if (burstDeps != null)
            {
                // use a job to iterate over all vertices in the batch that belong to this rope:
                burstDeps.jobHandle = new WavyJob
                {
                    vertices = batch.GetVertices<ProceduralRopeVertex>(),
                    vOffset = info.vertexRange.start,
                    time = Time.time,
                    amplitude = amplitude,
                    frequency = frequency,
                    scale = scale
                }.Schedule(info.vertexRange.count, 16, burstDeps.jobHandle);
            }
        }

        [BurstCompile]
        struct WavyJob : IJobParallelFor
        {
            [NativeDisableParallelForRestriction] public NativeArray<ProceduralRopeVertex> vertices;
            [ReadOnly] public int vOffset;
            [ReadOnly] public float time;
            
            [ReadOnly]public float amplitude;
            [ReadOnly]public float frequency;
            [ReadOnly]public float scale;

            public void Execute(int i)
            {
                i += vOffset;

                var vertex = vertices[i];
                vertex.pos += new Vector3(0,math.sin(vertex.pos.x * scale + time * frequency) * amplitude,0);
                vertices[i] = vertex;
            }
        }
    }
}

As you can see code in both cases is essentially the same: the only difference is the kind of struct they deal with: DynamicBatchVertex or ProceduralRopeVertex.