- Home /
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... e.g..
public static class ixMath
{
#include "hashFunctions.cginc"
#include "noiseFunctions.cginc"
}
Unfortunately CSharp doesnt allow #include. Can anyone suggest another solution?
How do you all do this?
Answer by Bunny83 · Nov 23, 2021 at 11:15 PM
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.
Answer by ixlabvr · Nov 23, 2021 at 11:34 PM
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.
Answer by unity_hosein · Nov 24, 2021 at 03:59 AM
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
@unity_hosein Thanks for answering, but I don't quite understand. Could you please explain again!?
Your answer
Follow this Question
Related Questions
Graphics.CopyTexture copies wrong mip on Windows 10 build 1 Answer
How to share constant variables between Compute Shaders? 0 Answers
How to multiply a float4x4 and a float4 in unity shaders? 0 Answers
What is best way to add transparent padding all around my sprites? 2 Answers
Multiple Cars not working 1 Answer