Monday, 18 November 2013

Into Code to IL to Node

I changed the title a bit, but yes I'll kinda speak again of code generation somehow.

I remember some time ago devvvvs shown some prototype to have simpler ways to makes nodes. Basically you create a function and it generates boilerplate code around.
Sadly it never really made it through (maybe they keep it for their new version).

Basically you build a function and you generate the node to fit it.

I started to work on this, I called the project MicroNodes ;)

Here is a simple example

Code Snippet
  1. [SlicewiseMethod(Name = "+", Category = "Value")]
  2. public static void Add([Input("Input 1")] double d1, [Input("Input 2")] double d2, [Output("Output")] out double dout)
  3. {
  4.     dout = d1 + d2;
  5. }

Ok That's the infamous Add (without group), but you see the idea.

You basically have your operator, and then I build a plugin in intermediate language that prepares data for each slice, then calls the function.

So a dummy implementation looks like this:

Code Snippet
  1. [PluginInfo(Name = "Add", Category = "Value", Version = "Slicewise Simple")]
  2. public class DummyAdd3 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ISpread<double> d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ISpread<double> d2;
  9.  
  10.     [Output("Output")]
  11.     private ISpread<double> dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.SliceCount = SpreadMax;
  16.         double dou;
  17.         for (int i = 0; i < SpreadMax; i++)
  18.         {
  19.             SliceWise.Add(d1[i], d2[i],out dou);
  20.             dout[i] = dou;
  21.         }
  22.     }
  23. }

You can notice I use output parameter in that case, that will fit some other parts. Here is the same implementation using operator:

Code Snippet
  1. [PluginInfo(Name = "Add", Category="Value",Version="Operator Simple")]
  2. public class DummyAdd : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ISpread<double> d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ISpread<double> d2;
  9.  
  10.     [Output("Output")]
  11.     private ISpread<double> dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.SliceCount = SpreadMax;
  16.         for (int i = 0; i < SpreadMax; i++)
  17.         {
  18.             dout[i] = d1[i] + d2[i];
  19.         }
  20.     }
  21. }

You can notice that it's very easy to generate intermediate language for Slicewise methods.

First interesting bit is that both of those are running at same speed. Reason being simple, the JIT, when it converts the Intermediate language into machine code will inline the function call, so assembly wise it's pretty similar.

That's good news, since it means I can easily use functions and call has no overhead.

Now let's see how we can optimize this.
First, any slicewise operation, output result count = spreadmax.
Doing dout[i] does the following in Intermediate Language:
virtcall ISpread<T>._setcyclic()

Setting a slice like this does (for every single write)

  • Mark the Spread as dirty (eg: it needs to flush data back into vvvv) 
  • Go access the internal DataStore (an array basically)
  • Do a Mod to store, output[i%icount] = data
That's actually a lot.

So now we can access the internal store ourselves, this is exposed on Spread Type.

Here is a better version:

Code Snippet
  1. [PluginInfo(Name = "Add", Category = "Value", Version = "Slicewise Buffer")]
  2. public class DummyAdd4 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ISpread<double> d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ISpread<double> d2;
  9.  
  10.     [Output("Output")]
  11.     private ISpread<double> dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.SliceCount = SpreadMax;
  16.         double[] b = dout.Stream.Buffer;
  17.         for (int i = 0; i < SpreadMax; i++)
  18.         {
  19.             SliceWise.Add(d1[i], d2[i], out b[i]);
  20.         }
  21.         dout.Flush(true);
  22.     }
  23. }

Now, since we access the buffer (and we know we never have to use Mod for output), we get access to the array, and can pass the index as output directly,this does this in IL:

  IL_0039:  ldloc.0 (This is our array local variable)
  IL_003a:  ldloc.1  (This is index)
  IL_003b:  ldelema    [mscorlib]System.Double

So instead it loads the address of the array and pass it to the function.

Pleace note that I call Flush(true), since now I write directly into the internal store, the dirty flag if never set.

So it's easy to add this in the IL generator, and it Gives you a decent substantial boost.

For 5000 elements:
ISpread virtual : 0.1 ms
ISpread buffer : 0.06 ms

For 50000 elements
ISpread virtual : 1 ms
ISpread buffer : 0.6 ms

It's pretty low values but it can easily add up.

