engineFunctions.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _ENGINEFUNCTIONS_H_
  23. #define _ENGINEFUNCTIONS_H_
  24. #include <tuple>
  25. #ifndef _ENGINEEXPORTS_H_
  26. #include "console/engineExports.h"
  27. #endif
  28. #ifndef _ENGINETYPEINFO_H_
  29. #include "console/engineTypeInfo.h"
  30. #endif
  31. /// @file
  32. /// Structures for function-type engine export information.
  33. #ifdef TORQUE_COMPILER_VISUALC
  34. #define TORQUE_API extern "C" __declspec( dllexport )
  35. #elif defined( TORQUE_COMPILER_GCC )
  36. #define TORQUE_API extern "C" __attribute__( ( visibility( "default" ) ) )
  37. #else
  38. #error Unsupported compiler.
  39. #endif
  40. // #pragma pack is bugged in GCC in that the packing in place at the template instantiation
  41. // sites rather than their definition sites is used. Enable workarounds.
  42. #ifdef TORQUE_COMPILER_GCC
  43. #define _PACK_BUG_WORKAROUNDS
  44. #endif
  45. /// Structure storing the default argument values for a function invocation
  46. /// frame.
  47. struct EngineFunctionDefaultArguments
  48. {
  49. /// Number of default arguments for the function call frame.
  50. ///
  51. /// @warn This is @b NOT the size of the memory block returned by getArgs() and also
  52. /// not the number of elements it contains.
  53. U32 mNumDefaultArgs;
  54. /// Return a pointer to the variable-sized array of default argument values.
  55. ///
  56. /// @warn The arguments must be stored @b IMMEDIATELY after #mNumDefaultArgs.
  57. /// @warn This is a @b FULL frame and not just the default arguments, i.e. it starts with the
  58. /// first argument that the function takes and ends with the last argument it takes.
  59. /// @warn If the compiler's #pragma pack is buggy, the elements in this structure are allowed
  60. /// to be 4-byte aligned rather than byte-aligned as they should be.
  61. const U8* getArgs() const
  62. {
  63. return ( const U8* ) &( mNumDefaultArgs ) + sizeof( mNumDefaultArgs );
  64. }
  65. };
  66. // Need byte-aligned packing for the default argument structures.
  67. #ifdef _WIN64
  68. #pragma pack( push, 4 )
  69. #else
  70. #pragma pack( push, 1 )
  71. #endif
  72. // Structure encapsulating default arguments to an engine API function.
  73. template< typename T >
  74. struct _EngineFunctionDefaultArguments {};
  75. template<typename ...ArgTs>
  76. struct _EngineFunctionDefaultArguments< void(ArgTs...) > : public EngineFunctionDefaultArguments
  77. {
  78. template<typename T> using DefVST = typename EngineTypeTraits<T>::DefaultArgumentValueStoreType;
  79. std::tuple<DefVST<ArgTs> ...> mArgs;
  80. private:
  81. using SelfType = _EngineFunctionDefaultArguments< void(ArgTs...) >;
  82. template<size_t ...> struct Seq {};
  83. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  84. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  85. template<typename ...TailTs, size_t ...I>
  86. static void copyHelper(std::tuple<DefVST<ArgTs> ...> &args, std::tuple<DefVST<TailTs> ...> &defaultArgs, Seq<I...>) {
  87. std::tie(std::get<I + (sizeof...(ArgTs) - sizeof...(TailTs))>(args)...) = defaultArgs;
  88. }
  89. template<typename ...TailTs> using MaybeSelfEnabled = typename std::enable_if<sizeof...(TailTs) <= sizeof...(ArgTs), decltype(mArgs)>::type;
  90. template<typename ...TailTs> static MaybeSelfEnabled<TailTs...> tailInit(TailTs ...tail) {
  91. std::tuple<DefVST<ArgTs>...> argsT;
  92. std::tuple<DefVST<TailTs>...> tailT = std::make_tuple(tail...);
  93. SelfType::copyHelper<TailTs...>(argsT, tailT, typename Gens<sizeof...(TailTs)>::type());
  94. return argsT;
  95. };
  96. public:
  97. template<typename ...TailTs> _EngineFunctionDefaultArguments(TailTs ...tail)
  98. : EngineFunctionDefaultArguments({sizeof...(TailTs)}), mArgs(SelfType::tailInit(tail...))
  99. {}
  100. };
  101. #pragma pack( pop )
  102. // Helper to allow flags argument to DEFINE_FUNCTION to be empty.
  103. struct _EngineFunctionFlags
  104. {
  105. U32 val;
  106. _EngineFunctionFlags()
  107. : val( 0 ) {}
  108. _EngineFunctionFlags( U32 val )
  109. : val( val ) {}
  110. operator U32() const { return val; }
  111. };
  112. ///
  113. enum EngineFunctionFlags
  114. {
  115. /// Function is a callback into the control layer. If this flag is not set,
  116. /// the function is a call-in.
  117. EngineFunctionCallout = BIT( 0 ),
  118. };
  119. /// A function exported by the engine for interfacing with the control layer.
  120. ///
  121. /// A function can either be a call-in, transfering control flow from the control layer to the engine, or a call-out,
  122. /// transfering control flow from the engine to the control layer.
  123. ///
  124. /// All engine API functions use the native C (@c cdecl) calling convention.
  125. ///
  126. /// Be aware that there a no implicit parameters to functions. This, for example, means that methods will simply
  127. /// list an object type parameter as their first argument but otherwise be indistinguishable from other functions.
  128. ///
  129. /// Variadic functions are supported.
  130. ///
  131. /// @section engineFunction_strings String Arguments and Return Values
  132. ///
  133. /// Strings passed through the API are assumed to be owned by the caller. They must persist for the entire duration
  134. /// of a call.
  135. ///
  136. /// Strings returned by a function are assumed to be in transient storage that will be overwritten by subsequent API
  137. /// calls. If the caller wants to preserve a string, it is responsible to copying strings to its own memory. This will
  138. /// happen with most higher-level control layers anyway.
  139. ///
  140. /// @section engineFunction_defaultargs Default Arguments
  141. ///
  142. /// As the engine API export system is set up to not require hand-written code in generated wrappers per se, the
  143. /// export system seeks to include a maximum possible amount of information in the export structures.
  144. /// To this end, where applicable, information about suggested default values for arguments to the engine API
  145. /// functions is stored in the export structures. It is up to the wrapper generator if and how it makes use of
  146. /// this information.
  147. ///
  148. /// Default arguments are represented by capturing raw stack frame vectors of the arguments to functions. These
  149. /// frames could be used as default images for passing arguments in stack frames, though wrapper generators
  150. /// may actually want to read out individual argument values and include them in function prototypes within
  151. /// the generated code.
  152. ///
  153. /// @section engineFunction_callin Call-ins
  154. ///
  155. /// Call-ins are exposed as native entry points. The control layer must be able to natively
  156. /// marshall arguments and call DLL function exports using C calling conventions.
  157. ///
  158. /// @section engineFunction_callout Call-outs
  159. ///
  160. /// Call-outs are exposed as pointer-sized memory locations into which the control layer needs
  161. /// to install addresses of functions that receive the call from the engine back into the control
  162. /// layer. The function has to follow C calling conventions and
  163. ///
  164. /// A call-out will initially be set to NULL and while being NULL, will simply cause the engine
  165. /// to skip and ignore the call-out. This allows the control layer to only install call-outs
  166. /// it is actually interested in.
  167. ///
  168. class EngineFunctionInfo : public EngineExport
  169. {
  170. public:
  171. DECLARE_CLASS( EngineFunctionInfo, EngineExport );
  172. protected:
  173. /// A combination of EngineFunctionFlags.
  174. BitSet32 mFunctionFlags;
  175. /// The type of the function.
  176. const EngineTypeInfo* mFunctionType;
  177. /// Default values for the function arguments.
  178. const EngineFunctionDefaultArguments* mDefaultArgumentValues;
  179. /// Name of the DLL symbol denoting the address of the exported entity.
  180. const char* mBindingName;
  181. /// Full function prototype string. Useful for quick printing and most importantly,
  182. /// this will be the only place containing information about the argument names.
  183. const char* mPrototypeString;
  184. /// Address of either the function implementation or the variable taking the address
  185. /// of a call-out.
  186. void* mAddress;
  187. /// Next function in the global link chain of engine functions.
  188. EngineFunctionInfo* mNextFunction;
  189. /// First function in the global link chain of engine functions.
  190. static EngineFunctionInfo* smFirstFunction;
  191. public:
  192. ///
  193. EngineFunctionInfo( const char* name,
  194. EngineExportScope* scope,
  195. const char* docString,
  196. const char* protoypeString,
  197. const char* bindingName,
  198. const EngineTypeInfo* functionType,
  199. const EngineFunctionDefaultArguments* defaultArgs,
  200. void* address,
  201. U32 flags );
  202. /// Return the name of the function.
  203. const char* getFunctionName() const { return getExportName(); }
  204. /// Return the function's full prototype string including the return type, function name,
  205. /// and argument list.
  206. const char* getPrototypeString() const { return mPrototypeString; }
  207. /// Return the DLL export symbol name.
  208. const char* getBindingName() const { return mBindingName; }
  209. /// Test whether this is a callout function.
  210. bool isCallout() const { return mFunctionFlags.test( EngineFunctionCallout ); }
  211. /// Test whether the function is variadic, i.e. takes a variable number of arguments.
  212. bool isVariadic() const { return mFunctionType->isVariadic(); }
  213. /// Return the type of this function.
  214. const EngineTypeInfo* getFunctionType() const { return mFunctionType; }
  215. /// Return the return type of the function.
  216. const EngineTypeInfo* getReturnType() const { return getFunctionType()->getArgumentTypeTable()->getReturnType(); }
  217. /// Return the number of arguments that this function takes. If the function is variadic,
  218. /// this is the number of fixed arguments.
  219. U32 getNumArguments() const { return getFunctionType()->getArgumentTypeTable()->getNumArguments(); }
  220. ///
  221. const EngineTypeInfo* getArgumentType( U32 index ) const { return ( *( getFunctionType()->getArgumentTypeTable() ) )[ index ]; }
  222. /// Return the vector storing the default argument values.
  223. const EngineFunctionDefaultArguments* getDefaultArguments() const { return mDefaultArgumentValues; }
  224. /// Reset all callout function pointers back to NULL. This deactivates all callbacks.
  225. static void resetAllCallouts();
  226. };
  227. ///
  228. ///
  229. /// Due to the given argument types and return type being directly used as is, it is not possible
  230. /// to use this macro with engine types that have more complex value passing semantics (like e.g.
  231. /// String). Use engineAPI in this case.
  232. ///
  233. /// @note The method of defining functions exposed by this macro is very low-level. To more
  234. /// conveniently define API functions and methods, use the facilities provided in engineAPI.h.
  235. ///
  236. /// @see engineAPI.h
  237. #define DEFINE_CALLIN( bindingName, exportName, scope, returnType, args, defaultArgs, flags, doc ) \
  238. TORQUE_API returnType bindingName args; \
  239. namespace { namespace _ ## bindingName { \
  240. _EngineFunctionDefaultArguments< void args > sDefaultArgs defaultArgs; \
  241. EngineFunctionInfo sFunctionInfo( \
  242. #exportName, \
  243. &_SCOPE< scope >()(), \
  244. doc, \
  245. #returnType " " #exportName #args, \
  246. #bindingName, \
  247. TYPE< returnType args >(), \
  248. &sDefaultArgs, \
  249. ( void* ) &bindingName, \
  250. _EngineFunctionFlags( flags ) \
  251. ); \
  252. } } \
  253. TORQUE_API returnType bindingName args
  254. ///
  255. ///
  256. /// Not all control layers may be able to access data variables in a DLL so this macro exposes
  257. /// both the variable and a set_XXX function to set the variable programmatically.
  258. #define DEFINE_CALLOUT( bindingName, exportName, scope, returnType, args, flags, doc ) \
  259. TORQUE_API returnType ( *bindingName ) args; \
  260. TORQUE_API void set_ ## bindingName( returnType ( *fn ) args ) \
  261. { bindingName = fn; } \
  262. returnType ( *bindingName ) args; \
  263. namespace { \
  264. ::EngineFunctionInfo _cb ## bindingName( \
  265. #exportName, \
  266. &::_SCOPE< scope >()(), \
  267. doc, \
  268. #returnType " " #exportName #args, \
  269. #bindingName, \
  270. ::TYPE< returnType args >(), \
  271. NULL, \
  272. ( void* ) &bindingName, \
  273. EngineFunctionCallout | EngineFunctionFlags( flags ) \
  274. ); \
  275. }
  276. #endif // !_ENGINEFUNCTIONS_H_