Sharing code between shader and c# - how?

Hi Everyone,

With the new Unity.Mathematics library we can now write more or less identical code for (compute) shaders and c#. Fantastic!

But really great would be if I could use a single source file for all common code. Maintaining identical code across c# and HLSL would then be trivial. (For example, noise functions that can be used in both c# and Compute Shaders and custom Shader-Graph nodes)

This could be easily done with #include. I could just put all the common code in .cginc files and then just #include them in my csharp code…

public static class ixMath
 #include "hashFunctions.cginc"
 #include "noiseFunctions.cginc"

Unfortunately #CSharp doesn’t allow #include.

Can anyone suggest another solution?

How do you all do this?

Unity have designed their Unity.mathematics package to have identical syntax to HLSL.

lerp, frac, sin, swizzling, its all there. Sure, not all of HLSL is supported, but enough for it to be very useful to share code between C# and HLSL.
For example, this code will compile in both C# and HLSL…

float3 foo(float4 q)
    float3 p = dot(q.xyxy, q.zwzw);
    return -1.0 + 2.0 * frac(sin(p));

The value comes from having a library of math functions that you can use on the CPU and GPU and get same results. This is very useful. For example, consider hash or noise functions, which are full of magic numbers.

more or less identical code

it’s just “more or less”. HLSL is a completely different language. Yes, like many languages both are C-style languages but they have fundamentally different syntax and features. Especially when it comes to Swizzling. So only a tiny fraction of code is actually the same. Though as I said the same could be said about javascript, java, C#, C or C++. Though that doesn’t make larger code fragments compatible with each other. In HLSL you can use include files to include code fragments. However C# does not have such a feature.

Of course it would be possible to create a source file generator that stitches code fragments together. However I highly doubt this would have much value.

Here’s the answer. Use Unity.Mathematics and write your HLSL code in C#. Use #defines and #ifs to stop the shader from including the C# parts. Include the .cs file normally in the shader. Profit!

you can create a public void and use mathematics in it.and use parameters you need fron of it and use it when you want in the game.
sorry for my bad eng