So now we can use pointer output, since we can write directly back into memory.
This doesn't give a decent improvement, since a memcpy on 5000 elements is blazing fast, But at least we save some memory (40 kilobytes for a 5000 spread).

It seems kinda minimal, but in a reasonably large patch, it also adds up quickly.

So now the obvious next part is to modify our input. We also do a virtcall for access which also does a mod.

Operator version:

Code Snippet
  1. [PluginInfo(Name = "Add", Category = "Value", Version = "Operator Ptr Full")]
  2. public unsafe class DummyAdd8 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ValueInput d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ValueInput d2;
  9.  
  10.     [Output("Output")]
  11.     private ValueOutput dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.Length = SpreadMax;
  16.         double* d = dout.Data;
  17.  
  18.         double* pt1 = d1.Data;
  19.         double* pt2 = d2.Data;
  20.  
  21.         int l1 = d1.Length;
  22.         int l2 = d2.Length;
  23.  
  24.         for (int i = 0; i < SpreadMax; i++)
  25.         {
  26.             d[i] = pt1[i%l1] + pt2[i%l2];
  27.         }
  28.     }
  29. }

And Static function version:

Code Snippet
  1. [PluginInfo(Name = "Add", Category = "Value", Version = "Slicewise Ptr Full")]
  2. public unsafe class DummyAdd10 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ValueInput d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ValueInput d2;
  9.  
  10.     [Output("Output")]
  11.     private ValueOutput dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.Length = SpreadMax;
  16.         double* d = dout.Data;
  17.         double* pt1 = d1.Data;
  18.         double* pt2 = d2.Data;
  19.         int l1 = d1.Length;
  20.         int l2 = d2.Length;
  21.         for (int i = 0; i < SpreadMax; i++)
  22.         {
  23.             SliceWise.Add(pt1[i % l1], pt2[i % l2], out d[i]);
  24.         }
  25.     }
  26. }

As before Operator vs Static function gets pretty much 0 difference, which is still good news, since it means that we can still easily generate that IL code.

It yields a difference compared to ISpread still, here is the table:

For 5000 elements:
ISpread virtual : 0.1 ms
ISpread buffer : 0.06 ms
Ful Pointer : 0.03 ms

For 50000 elements
ISpread virtual : 1 ms
ISpread buffer : 0.6 ms
Ful Pointer : 0.3 ms

Please note that we also save memory for each pin, so let's say we have 5000 elements in first spread and 500 in second, we gain : (5000*8*2) + (500*8) = 84 kilobytes

That's quite pretty decent specially also considering that we have a node that is much faster.

So technically speaking, one very fun thing is that by allowing the user to build this first function as above:

Code Snippet
  1. public static void Add(double d1, double d2, out double dout)
  2. {
  3.     dout = d1 + d2;
  4. }

By choosing a route in our IL generator we can make a node 3 times faster compared to the dummy implementation that comes from template.

Also please note that it's much easier to reuse that function or post optimize.
If you have 50 nodes like this, finding a new speedup is a decent amount of refactoring, here, none is needed.

Now I'll just give a second example, since now devvvs have presented their new 5x to 6x faster Vector Join, split, I might put them to the test :)

First thing is indeed, compared to last version they are much faster, no brainer, which is great!

Please note that there's also Zip (Value), which is normally pretty optimized.

So Let's see, Vector (2d Join)

5000 Elements
Native : 0.035 ms
Zip : 0.035 ms

50000 Elements
Native : 0.37 ms
Zip : 0.32 ms

So now I decided to test 3 techniques, so are more code generation friendly, some are more raw plugin, here we go.

First a Vector Join function is simply like this:

Code Snippet
  1. [SlicewiseMethod(Name = "Vector", Category = "2d Join")]
  2. public static void V2dJoin(
  3.     [Input("X")] double x,
  4.     [Input("Y")] double y,
  5.     [Output("Output")] out Vector2D result)
  6. {
  7.     result = new Vector2D(x, y);
  8. }

Really simple no?

Now here are the testers.

