Function Replacement Using Macros

Sometimes we need to create some common functions for different requirements to reduce code volume and maintenance costs.

However, for some functions in the process, we hope to replace them with specific versions on certain occasions to meet specific requirements.

This can be done using the macro definition mechanism.

  1. //example.chunk
  2. #ifndef CC_USER_MODIFY_SOMETHING
  3. void ModifySomething(){
  4. //do something here
  5. }
  6. #endif
  7. void Before(){
  8. //do something here
  9. }
  10. void After(){
  11. //do something here
  12. }
  13. void myFunc(){
  14. Before();
  15. ModifySomething();
  16. After();
  17. }

In the code above, myFunc has a complete calling process. If you want to modify the implementation of ModifySomething, you only need to define the CC_USER_MODIFY_SOMETHING macro before #include <example.chunk>, and implement your ModifySomething function.

  1. #define CC_USER_MODIFY_SOMETHING
  2. void ModifySomething(){
  3. //do what you want
  4. }
  5. #include <example.chunk>

Note: the definition of the replaced function should be placed before the include.

This mechanism is widely used in the Surface Shader system, such as the SurfacesFragmentModifySharedData function in lighting-models/includes/common mentioned earlier.

  1. // user-defined-common-surface.chunk:
  2. // base surface function
  3. #ifndef CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA
  4. #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA
  5. void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData)
  6. {
  7. .................
  8. }
  9. #endif
  10. // effect
  11. // this function needs overriding
  12. #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA
  13. void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData)
  14. {
  15. .............
  16. }
  17. // base functions should place after override functions
  18. #include <user-defined-common-surface.chunk>