samdauwe / BabylonCpp

A port of Babylon.js to C++
Apache License 2.0
284 stars 38 forks source link

Headerless examples #49

Closed pthom closed 4 years ago

pthom commented 4 years ago

Hello,

This is a new PR, which should be applied after the Layout Menu PR.

It simplifies the registration of examples via:

An example can now work :

See for example two commits where I did this


Explanations:

BABYLON_REGISTER_SAMPLE(_LoadersGLTFSamplesIndex::CategoryName(), TwoCylinderEngineScene)

will automatically register the example (and make the example name equal to the class name)

BABYLON_REGISTER_SAMPLE is a macro with some black magic inside, but I tried to explain it clearly:

// BABYLON_REGISTER_SAMPLE : registers an example in the Samples Index
// No need to create a header file, and no need to add it manually to the index
//
// This macro uses 3 black magic elements:
// 1. macro "token pasting" in order to create structure name per sample
// 2. A Raii structure that will register the sample on creation
// 3. a global variable of the Raii structure in order to do the actual registration
#define  BABYLON_REGISTER_SAMPLE(categoryName, sampleClassName)                                    \
  struct RaiiRegisterer_##sampleClassName {   /* 1. This struct name depends on the sample name */ \
    RaiiRegisterer_##sampleClassName()        /* 2. inside its constructor, it triggers         */ \
    {                                         /* the registration                            */    \
       BABYLON::Samples::SamplesIndex::Instance().RegisterSample(categoryName, #sampleClassName,   \
                     [](ICanvas* iCanvas) { return std::make_unique<sampleClassName>(iCanvas); }); \
    }                                                                                              \
  };                                                                                               \
  RaiiRegisterer_##sampleClassName gRaiiRegisterer_##sampleClassName; /* 3. global variable */
samdauwe commented 4 years ago

Hi Pascal,

That is a clever solution!

The macro makes it much easier to create examples because no header file needs to be created. The compiler also has to look at less files so the build time should decrease. With all the examples we have now and will be added in the future that is a great advantage.

Thanks! Sam