Method one:
Code Snippet
  1.   [PluginInfo(Name = "Vector", Category = "2d Join", Version = "Ptr")]
  2.   public unsafe class DummyVector: IPluginEvaluate
  3.   {
  4.       [Input("Input 1")]
  5.       private ValueInput d1;
  6.  
  7.       [Input("Input 2")]
  8.       private ValueInput d2;
  9.  
  10.       [Output("Output")]
  11.       private ValueOutput dout;
  12.  
  13.       public void Evaluate(int SpreadMax)
  14.       {
  15.           dout.Length = SpreadMax*2;
  16.           double* d = dout.Data;
  17.  
  18.           double* pt1 = d1.Data;
  19.           double* pt2 = d2.Data;
  20.  
  21.           int l1 = d1.Length;
  22.           int l2 = d2.Length;
  23.  
  24.           for (int i = 0; i < SpreadMax; i++)
  25.           {
  26.               *d = pt1[i % l1];
  27.               d++;
  28.                 *d=pt2[i % l2];
  29.               d++;
  30.           }
  31.       }
  32.   }

Pretty simple, we push per component.

Method 2:

Code Snippet
  1. [PluginInfo(Name = "Vector", Category = "2d Join", Version = "Ptr Struct")]
  2. public unsafe class DummyVector2 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ValueInput d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ValueInput d2;
  9.  
  10.     [Output("Output")]
  11.     private ValueOutput dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.Length = SpreadMax * 2;
  16.         Vector2D* d = (Vector2D*)dout.Data;
  17.  
  18.         double* pt1 = d1.Data;
  19.         double* pt2 = d2.Data;
  20.  
  21.         int l1 = d1.Length;
  22.         int l2 = d2.Length;
  23.  
  24.         for (int i = 0; i < SpreadMax; i++)
  25.         {
  26.             d->x = pt1[i % l1];
  27.             d->y = pt2[i % l2];
  28.             d++;
  29.         }
  30.     }
  31. }

This is almost the same, but we build as struct.

Now actually we can also simply use our slicewise:

Code Snippet
  1. [PluginInfo(Name = "Vector", Category = "2d Join", Version = "Ptr Out")]
  2. public unsafe class DummyVector3 : IPluginEvaluate
  3. {
  4.     [Input("Input 1")]
  5.     private ValueInput d1;
  6.  
  7.     [Input("Input 2")]
  8.     private ValueInput d2;
  9.  
  10.     [Output("Output")]
  11.     private ValueOutput dout;
  12.  
  13.     public void Evaluate(int SpreadMax)
  14.     {
  15.         dout.Length = SpreadMax * 2;
  16.         Vector2D* d = (Vector2D*)dout.Data;
  17.         double* pt1 = d1.Data;
  18.         double* pt2 = d2.Data;
  19.         int l1 = d1.Length;
  20.         int l2 = d2.Length;
  21.         for (int i = 0; i < SpreadMax; i++)
  22.         {
  23.             Joiner.Join(pt1[i % l1], pt2[i % l2], out d[i]);
  24.         }
  25.     }
  26. }

So now the results:

5000 Elements
Native : 0.035 ms
Zip : 0.035 ms
Per Component: 0.035 ms
As Struct: 0.031 ms
Function Output:  0.038 ms

50000 Elements
Native : 0.37 ms
Zip : 0.32 ms
Per Component: 0.35 ms
As Struct: 0.33 ms
Function Output:  0.34 ms

Please note that values fluctuate a little bit.

But basically that means few things:

  • Devvvvs did a good job at optimizing vectors
  • On very low spread (50), zip seems slower, native is of course fastest (since you have COM object call). It is not as obvious tho.
  • A generated version from function is as Fast as optimized native ;)

So to resume, IL code generation is pretty cool.

Now you have a lot of other use cases than SliceWise.
What I decided was to build different templates, so for example:

Code Snippet
  1. [ReductorMethod(Name = "+", Category = "Value Spectral")]
  2. public static void SpectralAdd([Input("Input")] IEnumerable<double> data,[Output("Result")] out double result)
  3. {
  4.     result = 0.0;
  5.     foreach (double d in data) { result += d; }
  6. }

You can also do Struct Join/Split like this:

Code Snippet
  1. [Compactor(Name="Struct",Category="Test")]
  2. public struct MyStruct2
  3. {
  4.     [CompactorProperty(Name = "Hello")]
  5.     public double Hello;
  6.  
  7.     [CompactorProperty(Name = "Element2")]
  8.     public double Element2;
  9.  
  10.     [CompactorProperty(Name="Vector",Flatten=true)]
  11.     public Vector3 Vector;
  12. }

