Protecting Against Redefinitions

Sometimes a module may be used more than once. For example, the following code adds one module to itself.
IModule someModule = ...
IModule addedModule = new Add(someModule, someModule);

When compiling, the Add module, which inlines the code from both it's parameters, would end up defining the code in someModule twice, causing compilation errors. To protect against this, you must add include guards.
public string GetCode()
    return @"
#ifndef " + FunctionName.ToUpper() + @"
#define " + FunctionName.ToUpper() + @"
float " + FunctionName + @"(__global int *p, Single3 input)
    return noise(p, input.x, input.y, input.z);

Also, some modules may be created more than once, using different parameters.
Module module1 = new MyModule(parameter1, parameter2);
Module module2 = new MyModule(parameter3, parameter4);

This would result in the code being generated with the same signature, yet different contents. One way to protect against this is to count instances, and append the instance index to the end of the function name.
public class MyModule : IModule
    static int instanceCount;
    int instanceIndex;

    public MyModule(float someParameter1, float someParameter2)
        instanceIndex = instanceCount;

    public string FunctionName { get { return "myFunction" + instanceIndex.ToString(); } }


Last edited Sep 13, 2010 at 3:07 AM by YellPika, version 1


No comments yet.