engineAPI.h 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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 _ENGINEAPI_H_
  23. #define _ENGINEAPI_H_
  24. #include <tuple>
  25. #include <utility>
  26. #ifndef _FIXEDTUPLE_H_
  27. #include "fixedTuple.h"
  28. #endif
  29. #ifndef _CONSOLETYPES_H_
  30. #include "console/consoleTypes.h"
  31. #endif
  32. #ifndef _CONSOLE_H_
  33. #include "console/console.h"
  34. #endif
  35. #ifndef _STRINGFUNCTIONS_H_
  36. #include "core/strings/stringFunctions.h"
  37. #endif
  38. #ifndef _SIMOBJECT_H_
  39. #include "console/simObject.h"
  40. #endif
  41. #ifndef _ENGINEFUNCTIONS_H_
  42. #include "console/engineFunctions.h"
  43. #endif
  44. // Whatever types are used in API definitions, their DECLAREs must be visible to the
  45. // macros. We include the basic primitive and struct types here.
  46. #ifndef _ENGINEPRIMITIVES_H_
  47. #include "console/enginePrimitives.h"
  48. #endif
  49. #ifndef _ENGINESTRUCTS_H_
  50. #include "console/engineStructs.h"
  51. #endif
  52. // Needed for the executef macros. Blame GCC.
  53. #ifndef _SIMEVENTS_H_
  54. #include "console/simEvents.h"
  55. #endif
  56. /// @file
  57. /// Definitions for exposing engine functionality to the control layer.
  58. ///
  59. /// This file provides a convenience layer around the underlying engine interop system (which at
  60. /// the moment still includes the legacy TorqueScript interop a.k.a. "console system"). The
  61. /// macros exposed here will automatically take care of all marshalling, value type constraints,
  62. /// reflection info instancing, etc. involved in defining engine API call-ins and call-outs.
  63. ///
  64. /// @note At the moment, this file supplies both the legacy TorqueScript console system as well
  65. /// as the new engine export system with the structures and information they need. In the
  66. /// near future, the console-based parts will get purged. This will not result in visible
  67. /// changes to users of the functionality here except for the string-based marshalling
  68. /// functions currently exposed (which will also disappear).
  69. //TODO: Disable warning for extern "C" functions returning UDTs for now; need to take a closer look at this
  70. #pragma warning( disable : 4190 )
  71. // Disable some VC warnings that are irrelevant to us.
  72. #pragma warning( push )
  73. #pragma warning( disable : 4510 ) // default constructor could not be generated; all the Args structures are never constructed by us
  74. #pragma warning( disable : 4610 ) // can never be instantiated; again Args is never constructed by us
  75. namespace engineAPI {
  76. /// Flag for enabling legacy console behavior in the interop system while
  77. /// we still have it around. Will disappear along with console.
  78. extern bool gUseConsoleInterop;
  79. /// Flag to allow engine functions to detect whether the engine had been
  80. /// initialized or shut down.
  81. extern bool gIsInitialized;
  82. }
  83. /// @name Marshalling
  84. ///
  85. /// Functions for converting to/from string-based data representations.
  86. ///
  87. /// @note This functionality is specific to the console interop.
  88. /// @{
  89. /// Marshal a single piece of data from native into client form.
  90. template< typename T >
  91. inline const char* EngineMarshallData( const T& value )
  92. {
  93. return castConsoleTypeToString( value );
  94. }
  95. inline const char* EngineMarshallData( bool value )
  96. {
  97. if( value )
  98. return "1";
  99. else
  100. return "0";
  101. }
  102. inline const char* EngineMarshallData( const char* str )
  103. {
  104. // The API assumes that if you pass a plain "const char*" through it, then you are referring
  105. // to string storage with non-local lifetime that can be safely passed to the control layer.
  106. return str;
  107. }
  108. template< typename T >
  109. inline const char* EngineMarshallData( T* object )
  110. {
  111. return ( object ? object->getIdString() : "0" );
  112. }
  113. template< typename T >
  114. inline const char* EngineMarshallData( const T* object )
  115. {
  116. return ( object ? object->getIdString() : "0" );
  117. }
  118. inline const char* EngineMarshallData( U32 value )
  119. {
  120. return EngineMarshallData( S32( value ) );
  121. }
  122. /// Marshal data from native into client form stored directly in
  123. /// client function invocation vector.
  124. template< typename T >
  125. inline void EngineMarshallData( const T& arg, S32& argc, ConsoleValueRef *argv )
  126. {
  127. argv[ argc ] = castConsoleTypeToString( arg );
  128. argc ++;
  129. }
  130. inline void EngineMarshallData( bool arg, S32& argc, ConsoleValueRef *argv )
  131. {
  132. if( arg )
  133. argv[ argc ] = 1;
  134. else
  135. argv[ argc ] = 0;
  136. argc ++;
  137. }
  138. inline void EngineMarshallData( S32 arg, S32& argc, ConsoleValueRef *argv )
  139. {
  140. argv[ argc ] = arg;
  141. argc ++;
  142. }
  143. inline void EngineMarshallData( U32 arg, S32& argc, ConsoleValueRef *argv )
  144. {
  145. EngineMarshallData( S32( arg ), argc, argv );
  146. }
  147. inline void EngineMarshallData( F32 arg, S32& argc, ConsoleValueRef *argv )
  148. {
  149. argv[ argc ] = arg;
  150. argc ++;
  151. }
  152. inline void EngineMarshallData( const char* arg, S32& argc, ConsoleValueRef *argv )
  153. {
  154. argv[ argc ] = arg;
  155. argc ++;
  156. }
  157. inline void EngineMarshallData( char* arg, S32& argc, ConsoleValueRef *argv )
  158. {
  159. argv[ argc ] = arg;
  160. argc ++;
  161. }
  162. template< typename T >
  163. inline void EngineMarshallData( T* object, S32& argc, ConsoleValueRef *argv )
  164. {
  165. argv[ argc ] = object ? object->getId() : 0;
  166. argc ++;
  167. }
  168. template< typename T >
  169. inline void EngineMarshallData( const T* object, S32& argc, ConsoleValueRef *argv )
  170. {
  171. argv[ argc ] = object ? object->getId() : 0;
  172. argc ++;
  173. }
  174. /// Unmarshal data from client form to engine form.
  175. ///
  176. /// This is wrapped in an a struct as partial specializations on function
  177. /// templates are not allowed in C++.
  178. template< typename T >
  179. struct EngineUnmarshallData
  180. {
  181. T operator()( const char* str ) const
  182. {
  183. T value;
  184. castConsoleTypeFromString( value, str );
  185. return value;
  186. }
  187. };
  188. template<>
  189. struct EngineUnmarshallData< S32 >
  190. {
  191. S32 operator()( ConsoleValueRef &ref ) const
  192. {
  193. return (S32)ref;
  194. }
  195. S32 operator()( const char* str ) const
  196. {
  197. return dAtoi( str );
  198. }
  199. };
  200. template<>
  201. struct EngineUnmarshallData< U32 >
  202. {
  203. U32 operator()( ConsoleValueRef &ref ) const
  204. {
  205. return (U32)((S32)ref);
  206. }
  207. U32 operator()( const char* str ) const
  208. {
  209. return dAtoui( str );
  210. }
  211. };
  212. template<>
  213. struct EngineUnmarshallData< F32 >
  214. {
  215. F32 operator()( ConsoleValueRef &ref ) const
  216. {
  217. return (F32)ref;
  218. }
  219. F32 operator()( const char* str ) const
  220. {
  221. return dAtof( str );
  222. }
  223. };
  224. template<>
  225. struct EngineUnmarshallData< U8 >
  226. {
  227. U8 operator()( ConsoleValueRef &ref ) const
  228. {
  229. return (U8)((S32)ref);
  230. }
  231. U8 operator()( const char* str ) const
  232. {
  233. return dAtoui( str );
  234. }
  235. };
  236. template<>
  237. struct EngineUnmarshallData< const char* >
  238. {
  239. const char* operator()( ConsoleValueRef &ref ) const
  240. {
  241. return ref.getStringValue();
  242. }
  243. const char* operator()( const char* str ) const
  244. {
  245. return str;
  246. }
  247. };
  248. template< typename T >
  249. struct EngineUnmarshallData< T* >
  250. {
  251. T* operator()( ConsoleValueRef &ref ) const
  252. {
  253. return dynamic_cast< T* >( Sim::findObject( ref.getStringValue() ) );
  254. }
  255. T* operator()( const char* str ) const
  256. {
  257. return dynamic_cast< T* >( Sim::findObject( str ) );
  258. }
  259. };
  260. template<>
  261. struct EngineUnmarshallData< void >
  262. {
  263. void operator()( ConsoleValueRef& ) const {}
  264. void operator()( const char* ) const {}
  265. };
  266. template<>
  267. struct EngineUnmarshallData< ConsoleValueRef >
  268. {
  269. ConsoleValueRef operator()( ConsoleValueRef ref ) const
  270. {
  271. return ref;
  272. }
  273. };
  274. /// @}
  275. /// @name C to C++ Trampolines
  276. ///
  277. /// The trampolines serve two purposes:
  278. ///
  279. /// For one, they ensure that no matter what argument types are specified by users of the engine API macros, the correct
  280. /// argument value types are enforced on the functions exported by the engine. Let's say, for example, the user writes
  281. /// a function that takes a "Point3F direction" argument, then the template machinery here will automatically expose an
  282. /// API function that takes a "Point3F& direction" argument.
  283. ///
  284. /// Secondly, the templates jump the incoming calls from extern "C" space into C++ space. This is mostly relevant for
  285. /// methods only as they will need an implicit object type argument.
  286. ///
  287. /// @{
  288. // Helper type to factor out commonalities between function and method trampolines.
  289. template<typename T> struct _EngineTrampoline {
  290. struct Args {};
  291. };
  292. template< typename R, typename ...ArgTs >
  293. struct _EngineTrampoline< R( ArgTs ... ) >
  294. {
  295. template<typename T> using AVT = typename EngineTypeTraits<T>::ArgumentValueType;
  296. typedef fixed_tuple<AVT<ArgTs> ...> Args;
  297. Args argT;
  298. };
  299. template< typename T >
  300. struct _EngineFunctionTrampolineBase : public _EngineTrampoline< T >
  301. {
  302. typedef T FunctionType;
  303. };
  304. // Trampolines for any call-ins that aren't methods.
  305. template< typename T >
  306. struct _EngineFunctionTrampoline {};
  307. template< typename R, typename ...ArgTs >
  308. struct _EngineFunctionTrampoline< R(ArgTs...) > : public _EngineFunctionTrampolineBase< R(ArgTs...) >
  309. {
  310. private:
  311. using Super = _EngineFunctionTrampolineBase< R(ArgTs...) >;
  312. using SelfType = _EngineFunctionTrampoline< R(ArgTs...) >;
  313. using ArgsType = typename _EngineFunctionTrampolineBase< R(ArgTs ...) >::Args;
  314. template<size_t ...> struct Seq {};
  315. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  316. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  317. template<size_t I>
  318. static typename fixed_tuple_element<I, fixed_tuple<ArgTs...>>::type getAndToType(const ArgsType& args) {
  319. return EngineTypeTraits<typename fixed_tuple_element<I, fixed_tuple<ArgTs...>>::type>::ArgumentToValue(fixed_tuple_accessor<I>::get(args));
  320. }
  321. template<size_t ...I>
  322. static R dispatchHelper(typename Super::FunctionType fn, const ArgsType& args, Seq<I...>) {
  323. return R( fn(SelfType::template getAndToType<I>(args) ...) );
  324. }
  325. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  326. public:
  327. static R jmp(typename Super::FunctionType fn, const ArgsType& args )
  328. {
  329. return dispatchHelper(fn, args, SeqType());
  330. }
  331. };
  332. // Trampolines for engine methods
  333. template< typename T >
  334. struct _EngineMethodTrampolineBase : public _EngineTrampoline< T > {};
  335. template< typename Frame, typename T >
  336. struct _EngineMethodTrampoline {};
  337. template< typename Frame, typename R, typename ...ArgTs >
  338. struct _EngineMethodTrampoline< Frame, R(ArgTs ...) > : public _EngineMethodTrampolineBase< R(ArgTs ...) >
  339. {
  340. using FunctionType = R( typename Frame::ObjectType*, ArgTs ...);
  341. private:
  342. using Super = _EngineMethodTrampolineBase< R(ArgTs ...) >;
  343. using SelfType = _EngineMethodTrampoline< Frame, R(ArgTs ...) >;
  344. using ArgsType = typename _EngineMethodTrampolineBase< R(ArgTs ...) >::Args;
  345. template<size_t ...> struct Seq {};
  346. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  347. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  348. template<size_t I>
  349. static typename fixed_tuple_element<I, fixed_tuple<ArgTs...>>::type getAndToType(const ArgsType& args) {
  350. return typename EngineTypeTraits<typename fixed_tuple_element<I, fixed_tuple<ArgTs...>>::type>::ArgumentToValue(fixed_tuple_accessor<I>::get(args));
  351. }
  352. template<size_t ...I>
  353. static R dispatchHelper(Frame f, const ArgsType& args, Seq<I...>) {
  354. return R(f._exec(SelfType::template getAndToType<I>(args) ...));
  355. }
  356. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  357. public:
  358. static R jmp( typename Frame::ObjectType* object, const ArgsType& args )
  359. {
  360. Frame f;
  361. f.object = object;
  362. return dispatchHelper(f, args, SeqType());
  363. }
  364. };
  365. /// @}
  366. /// @name Thunking
  367. ///
  368. /// Internal functionality for thunks placed between TorqueScript calls of engine functions and their native
  369. /// implementations.
  370. ///
  371. /// @note The functionality in this group is specific to the console interop system.
  372. /// @{
  373. // Helper function to return data from a thunk.
  374. template< typename T >
  375. inline const char* _EngineConsoleThunkReturnValue( const T& value )
  376. {
  377. return EngineMarshallData( value );
  378. }
  379. inline bool _EngineConsoleThunkReturnValue( bool value )
  380. {
  381. return value;
  382. }
  383. inline S32 _EngineConsoleThunkReturnValue( S32 value )
  384. {
  385. return value;
  386. }
  387. inline F32 _EngineConsoleThunkReturnValue( F32 value )
  388. {
  389. return value;
  390. }
  391. inline const char* _EngineConsoleThunkReturnValue( const String& str )
  392. {
  393. return Con::getReturnBuffer( str );
  394. }
  395. inline const char* _EngineConsoleThunkReturnValue( const char* value )
  396. {
  397. return EngineMarshallData( value );
  398. }
  399. template< typename T >
  400. inline const char* _EngineConsoleThunkReturnValue( T* value )
  401. {
  402. return ( value ? value->getIdString() : "" );
  403. }
  404. template< typename T >
  405. inline const char* _EngineConsoleThunkReturnValue( const T* value )
  406. {
  407. return ( value ? value->getIdString() : "" );
  408. }
  409. // Helper class to determine the type of callback registered with the console system.
  410. template< typename R >
  411. struct _EngineConsoleThunkType
  412. {
  413. typedef const char* ReturnType;
  414. typedef StringCallback CallbackType;
  415. };
  416. template<>
  417. struct _EngineConsoleThunkType< S32 >
  418. {
  419. typedef S32 ReturnType;
  420. typedef IntCallback CallbackType;
  421. };
  422. template<>
  423. struct _EngineConsoleThunkType< U32 >
  424. {
  425. typedef U32 ReturnType;
  426. typedef IntCallback CallbackType;
  427. };
  428. template<>
  429. struct _EngineConsoleThunkType< F32 >
  430. {
  431. typedef F32 ReturnType;
  432. typedef FloatCallback CallbackType;
  433. };
  434. template<>
  435. struct _EngineConsoleThunkType< bool >
  436. {
  437. typedef bool ReturnType;
  438. typedef BoolCallback CallbackType;
  439. };
  440. template<>
  441. struct _EngineConsoleThunkType< void >
  442. {
  443. typedef void ReturnType;
  444. typedef VoidCallback CallbackType;
  445. };
  446. // Helper struct to count the number of parameters in a function list.
  447. // The setup through operator () allows omitting the the argument list entirely.
  448. struct _EngineConsoleThunkCountArgs
  449. {
  450. template<typename ...ArgTs> U32 operator()(ArgTs... args){
  451. return sizeof...(ArgTs);
  452. }
  453. operator U32() const{ // FIXME: WHAT IS THIS?? I'm pretty sure it's incorrect, and it's the version that is invoked by all the macros
  454. return 0;
  455. }
  456. };
  457. // Encapsulation of a legacy console function invocation.
  458. namespace engineAPI{
  459. namespace detail{
  460. template<S32 startArgc, typename R, typename ...ArgTs>
  461. struct ThunkHelpers {
  462. using SelfType = ThunkHelpers<startArgc, R, ArgTs...>;
  463. using FunctionType = R(*)(ArgTs...);
  464. template<typename Frame> using MethodType = R(Frame::*)(ArgTs ...) const;
  465. template<size_t I> using IthArgType = typename std::tuple_element<I, std::tuple<ArgTs ...> >::type;
  466. template<size_t ...> struct Seq {};
  467. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  468. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  469. typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType;
  470. static const S32 NUM_ARGS = sizeof...(ArgTs) + startArgc;
  471. template<size_t index, size_t method_offset = 0, typename ...RealArgTs>
  472. static IthArgType<index> getRealArgValue(S32 argc, ConsoleValueRef *argv, const _EngineFunctionDefaultArguments< void(RealArgTs...) >& defaultArgs)
  473. {
  474. if((startArgc + index) < argc)
  475. {
  476. return EngineUnmarshallData< IthArgType<index> >()( argv[ startArgc + index ] );
  477. } else {
  478. return fixed_tuple_accessor<index + method_offset>::get(defaultArgs.mArgs);
  479. }
  480. }
  481. template<size_t ...I>
  482. static R dispatchHelper(S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs, Seq<I...>){
  483. return fn(SelfType::getRealArgValue<I>(argc, argv, defaultArgs) ...);
  484. }
  485. template<typename Frame, size_t ...I>
  486. static R dispatchHelper(S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs, Seq<I...>){
  487. return (frame->*fn)(SelfType::getRealArgValue<I,1>(argc, argv, defaultArgs) ...);
  488. }
  489. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  490. };
  491. template<typename ArgVT> struct MarshallHelpers {
  492. template<typename ...ArgTs> static void marshallEach(S32 &argc, ArgVT *argv, const ArgTs& ...args){}
  493. template<typename H, typename ...Tail> static void marshallEach(S32 &argc, ArgVT *argv, const H& head, const Tail& ...tail){
  494. argv[argc++] = EngineMarshallData(head);
  495. marshallEach(argc, argv, tail...);
  496. }
  497. };
  498. template<> struct MarshallHelpers<ConsoleValueRef> {
  499. template<typename ...ArgTs> static void marshallEach(S32 &argc, ConsoleValueRef *argv, const ArgTs& ...args){}
  500. template<typename H, typename ...Tail> static void marshallEach(S32 &argc, ConsoleValueRef *argv, const H& head, const Tail& ...tail){
  501. EngineMarshallData(head, argc, argv);
  502. marshallEach(argc, argv, tail...);
  503. }
  504. };
  505. }
  506. }
  507. template< S32 startArgc, typename T >
  508. struct _EngineConsoleThunk {};
  509. template< S32 startArgc, typename R, typename ...ArgTs >
  510. struct _EngineConsoleThunk< startArgc, R(ArgTs...) >
  511. {
  512. private:
  513. using Helper = engineAPI::detail::ThunkHelpers<startArgc, R, ArgTs...>;
  514. using SeqType = typename Helper::SeqType;
  515. public:
  516. typedef typename Helper::FunctionType FunctionType;
  517. typedef typename Helper::ReturnType ReturnType;
  518. template<typename Frame> using MethodType = typename Helper::template MethodType<Frame>;
  519. static const S32 NUM_ARGS = Helper::NUM_ARGS;
  520. static ReturnType thunk( S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs)
  521. {
  522. return _EngineConsoleThunkReturnValue( Helper::dispatchHelper(argc, argv, fn, defaultArgs, SeqType()));
  523. }
  524. template< typename Frame >
  525. static ReturnType thunk( S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs)
  526. {
  527. return _EngineConsoleThunkReturnValue( Helper::dispatchHelper(argc, argv, fn, frame, defaultArgs, SeqType()));
  528. }
  529. };
  530. // Have to do a partial specialization for void-returning functions :(
  531. template<S32 startArgc, typename ...ArgTs>
  532. struct _EngineConsoleThunk<startArgc, void(ArgTs...)> {
  533. private:
  534. using Helper = engineAPI::detail::ThunkHelpers<startArgc, void, ArgTs...>;
  535. using SeqType = typename Helper::SeqType;
  536. public:
  537. typedef typename Helper::FunctionType FunctionType;
  538. typedef typename Helper::ReturnType ReturnType;
  539. template<typename Frame> using MethodType = typename Helper::template MethodType<Frame>;
  540. static const S32 NUM_ARGS = Helper::NUM_ARGS;
  541. static void thunk( S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs)
  542. {
  543. Helper::dispatchHelper(argc, argv, fn, defaultArgs, SeqType());
  544. }
  545. template< typename Frame >
  546. static void thunk( S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs)
  547. {
  548. Helper::dispatchHelper(argc, argv, fn, frame, defaultArgs, SeqType());
  549. }
  550. };
  551. /// @}
  552. /// @name API Definition Macros
  553. ///
  554. /// The macros in this group allow to create engine API functions that work both with the
  555. /// legacy console system as well as with the new engine export system. As such, they only
  556. /// support those function features that are available in both systems. This means that for
  557. /// console-style variadic functions, the ConsoleXXX must be used and that for overloaded
  558. /// and/or C-style variadic functions as well as for placing functions in export scopes,
  559. /// DEFINE_CALLIN must be used directly.
  560. ///
  561. /// When the console system is removed, the console thunking functionality will be removed
  562. /// from these macros but otherwise they will remain unchanged and in place.
  563. ///
  564. /// @{
  565. // Helpers to implement initialization checks. Pulled out into separate macros so this can be deactivated easily.
  566. // Especially important for the initialize() function itself.
  567. #define _CHECK_ENGINE_INITIALIZED_IMPL( fnName, returnType ) \
  568. if( !engineAPI::gIsInitialized ) \
  569. { \
  570. Con::errorf( "EngineAPI: Engine not initialized when calling " #fnName ); \
  571. return EngineTypeTraits< returnType >::ReturnValue( EngineTypeTraits< returnType >::ReturnValueType() ); \
  572. }
  573. #define _CHECK_ENGINE_INITIALIZED( fnName, returnType ) _CHECK_ENGINE_INITIALIZED_IMPL( fnName, returnType )
  574. /// Define a call-in point for calling into the engine.
  575. ///
  576. /// @param name The name of the function as it should be seen by the control layer.
  577. /// @param returnType The value type returned to the control layer.
  578. /// @param args The argument list as it would appear on the function definition
  579. /// @param defaultArgs The list of default argument values.
  580. /// @param usage The usage doc string for the engine API reference.
  581. ///
  582. /// @code
  583. /// DefineEngineFunction( myFunction, int, ( float f, const String& s ), ( "value for s" ), "This is my function." )
  584. /// {
  585. /// return int( f ) + dAtoi( s );
  586. /// }
  587. /// @endcode
  588. #define DefineEngineFunction( name, returnType, args, defaultArgs, usage ) \
  589. static inline returnType _fn ## name ## impl args; \
  590. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  591. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  592. { \
  593. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  594. return EngineTypeTraits< returnType >::ReturnValue( \
  595. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## name ## impl, a ) \
  596. ); \
  597. } \
  598. static _EngineFunctionDefaultArguments< void args > _fn ## name ## DefaultArgs defaultArgs; \
  599. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  600. #name, \
  601. &_SCOPE<>()(), \
  602. usage, \
  603. #returnType " " #name #args, \
  604. "fn" #name, \
  605. TYPE< returnType args >(), \
  606. &_fn ## name ## DefaultArgs, \
  607. ( void* ) &fn ## name, \
  608. 0 \
  609. ); \
  610. static _EngineConsoleThunkType< returnType >::ReturnType _ ## name ## caster( SimObject*, S32 argc, ConsoleValueRef *argv ) \
  611. { \
  612. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 1, returnType args >::thunk( \
  613. argc, argv, &_fn ## name ## impl, _fn ## name ## DefaultArgs \
  614. ) ); \
  615. } \
  616. static ConsoleFunctionHeader _ ## name ## header \
  617. ( #returnType, #args, #defaultArgs ); \
  618. static ConsoleConstructor \
  619. _ ## name ## obj( NULL, #name, _EngineConsoleThunkType< returnType >::CallbackType( _ ## name ## caster ), usage, \
  620. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  621. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS, \
  622. false, &_ ## name ## header \
  623. ); \
  624. static inline returnType _fn ## name ## impl args
  625. // The next thing is a bit tricky. DefineEngineMethod allows to make the 'object' (=this) argument to the function
  626. // implicit which presents quite an obstacle for the macro internals as the engine export system requires the
  627. // name of a DLL symbol that represents an extern "C" function with an explicit first object pointer argument.
  628. //
  629. // Even if we ignored the fact that we don't have a guarantee how the various C++ compilers implement implicit 'this' arguments,
  630. // we could still not just use a C++ method for this as then we would have to get past the C++ compiler's mangling to
  631. // get to the function symbol name (let alone the fact that typing this method correctly would be tricky).
  632. //
  633. // So, the trick employed here is to package all but the implicit 'this' argument in a structure and then define an
  634. // extern "C" function that takes the object pointer as a first argument and the struct type as the second argument.
  635. // This will result in a function with an identical stack call frame layout to the function we want.
  636. //
  637. // Unfortunately, that still requires that function to chain on to the real user-defined function. To do this
  638. // cleanly and portably, _EngineMethodTrampoline is used to unpack and jump the call from extern "C" into C++ space.
  639. // In optimized builds, the compiler should be smart enough to pretty much optimize all our trickery here away.
  640. #define _DefineMethodTrampoline( className, name, returnType, args ) \
  641. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType \
  642. fn ## className ## _ ## name ( className* object, _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::Args a )\
  643. { \
  644. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  645. return EngineTypeTraits< returnType >::ReturnValue( \
  646. _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::jmp( object, a ) \
  647. ); \
  648. }
  649. /// Define a call-in point for calling a method on an engine object.
  650. ///
  651. /// @param name The name of the C++ class.
  652. /// @param name The name of the method as it should be seen by the control layer.
  653. /// @param returnType The value type returned to the control layer.
  654. /// @param args The argument list as it would appear on the function definition
  655. /// @param defaultArgs The list of default argument values.
  656. /// @param usage The usage doc string for the engine API reference.
  657. ///
  658. /// @code
  659. /// DefineEngineMethod( MyClass, myMethod, int, ( float f, const String& s ), ( "value for s" ), "This is my method." )
  660. /// {
  661. /// return object->someMethod( f, s );
  662. /// }
  663. /// @endcode
  664. #define DefineEngineMethod( className, name, returnType, args, defaultArgs, usage ) \
  665. struct _ ## className ## name ## frame \
  666. { \
  667. typedef className ObjectType; \
  668. className* object; \
  669. inline returnType _exec args const; \
  670. }; \
  671. _DefineMethodTrampoline( className, name, returnType, args ); \
  672. static _EngineFunctionDefaultArguments< _EngineMethodTrampoline< _ ## className ## name ## frame, void args >::FunctionType > \
  673. _fn ## className ## name ## DefaultArgs defaultArgs; \
  674. static EngineFunctionInfo _fn ## className ## name ## FunctionInfo( \
  675. #name, \
  676. &_SCOPE< className >()(), \
  677. usage, \
  678. "virtual " #returnType " " #name #args, \
  679. "fn" #className "_" #name, \
  680. TYPE< _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::FunctionType >(), \
  681. &_fn ## className ## name ## DefaultArgs, \
  682. ( void* ) &fn ## className ## _ ## name, \
  683. 0 \
  684. ); \
  685. static _EngineConsoleThunkType< returnType >::ReturnType _ ## className ## name ## caster( SimObject* object, S32 argc, ConsoleValueRef *argv ) \
  686. { \
  687. _ ## className ## name ## frame frame; \
  688. frame.object = static_cast< className* >( object ); \
  689. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 2, returnType args >::thunk( \
  690. argc, argv, &_ ## className ## name ## frame::_exec, &frame, _fn ## className ## name ## DefaultArgs \
  691. ) ); \
  692. } \
  693. static ConsoleFunctionHeader _ ## className ## name ## header \
  694. ( #returnType, #args, #defaultArgs ); \
  695. static ConsoleConstructor \
  696. className ## name ## obj( #className, #name, \
  697. _EngineConsoleThunkType< returnType >::CallbackType( _ ## className ## name ## caster ), usage, \
  698. _EngineConsoleThunk< 2, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  699. _EngineConsoleThunk< 2, returnType args >::NUM_ARGS, \
  700. false, &_ ## className ## name ## header \
  701. ); \
  702. returnType _ ## className ## name ## frame::_exec args const
  703. /// Define a call-in point for calling into the engine. Unlike with DefineEngineFunction, the statically
  704. /// callable function will be confined to the namespace of the given class.
  705. ///
  706. /// @param classname The name of the C++ class (or a registered export scope).
  707. /// @param name The name of the method as it should be seen by the control layer.
  708. /// @param returnType The value type returned to the control layer.
  709. /// @param args The argument list as it would appear on the function definition
  710. /// @param defaultArgs The list of default argument values.
  711. /// @param usage The usage doc string for the engine API reference.
  712. ///
  713. /// @code
  714. /// DefineEngineStaticMethod( MyClass, myMethod, int, ( float f, string s ), ( "value for s" ), "This is my method." )
  715. /// {
  716. /// }
  717. /// @endcode
  718. #define DefineEngineStaticMethod( className, name, returnType, args, defaultArgs, usage ) \
  719. static inline returnType _fn ## className ## name ## impl args; \
  720. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  721. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  722. { \
  723. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  724. return EngineTypeTraits< returnType >::ReturnValue( \
  725. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## className ## name ## impl, a ) \
  726. ); \
  727. } \
  728. static _EngineFunctionDefaultArguments< void args > _fn ## className ## name ## DefaultArgs defaultArgs; \
  729. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  730. #name, \
  731. &_SCOPE< className >()(), \
  732. usage, \
  733. #returnType " " #name #args, \
  734. "fn" #className "_" #name, \
  735. TYPE< returnType args >(), \
  736. &_fn ## className ## name ## DefaultArgs, \
  737. ( void* ) &fn ## className ## _ ## name, \
  738. 0 \
  739. ); \
  740. static _EngineConsoleThunkType< returnType >::ReturnType _ ## className ## name ## caster( SimObject*, S32 argc, ConsoleValueRef *argv )\
  741. { \
  742. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 1, returnType args >::thunk( \
  743. argc, argv, &_fn ## className ## name ## impl, _fn ## className ## name ## DefaultArgs \
  744. ) ); \
  745. } \
  746. static ConsoleFunctionHeader _ ## className ## name ## header \
  747. ( #returnType, #args, #defaultArgs, true ); \
  748. static ConsoleConstructor \
  749. _ ## className ## name ## obj( #className, #name, _EngineConsoleThunkType< returnType >::CallbackType( _ ## className ## name ## caster ), usage, \
  750. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  751. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS, \
  752. false, &_ ## className ## name ## header \
  753. ); \
  754. static inline returnType _fn ## className ## name ## impl args
  755. # define DefineEngineStringlyVariadicFunction(name,returnType,minArgs,maxArgs,usage) \
  756. static inline returnType _fn ## name ## impl (SimObject *, S32 argc, ConsoleValueRef *argv); \
  757. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  758. (Vector<const char*>* vec) \
  759. { \
  760. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  761. StringStackConsoleWrapper args(vec->size(), vec->address()); \
  762. return EngineTypeTraits< returnType >::ReturnValue( \
  763. _fn ## name ## impl(NULL, args.count(), args) \
  764. ); \
  765. } \
  766. static _EngineFunctionDefaultArguments< void (Vector<const char*>* vec) > _fn ## name ## DefaultArgs; \
  767. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  768. #name, \
  769. &_SCOPE<>()(), \
  770. usage, \
  771. #returnType " " #name "(Vector<String> args)", \
  772. "fn" #name, \
  773. TYPE< returnType (Vector<const char*>* vec) >(), \
  774. &_fn ## name ## DefaultArgs, \
  775. ( void* ) &fn ## name, \
  776. 0 \
  777. ); \
  778. ConsoleConstructor cc_##name##_obj(NULL,#name,_fn ## name ## impl,usage,minArgs,maxArgs); \
  779. returnType _fn ## name ## impl(SimObject *, S32 argc, ConsoleValueRef *argv)
  780. # define DefineEngineStringlyVariadicMethod(className, name,returnType,minArgs,maxArgs,usage) \
  781. struct _ ## className ## name ## frame \
  782. { \
  783. typedef className ObjectType; \
  784. className* object; \
  785. inline returnType _exec (S32 argc, ConsoleValueRef* argv) const; \
  786. }; \
  787. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  788. (className* object, Vector<const char*>* vec) \
  789. { \
  790. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  791. StringStackConsoleWrapper args(vec->size(), vec->address()); \
  792. _ ## className ## name ## frame frame {}; \
  793. frame.object = static_cast< className* >( object ); \
  794. return EngineTypeTraits< returnType >::ReturnValue( \
  795. frame._exec(args.count(), args) \
  796. ); \
  797. } \
  798. static _EngineFunctionDefaultArguments< void (className* object, S32 argc, const char** argv) > \
  799. _fn ## className ## name ## DefaultArgs; \
  800. static EngineFunctionInfo _fn ## className ## name ## FunctionInfo( \
  801. #name, \
  802. &_SCOPE< className >()(), \
  803. usage, \
  804. "virtual " #returnType " " #name "(Vector<String> args)", \
  805. "fn" #className "_" #name, \
  806. TYPE< _EngineMethodTrampoline< _ ## className ## name ## frame, returnType (Vector<const char*> vec) >::FunctionType >(), \
  807. &_fn ## className ## name ## DefaultArgs, \
  808. ( void* ) &fn ## className ## _ ## name, \
  809. 0 \
  810. ); \
  811. returnType cm_##className##_##name##_caster(SimObject* object, S32 argc, ConsoleValueRef* argv) { \
  812. AssertFatal( dynamic_cast<className*>( object ), "Object passed to " #name " is not a " #className "!" ); \
  813. _ ## className ## name ## frame frame {}; \
  814. frame.object = static_cast< className* >( object ); \
  815. conmethod_return_##returnType ) frame._exec(argc,argv); \
  816. }; \
  817. ConsoleConstructor cc_##className##_##name##_obj(#className,#name,cm_##className##_##name##_caster,usage,minArgs,maxArgs); \
  818. inline returnType _ ## className ## name ## frame::_exec(S32 argc, ConsoleValueRef *argv) const
  819. // The following three macros are only temporary. They allow to define engineAPI functions using the framework
  820. // here in this file while being visible only in the new API. When the console interop is removed, these macros
  821. // can be removed and all their uses be replaced with their corresponding versions that now still include support
  822. // for the console (e.g. DefineNewEngineFunction should become DefineEngineFunction).
  823. #define DefineNewEngineFunction( name, returnType, args, defaultArgs, usage ) \
  824. static inline returnType _fn ## name ## impl args; \
  825. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  826. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  827. { \
  828. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  829. return EngineTypeTraits< returnType >::ReturnValue( \
  830. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## name ## impl, a ) \
  831. ); \
  832. } \
  833. static _EngineFunctionDefaultArguments< void args > _fn ## name ## DefaultArgs defaultArgs; \
  834. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  835. #name, \
  836. &_SCOPE<>()(), \
  837. usage, \
  838. #returnType " " #name #args, \
  839. "fn" #name, \
  840. TYPE< returnType args >(), \
  841. &_fn ## name ## DefaultArgs, \
  842. ( void* ) &fn ## name, \
  843. 0 \
  844. ); \
  845. static inline returnType _fn ## name ## impl args
  846. #define DefineNewEngineMethod( className, name, returnType, args, defaultArgs, usage ) \
  847. struct _ ## className ## name ## frame \
  848. { \
  849. typedef className ObjectType; \
  850. className* object; \
  851. inline returnType _exec args const; \
  852. }; \
  853. _DefineMethodTrampoline( className, name, returnType, args ); \
  854. static _EngineFunctionDefaultArguments< _EngineMethodTrampoline< _ ## className ## name ## frame, void args >::FunctionType > \
  855. _fn ## className ## name ## DefaultArgs defaultArgs; \
  856. static EngineFunctionInfo _fn ## className ## name ## FunctionInfo( \
  857. #name, \
  858. &_SCOPE< className >()(), \
  859. usage, \
  860. "virtual " #returnType " " #name #args, \
  861. "fn" #className "_" #name, \
  862. TYPE< _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::FunctionType >(), \
  863. &_fn ## className ## name ## DefaultArgs, \
  864. ( void* ) &fn ## className ## _ ## name, \
  865. 0 \
  866. ); \
  867. returnType _ ## className ## name ## frame::_exec args const
  868. #define DefineNewEngineStaticMethod( className, name, returnType, args, defaultArgs, usage ) \
  869. static inline returnType _fn ## className ## name ## impl args; \
  870. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  871. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  872. { \
  873. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  874. return EngineTypeTraits< returnType >::ReturnValue( \
  875. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## className ## name ## impl, a ) \
  876. ); \
  877. } \
  878. static _EngineFunctionDefaultArguments< void args > _fn ## className ## name ## DefaultArgs defaultArgs; \
  879. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  880. #name, \
  881. &_SCOPE< className >()(), \
  882. usage, \
  883. #returnType " " #name #args, \
  884. "fn" #className "_" #name, \
  885. TYPE< returnType args >(), \
  886. &_fn ## className ## name ## DefaultArgs, \
  887. ( void* ) &fn ## className ## _ ## name, \
  888. 0 \
  889. ); \
  890. static inline returnType _fn ## className ## name ## impl args
  891. /// @}
  892. //=============================================================================
  893. // Callbacks.
  894. //=============================================================================
  895. /// Matching implement for DECLARE_CALLBACK.
  896. ///
  897. ///
  898. /// @warn With the new interop system, method-style callbacks <em>must not</em> be triggered on object
  899. /// that are being created! This is because the control layer will likely not yet have a fully valid wrapper
  900. /// object in place for the EngineObject under construction.
  901. #define IMPLEMENT_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  902. struct _ ## class ## name ## frame { typedef class ObjectType; }; \
  903. TORQUE_API _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  904. TORQUE_API void set_cb ## class ## _ ## name( \
  905. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType fn ) \
  906. { cb ## class ## _ ## name = fn; } \
  907. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  908. namespace { \
  909. ::EngineFunctionInfo _cb ## class ## name( \
  910. #name, \
  911. &::_SCOPE< class >()(), \
  912. usageString, \
  913. "virtual " #returnType " " #name #args, \
  914. "cb" #class "_" #name, \
  915. ::TYPE< _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType >(), \
  916. NULL, \
  917. ( void* ) &cb ## class ## _ ## name, \
  918. EngineFunctionCallout \
  919. ); \
  920. } \
  921. returnType class::name ## _callback args \
  922. { \
  923. if( cb ## class ## _ ## name ) { \
  924. _EngineCallbackHelper cbh( this, reinterpret_cast< const void* >( cb ## class ## _ ## name ) ); \
  925. return returnType( cbh.call< returnType > argNames ); \
  926. } \
  927. if( engineAPI::gUseConsoleInterop ) \
  928. { \
  929. static StringTableEntry sName = StringTable->insert( #name ); \
  930. _EngineConsoleCallbackHelper cbh( sName, this ); \
  931. return returnType( cbh.call< returnType > argNames ); \
  932. } \
  933. return returnType(); \
  934. } \
  935. namespace { \
  936. ConsoleFunctionHeader _ ## class ## name ## header( \
  937. #returnType, #args, "" ); \
  938. ConsoleConstructor _ ## class ## name ## obj( #class, #name, usageString, &_ ## class ## name ## header ); \
  939. }
  940. /// Used to define global callbacks not associated with
  941. /// any particular class or namespace.
  942. #define IMPLEMENT_GLOBAL_CALLBACK( name, returnType, args, argNames, usageString ) \
  943. DEFINE_CALLOUT( cb ## name, name,, returnType, args, 0, usageString ); \
  944. returnType name ## _callback args \
  945. { \
  946. if( cb ## name ) \
  947. return returnType( cb ## name argNames ); \
  948. if( engineAPI::gUseConsoleInterop ) \
  949. { \
  950. static StringTableEntry sName = StringTable->insert( #name ); \
  951. _EngineConsoleCallbackHelper cbh( sName, NULL ); \
  952. return returnType( cbh.call< returnType > argNames ); \
  953. } \
  954. return returnType(); \
  955. } \
  956. namespace { \
  957. ConsoleFunctionHeader _ ## name ## header( \
  958. #returnType, #args, "" ); \
  959. ConsoleConstructor _ ## name ## obj( NULL, #name, usageString, &_ ## name ## header ); \
  960. }
  961. // Again, temporary macros to allow splicing the API while we still have the console interop around.
  962. #define IMPLEMENT_CONSOLE_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  963. returnType class::name ## _callback args \
  964. { \
  965. if( engineAPI::gUseConsoleInterop ) \
  966. { \
  967. static StringTableEntry sName = StringTable->insert( #name ); \
  968. _EngineConsoleCallbackHelper cbh( sName, this ); \
  969. return returnType( cbh.call< returnType > argNames ); \
  970. } \
  971. return returnType(); \
  972. } \
  973. namespace { \
  974. ConsoleFunctionHeader _ ## class ## name ## header( \
  975. #returnType, #args, "" ); \
  976. ConsoleConstructor _ ## class ## name ## obj( #class, #name, usageString, &_ ## class ## name ## header ); \
  977. }
  978. #define IMPLEMENT_NEW_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  979. struct _ ## class ## name ## frame { typedef class ObjectType; }; \
  980. TORQUE_API _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  981. TORQUE_API void set_cb ## class ## _ ## name( \
  982. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType fn ) \
  983. { cb ## class ## _ ## name = fn; } \
  984. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  985. namespace { \
  986. ::EngineFunctionInfo _cb ## class ## name( \
  987. #name, \
  988. &::_SCOPE< class >()(), \
  989. usageString, \
  990. "virtual " #returnType " " #name #args, \
  991. "cb" #class "_" #name, \
  992. ::TYPE< _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType >(), \
  993. NULL, \
  994. &cb ## class ## _ ## name, \
  995. EngineFunctionCallout \
  996. ); \
  997. } \
  998. returnType class::name ## _callback args \
  999. { \
  1000. if( cb ## class ## _ ## name ) { \
  1001. _EngineCallbackHelper cbh( this, reinterpret_cast< const void* >( cb ## class ## _ ## name ) ); \
  1002. return returnType( cbh.call< returnType > argNames ); \
  1003. } \
  1004. return returnType(); \
  1005. }
  1006. // Internal helper class for doing call-outs in the new interop.
  1007. struct _EngineCallbackHelper
  1008. {
  1009. protected:
  1010. EngineObject* mThis;
  1011. const void* mFn;
  1012. public:
  1013. _EngineCallbackHelper( EngineObject* pThis, const void* fn )
  1014. : mThis( pThis ),
  1015. mFn( fn ) {}
  1016. template< typename R, typename ...ArgTs >
  1017. R call(ArgTs ...args) const
  1018. {
  1019. typedef R( FunctionType )( EngineObject*, ArgTs... );
  1020. return R( reinterpret_cast< FunctionType* >( const_cast<void*>(mFn) )( mThis, args... ) );
  1021. }
  1022. };
  1023. #include "console/stringStack.h"
  1024. // Internal helper for callback support in legacy console system.
  1025. struct _BaseEngineConsoleCallbackHelper
  1026. {
  1027. public:
  1028. /// Matches up to storeArgs.
  1029. static const U32 MAX_ARGUMENTS = 11;
  1030. SimObject* mThis;
  1031. S32 mInitialArgc;
  1032. S32 mArgc;
  1033. StringTableEntry mCallbackName;
  1034. ConsoleValueRef mArgv[ MAX_ARGUMENTS + 2 ];
  1035. ConsoleValueRef _exec();
  1036. ConsoleValueRef _execLater(SimConsoleThreadExecEvent *evt);
  1037. _BaseEngineConsoleCallbackHelper(): mThis(NULL), mInitialArgc(0), mArgc(0), mCallbackName(StringTable->EmptyString()){;}
  1038. };
  1039. // Base helper for console callbacks
  1040. struct _EngineConsoleCallbackHelper : public _BaseEngineConsoleCallbackHelper
  1041. {
  1042. private:
  1043. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1044. public:
  1045. _EngineConsoleCallbackHelper( StringTableEntry callbackName, SimObject* pThis )
  1046. {
  1047. mThis = pThis;
  1048. mArgc = mInitialArgc = pThis ? 2 : 1 ;
  1049. mCallbackName = callbackName;
  1050. }
  1051. template< typename R, typename ...ArgTs >
  1052. R call(ArgTs ...args)
  1053. {
  1054. if (Con::isMainThread())
  1055. {
  1056. ConsoleStackFrameSaver sav; sav.save();
  1057. CSTK.reserveValues(mArgc + sizeof...(ArgTs), mArgv);
  1058. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1059. Helper::marshallEach(mArgc, mArgv, args...);
  1060. return R( EngineUnmarshallData< R >()( _exec() ) );
  1061. }
  1062. else
  1063. {
  1064. SimConsoleThreadExecCallback cb;
  1065. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc + sizeof...(ArgTs), NULL, false, &cb);
  1066. evt->populateArgs(mArgv);
  1067. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1068. Helper::marshallEach(mArgc, mArgv, args...);
  1069. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1070. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1071. }
  1072. }
  1073. };
  1074. // Override for when first parameter is presumably a SimObject*, in which case A will be absorbed as the callback
  1075. template<typename P1> struct _EngineConsoleExecCallbackHelper : public _BaseEngineConsoleCallbackHelper
  1076. {
  1077. private:
  1078. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1079. public:
  1080. _EngineConsoleExecCallbackHelper( SimObject* pThis )
  1081. {
  1082. mThis = pThis;
  1083. mArgc = mInitialArgc = 2;
  1084. mCallbackName = NULL;
  1085. }
  1086. template< typename R, typename SCB, typename ...ArgTs >
  1087. R call( SCB simCB , ArgTs ...args )
  1088. {
  1089. if (Con::isMainThread())
  1090. {
  1091. ConsoleStackFrameSaver sav; sav.save();
  1092. CSTK.reserveValues(mArgc+sizeof...(ArgTs), mArgv);
  1093. mArgv[ 0 ].value->setStackStringValue(simCB);
  1094. Helper::marshallEach(mArgc, mArgv, args...);
  1095. return R( EngineUnmarshallData< R >()( _exec() ) );
  1096. }
  1097. else
  1098. {
  1099. SimConsoleThreadExecCallback cb;
  1100. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc+sizeof...(ArgTs), NULL, true, &cb);
  1101. evt->populateArgs(mArgv);
  1102. mArgv[ 0 ].value->setStackStringValue(simCB);
  1103. Helper::marshallEach(mArgc, mArgv, args...);
  1104. Sim::postEvent(mThis, evt, Sim::getCurrentTime());
  1105. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1106. }
  1107. }
  1108. };
  1109. // Override for when first parameter is const char*
  1110. template<> struct _EngineConsoleExecCallbackHelper<const char*> : public _BaseEngineConsoleCallbackHelper
  1111. {
  1112. private:
  1113. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1114. public:
  1115. _EngineConsoleExecCallbackHelper( const char *callbackName )
  1116. {
  1117. mThis = NULL;
  1118. mArgc = mInitialArgc = 1;
  1119. mCallbackName = StringTable->insert(callbackName);
  1120. }
  1121. template< typename R, typename ...ArgTs >
  1122. R call(ArgTs ...args)
  1123. {
  1124. if (Con::isMainThread())
  1125. {
  1126. ConsoleStackFrameSaver sav; sav.save();
  1127. CSTK.reserveValues(mArgc+sizeof...(ArgTs), mArgv);
  1128. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1129. Helper::marshallEach(mArgc, mArgv, args...);
  1130. return R( EngineUnmarshallData< R >()( _exec() ) );
  1131. }
  1132. else
  1133. {
  1134. SimConsoleThreadExecCallback cb;
  1135. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc+sizeof...(ArgTs), NULL, false, &cb);
  1136. evt->populateArgs(mArgv);
  1137. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1138. Helper::marshallEach(mArgc, mArgv, args...);
  1139. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1140. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1141. }
  1142. }
  1143. };
  1144. // Re-enable some VC warnings we disabled for this file.
  1145. #pragma warning( pop ) // 4510 and 4610
  1146. #endif // !_ENGINEAPI_H_