Or have a visitor class in case you want to use an existing struct.

There is some other types/parts, but that will be for another post.


Friday, 15 November 2013

Dynamic Compilation (Part 4)

I already explained how to quickly generate code from functions in previous posts.

Code generation has some interesting advantages:
  • You can export code to a project/file
  • This allows you to easily debug
Now this also has some drawbacks:
  • You need a good template engine, or create your own.
  • You can start to have a lot of different templates
  • String generation is feeling a bit clunky at times.
  • You are not allowed to dump your assembly, and in most cases you'll also have to create one temporary assembly per node (not always true).

In the other hand, it's also possible to generate IL code directly, or have it generated via Expression.

Expression is awesome, you can really do cool things with it, but in my use case it's not ideal (I need to reflect existing functions).I'll go back to expressions another time, since now we'll look at IL generation.

Instead of doing all this string cooking, we can just build our class at runtime emitting IL code (which is some kind of "high level assembler" to simplify.

This has the advantage that it's faster to build, you can create several nodes in the same assembly any time during your application lifecycle, dump/replace a method on the fly, and you learn a bit into the depths of .net ;)

So first you need to prepare a few builders:

Code Snippet
  1. AssemblyName myAssembly = new AssemblyName(Guid.NewGuid().ToString());
  2. AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssembly, AssemblyBuilderAccess.Run);
  3.  
  4. ModuleBuilder mb = asm.DefineDynamicModule("MyModule");
  5.  
  6. TypeBuilder tb = mb.DefineType("Hello");
  7. tb.AddInterfaceImplementation(typeof(IAutomatonNodeInstance));

Then you need a default constructor, it doesn't create one for you:

Code Snippet
  1. ConstructorBuilder cb = tb.DefineDefaultConstructor(MethodAttributes.Public);

That was hard :)

Now you need to also create fields to accept your method delegate:

Code Snippet
  1. ParameterInfo[] prms = method.GetParameters();
  2. List<FieldBuilder> fields = new List<FieldBuilder>();
  3.  
  4. FieldBuilder containerfield = tb.DefineField("container", typeof(IAutomatonNodeContainer), FieldAttributes.Private);
  5. FieldBuilder routput = tb.GetSourcePin(method.ReturnParameter.ParameterType, "output");
  6.  
  7. foreach (ParameterInfo pi in prms)
  8. {
  9.     fields.Add(tb.DefineField(pi.Name, this.GetSinkType(pi.ParameterType), FieldAttributes.Private));
  10. }

Basically I create one field to accept the Node container, one field for the ouput.
Then you iterate on Parameter list and create one field for each of those (oh and you can just specify type, no crazy using namespaces or adding them all around).

Now let's go to the interesting bit, my node has 2 methods : Initialize (container), Evaluate (no parameters)

Initialize does the following:
  • Assign container
  • Create pins/parameters.
Evaluate does:
  • Read parameters
  • Call function
  • Assign output
So to initialize, we do the following:

Code Snippet
  1. MethodBuilder assign = tb.DefineMethod("AssignContainer", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, typeof(void), new Type[] { typeof(IAutomatonNodeContainer) });
  2. ILGenerator assignopcodes = assign.GetILGenerator();
  3.  
  4. assignopcodes.Emit(OpCodes.Ldarg_0);
  5. assignopcodes.Emit(OpCodes.Ldarg_1);
  6. assignopcodes.Emit(OpCodes.Stfld, containerfield);
  7.  
  8. int i = 0;
  9. foreach (ParameterInfo pi in prms)
  10. {
  11.     assignopcodes.CreateParameter(pi, fields[i]);
  12.     i++;
  13. }
  14.  
  15. assignopcodes.Emit(OpCodes.Ldarg_0);
  16. assignopcodes.Emit(OpCodes.Ldarg_1);
  17. assignopcodes.Emit(OpCodes.Callvirt, typeof(AutomatonNodeContainer).GetProperty("PinFactory").GetGetMethod(true));
  18. assignopcodes.Emit(OpCodes.Ldstr, "Output");
  19. assignopcodes.Emit(OpCodes.Callvirt, method.ReturnParameter.ParameterType.CreateSourcePinMethod());
  20. assignopcodes.Emit(OpCodes.Stfld, routput);
  21. assignopcodes.Emit(OpCodes.Ret);

We create a method (make it public and virtual since we implement an interface).
CallingConvetion.HasThis is necessary since it's a class method (basically this will be pushed as first argument, eg: OpCodes.Ldarg_0)

Then we create parameter like this:

Code Snippet
  1. public static void CreateParameter(this ILGenerator gen, ParameterInfo pi, FieldBuilder field)
  2. {
  3.     gen.Emit(OpCodes.Ldarg_0);
  4.     gen.Emit(OpCodes.Ldarg_1);
  5.     gen.Emit(OpCodes.Ldstr,pi.Name);
  6.     gen.Emit(OpCodes.Callvirt, pi.ParameterType.CreateParameterMethod());
  7.     gen.Emit(OpCodes.Stfld, field);
  8. }

We push this + container.
Push parameter name on the stack.
Emit a callvirt on the method info.
Stfld will store the result into our private field.

Testing in debug, and here we go, all our parameters are properly injected, I can see my node fully initialized.

Of course for now it does nothing. So second part: evaluate:

This is mostly as easy.

  • Push all the parameters necessary to call the static method (here i need to be careful of Getters/Setters).
  • Call the static method.
  • Push the return value in the output field.
Here we are :

Code Snippet
  1. MethodBuilder eval = tb.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, null, new Type[] { });
  2. ILGenerator evalopcodes = eval.GetILGenerator();
  3. evalopcodes.Emit(OpCodes.Nop);
  4. evalopcodes.Emit(OpCodes.Ldarg_0);
  5. evalopcodes.Emit(OpCodes.Ldfld, routput);
  6.  
  7. i = 0;
  8. foreach (ParameterInfo pi in prms)
  9. {
  10.     evalopcodes.Emit(OpCodes.Ldarg_0);
  11.     evalopcodes.Emit(OpCodes.Ldfld, fields[i]);
  12.     evalopcodes.Emit(OpCodes.Callvirt, pi.ParameterType.ParemeterGetterMethod());
  13.     i++;
  14. }
  15.  
  16. evalopcodes.Emit(OpCodes.Call, method);
  17. evalopcodes.Emit(OpCodes.Callvirt, method.ReturnParameter.ParameterType.SourcePinSetterMethod());
  18. evalopcodes.Emit(OpCodes.Nop);
  19. evalopcodes.Emit(OpCodes.Ret);
  20.  
  21. Type t = tb.CreateType();

First we push our return field first (since it needs to receive the value).

Then we push on the stack all fields (for loop).
Call the function.
Push the output result (on top of the stack) in our output pin.

Et voila.

As you can notice, code is decently verbose, but it's not too bad, and a lot of the code can be reused to build different type of nodes.

Please of course note that I can also just export this assembly as a file.

That's it for now, probably more to come !












Wednesday, 6 November 2013

Dynamic Compilation (Part 3)

Here we are... Again!

So in previous post I explained about reflecting functions, now one common thing I have is some form of post processors.

For most of them, they are pretty straightforward, a few render pass and bit of rebinding. Having a generic host is nice, but sometimes I need more sandboxing (so you can have a bit better internal optimization).

So if we take this basic shader (Yes my copyashtml is broken again ;)


Simple, just displace a texture from some FFT data, nothing fancy.

Now here is the c# code to glue this, here is the property class.


And here is the glue:


Nothing fancy, but when you have to bind this code for every shader you write, it quickly becomes cumbersome.

Please also note that this new post processing format it independent from both my tool and vvvv (technically I use another small code generator to build nodes from those class in my tool, I could do it as easily in vvvv but since my API is built in .NET 4.5 and vvvv prefers to support WindowsXP instead, it's not gonna happen right now ;)

As you can notice, this is again a lot of boilerplate code, that can easily be generated.

So instead, I have a small exe, you send the fx file to it, and it builds pretty much the same code from reflection (and give me the compiled shader on the way, so i can store it to speed up load time).

Here is a shader example (does nothing of any use):



And here is generated code


So basically I generate code from a shader file, then this code generates node code, uff ;)

If you are wondering, I'm not all in full for generating everything, there's a lot of cases where you don't want to.

Funnily, generating code can also make debugging easier, compared to a generic host, since most of your case handling has already be pre processed, you only end up with the very core logic (no crazy for loops/crazy dictionaries, if/then else to check a condition...), so You have a reasonable performance boost, which is not as big as if you do that "dream case cbuffer god of all", but we like dynamic languages no?

And for vvvv readers don't forget to bitch about .NET 4.5, so SharpDX in vvvv gets some more progress ;)

http://vvvv.org/forum/.net-4.5-framework-support












Tuesday, 5 November 2013

Dynamic Compilation (Part 2)

Finally I have a full windows 8.1 installed on all my machines, so I'm pretty excited to be able to now concentrate fully on dx11.2 development. That also means that I have my CopyToHtml tool working again (it got fucked up somehow in my previous studio).

I spoke about how I was reflecting hlsl functions using latest DirectX features in previous post.

Now one interesting thing, is my automaton has (a lot) of boilerplate. Building a node is fairly easy, but generally quite tedious.

Here is an example (that builds a color from hsl parameters):

Code Snippet
  1. using System.Text;
  2. using SharpDX;
  3.  
  4. using FlareTic.Graph.Interface;
  5. using FlareTic.Graph.Interface.Automaton;
  6.  
  7. namespace FlareTic.Nodes.Automaton
  8. {
  9.     [AutomatonNode(Name = "HSL", Category = "Color", SystemName = "flt.automaton.Color.HSL")]
  10.     public class ColorHSLNode : IAutomatonNodeInstance
  11.     {
  12.         private ScalarSinkPin h;
  13.         private ScalarSinkPin s;
  14.         private ScalarSinkPin l;
  15.         private ScalarSinkPin a;
  16.  
  17.         private ColorSourcePin output;
  18.  
  19.         public void AssignContainer(IAutomatonNodeContainer container)
  20.         {
  21.             this.h = container.PinFactory.CreateScalarSinkPin("Hue");
  22.             this.s = container.PinFactory.CreateScalarSinkPin("Saturation");
  23.             this.l = container.PinFactory.CreateScalarSinkPin("Brightness");
  24.             this.a = container.PinFactory.CreateScalarSinkPin("Alpha");
  25.  
  26.             this.output = container.PinFactory.CreateColorSourcePin("Output");
  27.         }
  28.  
  29.         public void Evaluate()
  30.         {
  31.             this.output.Value = FlareTic.Core.Maths.ColorSpaces.FromHSL(h.Value, s.Value, l.Value, a.Value);
  32.         }
  33.  
  34.         public void Dispose() { }
  35.  
  36.     }
  37. }

Finally from what we see here, we have a static function, a few parameters and some attributes.

For each node we need to endlessly repeat all that build code, all this just to build a function...
But, thinking about it (and I remember 4v people trying to do something like that at some point), I can easily reflect a function too.
And c# allows to compile an assembly on the fly.
So wouldn't it be better to just reflect the function, generate code on the fly and compile into an assembly?

It would look somehow like this:

Code Snippet
  1. [FunctionBank()]
  2. public static class Arithmetic
  3. {
  4.     [Function(Name = "Add",Category="Value", OutputName="Output")]
  5.     public static float Add([Parameter(Name = "Input 1")] float v1, [Parameter(Name = "Input 2")] float v2)
  6.     {
  7.         return v1 + v2;
  8.     }
  9.  
  10.     [Function(Name = "Substract", Category = "Value", OutputName = "Output")]
  11.     public static float Substract([Parameter(Name = "Input 1")] float v1, [Parameter(Name = "Input 2")] float v2)
  12.     {
  13.         return v1 - v2;
  14.     }
  15.  
  16.     [Function(Name = "Multiply", Category = "Value", OutputName = "Output")]
  17.     public static float Multiply([Parameter(Name = "Input 1")] float v1, [Parameter(Name = "Input 2")] float v2)
  18.     {
  19.         return v1 * v2;
  20.     }
  21.  
  22.  
  23.     [Function(Name = "Equals", Category = "Value", OutputName = "Output")]
  24.     public static bool Equals([Parameter(Name = "Input 1")] float v1, [Parameter(Name = "Input 2")] float v2, [Parameter(Name = "Espilon")] float eps)
  25.     {
  26.         return Math.Abs(v1 - v2) <= eps;
  27.     }
  28. }

Now from this, we can indicate that our class has functions (to speed up processing and not scan every method of every class).

Every export function has a little description, same for parameters.

Try number 1, build a little code builder, small template node, and inject code depending on parameters.

Simple and easy, works.

Now as you see you have a lot of attributes, and I find them a bit intrusive. The main problem is also that sometimes I might just want to use a function in a compiled dll.

So instead of reflecting the function directly, you can simply create a delegate, this looks like this:

Code Snippet
  1. [NodeDelegateAttribute(Name = "Add", Category = "Value", OutputName = "Output", FunctionName = "CodeLib.Arithmetic.Add")]
  2.     public delegate float AddDelegate([Parameter(Name = "Input 1")] float v1, [Parameter(Name = "Input 2")] float v2);

Now the nice thing is I can rename the function, give proper naming to parameters...

So from those 2 lines of code I now have a nice nodes.

Please note that this is also cumbersome, when you have an API like SharpDX you have thousands of functions.

So instead, we can also do the following:

  • Scan the datatypes I want to import.
  • Reflect functions.
  • Do a pre-test to check that I want/can import this function.
  • Use function reflection directly to build my code.
This is really simple and works really well, the only little issue is that I can't really name parameters the way I want (unless I start to build some ruleset, but it might be painful).
In case of standard Math types, it's really not important at all tho ;)

So here we go, on startup I specify what types I want to scan, it builds a function list, selecting a function simply generate node code on the fly, compiles it and create a node.

How to have 5000 nodes in few lines of code, one weekend well spent ;)



Of course, another great thing is that it also helps a lot for exporting an exe at the end, since you can just compile all functions used in a single assembly (as nodes), or export the generated code in a c# project, you can easily cherry pick which function get used and avoid to deploy all nodes.

Here we are, most of my tool is now heading towards that, simpler, cleaner, all that I love ;)

Stay tuned for next section, which is going into something a bit more complex ;)

Monday, 4 November 2013

Dynamic Compilation (Part 1)

I already spoke about the fact that I wasn't that keen on Visual graph editor for shaders.

Well I started (thanks to DirectX11.2) to partly change my mind.

In DirectX11.2 they introduced this compiler feature called Function Linking Graph, which basically allows you to link HLSL functions together.

One thing that I quite liked in that in some extent is that the linker is fast (very fast). Another very cool aspect is that you can reflect a function (including parameters). This is really nice, I can have a list of common useful functions (noise/waves...), but also create a function on the fly and have full reflection access.

Having the possibility to get an hybrid approach is a huge step in the right direction, patch only is a bit too monolithic, you end up quickly limited or have to build some pretty heavy patches.

So here is a screenshot of shader patch (builds a pixelshader), It really took very little time to build it:



I have a folder with common functions, which get reflected on load and build node on the fly, but I can as well add my own custom functions on the fly with code editor, that's quite fun ;)

Now there's always a but with these things ;)

First, it only works with Vertex/PixelShaders.

So it's pretty cool to make some nice materials, post processors. I can even make some of my voxel processing with it (trading Compute Shader to few draw calls with GS).

Now one problem besides that, I would love to actually just have the function, and bind it in whatever context I want, this is what I do with subshaders (which are some kind of includes). I have an incomplete shader (that I call host), and bind only the include code. If I simply could include the graph that would be perfect :)

Well it's not possible with linker, but the graph has this quite useful function called : GenerateHLSL :)

So you can get the generated code from it, here is how it looks for the screenshot above:




You have forward function declarations (eg: you still need to add includes yourself), and you have your pixel shader function as inout.

But wait...

Finally let's say I want this prototype:
float GetForce(float3 position);

I can simply tell the pixel shader that i return a float since when you generate hlsl , unlike when you link, you don't care much about context.

So I just need to add a function (to fit the out), or modify my host (with conditional compilation), to change prototype to:
GetForce(float3 position, out float force);

And there we go :)


Of course in that case I just have generated code (eg: no link), so I still have to compile the whole shader, but still, having some graphical tool to build functions opens some new possibilities (sphere tracer, behaviours, colliders)...

Next part will go into something similar but different ;)