2 /// Expose C++ objects to Nasal as ghosts
4 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Library General Public
8 // License as published by the Free Software Foundation; either
9 // version 2 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Library General Public License for more details.
16 // You should have received a copy of the GNU Library General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
23 #include "from_nasal.hxx"
24 #include "to_nasal.hxx"
26 #include <simgear/debug/logstream.hxx>
28 #include <boost/bind.hpp>
29 #include <boost/function.hpp>
30 #include <boost/lambda/lambda.hpp>
31 #include <boost/utility/enable_if.hpp>
36 * Bindings between C++ and the Nasal scripting language
42 * Traits for C++ classes exposed as Ghost. This is the basic template for
46 struct GhostTypeTraits
48 /** Whether the class is passed by shared pointer or raw pointer */
49 typedef boost::false_type::type is_shared;
51 /** The raw class type (Without any shared pointer) */
56 struct GhostTypeTraits<boost::shared_ptr<T> >
58 typedef boost::true_type::type is_shared;
64 struct GhostTypeTraits<osg::ref_ptr<T> >
66 typedef boost::true_type::type is_shared;
71 #ifdef SGSharedPtr_HXX
73 struct GhostTypeTraits<SGSharedPtr<T> >
75 typedef boost::true_type::type is_shared;
81 * Policy for creating ghost instances from shared pointer objects.
84 struct SharedPointerPolicy
86 typedef typename GhostTypeTraits<T>::raw_type raw_type;
87 typedef boost::false_type returns_dynamic_type;
90 * Create a shared pointer on the heap to handle the reference counting for
91 * the passed shared pointer while it is used in Nasal space.
93 static T* createInstance(const T& ptr)
98 static raw_type* getRawPtr(void* ptr)
100 return static_cast<T*>(ptr)->get();
105 * Policy for creating ghost instances as raw objects on the heap.
108 struct RawPointerPolicy
110 typedef typename GhostTypeTraits<T>::raw_type raw_type;
111 typedef boost::true_type returns_dynamic_type;
114 * Create a new object instance on the heap
116 static T* createInstance()
121 static raw_type* getRawPtr(void* ptr)
123 BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
124 return static_cast<T*>(ptr);
131 * Metadata for Ghost object types
137 * Add a nasal base class to the ghost. Will be available in the ghosts
140 void addNasalBase(const naRef& parent)
142 assert( naIsHash(parent) );
143 _parents.push_back(parent);
147 const std::string _name;
148 naGhostType _ghost_type;
149 // std::vector<GhostMetadata*> _base_classes;
150 std::vector<naRef> _parents;
152 explicit GhostMetadata(const std::string& name):
158 // void addBaseClass(GhostMetadata* base)
161 // _base_classes.push_back(base);
164 naRef getParents(naContext c)
166 return nasal::to_nasal(c, _parents);
172 * Class for exposing C++ objects to Nasal
175 * // Example class to be exposed to Nasal
182 * naRef myMember(naContext c, int argc, naRef* args);
185 * void exposeClasses()
187 * // Register a nasal ghost type for MyClass. This needs to be done only
188 * // once before creating the first ghost instance.
189 * Ghost<MyClass>::init("MyClass")
190 * // Members can be exposed by getters and setters
191 * .member("x", &MyClass::getX, &MyClass::setX)
192 * // For readonly variables only pass a getter
193 * .member("x_readonly", &MyClass::getX)
194 * // It is also possible to expose writeonly members
195 * .member("x_writeonly", &MyClass::setX)
196 * // Methods use a slightly different syntax - The pointer to the member
197 * // function has to be passed as template argument
198 * .method<&MyClass::myMember>("myMember");
204 public internal::GhostMetadata,
205 protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
206 SharedPointerPolicy<T>,
207 RawPointerPolicy<T> >::type
210 typedef typename GhostTypeTraits<T>::raw_type raw_type;
211 typedef naRef (raw_type::*member_func_t)(naContext, int, naRef*);
212 typedef naRef (*free_func_t)(raw_type&, naContext, int, naRef*);
213 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
214 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
217 * A ghost member. Can consist either of getter and/or setter functions
218 * for exposing a data variable or a single callable function.
226 member_t( const getter_t& getter,
227 const setter_t& setter,
228 naCFunction func = 0 ):
234 member_t(naCFunction func):
243 typedef std::map<std::string, member_t> MemberMap;
246 * Register a new ghost type.
248 * @note Only intialize each ghost type once!
250 * @param name Descriptive name of the ghost type.
252 static Ghost& init(const std::string& name)
254 assert( !getSingletonPtr() );
256 getSingletonHolder().reset( new Ghost(name) );
257 return *getSingletonPtr();
261 * Register a base class for this ghost. The base class needs to be
262 * registers on its own before it can be used as base class.
264 * @tparam BaseGhost Type of base class already wrapped into Ghost class
268 * Ghost<MyBase>::init("MyBase");
269 * Ghost<MyClass>::init("MyClass")
270 * .bases<Ghost<MyBase> >();
273 template<class BaseGhost>
274 typename boost::enable_if_c
275 < boost::is_base_of<GhostMetadata, BaseGhost>::value
276 && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
281 BaseGhost* base = BaseGhost::getSingletonPtr();
284 // Both ways of retrieving the address of a static member function
285 // should be legal but not all compilers know this.
286 // g++-4.4.7+ has been tested to work with both versions
287 #if defined(GCC_VERSION) && GCC_VERSION < 40407
288 // The old version of g++ used on Jenkins (16.11.2012) only compiles
290 &getTypeFor<BaseGhost>
292 // VS (2008, 2010, ... ?) only allow this version.
293 &Ghost::getTypeFor<BaseGhost>
297 // Replace any getter that is not available in the current class.
298 // TODO check if this is the correct behavior of function overriding
299 for( typename BaseGhost::MemberMap::const_iterator member =
300 base->_members.begin();
301 member != base->_members.end();
304 if( _members.find(member->first) == _members.end() )
305 _members[member->first] = member_t
307 member->second.getter,
308 member->second.setter,
317 * Register a base class for this ghost. The base class needs to be
318 * registers on its own before it can be used as base class.
320 * @tparam Base Type of base class (Base as used in Ghost<Base>)
323 * Ghost<MyBase>::init("MyBase");
324 * Ghost<MyClass>::init("MyClass")
329 typename boost::enable_if_c
330 < !boost::is_base_of<GhostMetadata, Base>::value
331 && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
336 return bases< Ghost<Base> >();
340 * Register an existing Nasal class/hash as base class for this ghost.
342 * @param parent Nasal hash/class
344 Ghost& bases(const naRef& parent)
346 addNasalBase(parent);
351 * Register a member variable by passing a getter and/or setter method.
353 * @param field Name of member
354 * @param getter Getter for variable
355 * @param setter Setter for variable (Pass 0 to prevent write access)
359 Ghost& member( const std::string& field,
360 Var (raw_type::*getter)() const,
361 void (raw_type::*setter)(Var) = 0 )
366 naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
368 // Getter signature: naRef(naContext, raw_type&)
369 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
374 Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
376 // Setter signature: void(naContext, raw_type&, naRef)
377 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
380 return member(field, m.getter, m.setter);
384 * Register a write only member variable.
386 * @param field Name of member
387 * @param setter Setter for variable
390 Ghost& member( const std::string& field,
391 void (raw_type::*setter)(Var) )
393 return member<Var>(field, 0, setter);
397 * Register a member variable by passing a getter and/or setter method.
399 * @param field Name of member
400 * @param getter Getter for variable
401 * @param setter Setter for variable (Pass empty to prevent write access)
404 Ghost& member( const std::string& field,
405 const getter_t& getter,
406 const setter_t& setter = setter_t() )
408 if( !getter.empty() || !setter.empty() )
409 _members[field] = member_t(getter, setter);
415 "Member '" << field << "' requires a getter or setter"
421 * Register a member function.
423 * @note Because only function pointers can be registered as Nasal
424 * functions it is needed to pass the function pointer as template
425 * argument. This allows us to create a separate instance of the
426 * MemberFunctionWrapper for each registered function and therefore
427 * provides us with the needed static functions to be passed on to
430 * @tparam func Pointer to member function being registered.
436 * naRef myMethod(naContext c, int argc, naRef* args);
439 * Ghost<MyClass>::init("Test")
440 * .method<&MyClass::myMethod>("myMethod");
443 template<member_func_t func>
444 Ghost& method(const std::string& name)
446 _members[name].func = &MemberFunctionWrapper<func>::call;
451 * Register a free function as member function. The object instance is
452 * passed as additional first argument.
454 * @tparam func Pointer to free function being registered.
456 * @note Due to a severe bug in Visual Studio it is not possible to create
457 * a specialization of #method for free function pointers and
458 * member function pointers at the same time. Do overcome this
459 * limitation we had to use a different name for this function.
463 * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
465 * Ghost<MyClass>::init("Test")
466 * .method_func<&myMethod>("myMethod");
469 template<free_func_t func>
470 Ghost& method_func(const std::string& name)
472 _members[name].func = &FreeFunctionWrapper<func>::call;
476 // TODO use variadic template when supporting C++11
478 * Create a Nasal instance of this ghost.
480 * @param c Active Nasal context
482 static naRef create( naContext c )
484 return makeGhost(c, Ghost::createInstance());
488 * Create a Nasal instance of this ghost.
490 * @param c Active Nasal context
491 * @param a1 Parameter used for creating new instance
494 static naRef create( naContext c, const A1& a1 )
496 return makeGhost(c, Ghost::createInstance(a1));
500 * Nasal callback for creating a new instance of this ghost.
502 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
512 typedef naGhostType* (*type_checker_t)(const raw_type*);
513 typedef std::vector<type_checker_t> DerivedList;
514 DerivedList _derived_classes;
516 void addDerived(const type_checker_t& derived_info)
518 _derived_classes.push_back(derived_info);
521 template<class BaseGhost>
523 typename boost::enable_if
524 < boost::is_polymorphic<typename BaseGhost::raw_type>,
527 getTypeFor(const typename BaseGhost::raw_type* base)
529 // Check first if passed pointer can by converted to instance of class
532 < typename BaseGhost::raw_type,
533 typename Ghost::raw_type
535 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
538 // Now check if we can further downcast to one of our derived classes.
539 for( typename DerivedList::reverse_iterator
540 derived = getSingletonPtr()->_derived_classes.rbegin();
541 derived != getSingletonPtr()->_derived_classes.rend();
544 naGhostType* ghost_type =
545 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
550 // If base is not an instance of any derived class, this class has to
551 // be the dynamic type.
552 return &getSingletonPtr()->_ghost_type;
555 template<class BaseGhost>
557 typename boost::disable_if
558 < boost::is_polymorphic<typename BaseGhost::raw_type>,
561 getTypeFor(const typename BaseGhost::raw_type* base)
563 // For non polymorphic classes there is no possibility to get the actual
564 // dynamic type, therefore we can only use its static type.
565 return &BaseGhost::getSingletonPtr()->_ghost_type;
568 static Ghost* getSingletonPtr()
570 return getSingletonHolder().get();
573 // TODO integrate with from_nasal template to be able to cast objects
574 // passed as function argument.
575 static raw_type* from_nasal(naRef me)
577 if( naGhost_type(me) != &getSingletonPtr()->_ghost_type )
580 return Ghost::getRawPtr( static_cast<T*>(naGhost_ptr(me)) );
583 static raw_type& requireObject(naContext c, naRef me)
585 raw_type* obj = Ghost::from_nasal(me);
590 "method called on object of wrong type: '%s' expected",
591 getSingletonPtr()->_ghost_type.name
598 * Wrapper class to enable registering pointers to member functions as
599 * Nasal function callbacks. We need to use the function pointer as
600 * template parameter to ensure every registered function gets a static
601 * function which can be passed to Nasal.
603 template<member_func_t func>
604 struct MemberFunctionWrapper
607 * Called from Nasal upon invocation of the according registered
608 * function. Forwards the call to the passed object instance.
610 static naRef call(naContext c, naRef me, int argc, naRef* args)
612 return (requireObject(c, me).*func)(c, argc, args);
617 * Wrapper class to enable registering pointers to free functions (only
618 * external linkage). We need to use the function pointer as template
619 * parameter to ensure every registered function gets a static function
620 * which can be passed to Nasal. Even though we just wrap another simple
621 * function pointer this intermediate step is need to be able to retrieve
622 * the object the function call belongs to and pass it along as argument.
624 template<free_func_t func>
625 struct FreeFunctionWrapper
628 * Called from Nasal upon invocation of the according registered
629 * function. Forwards the call to the passed function pointer and passes
630 * the required parameters.
632 static naRef call(naContext c, naRef me, int argc, naRef* args)
634 return func(requireObject(c, me), c, argc, args);
638 typedef std::auto_ptr<Ghost> GhostPtr;
641 explicit Ghost(const std::string& name):
642 GhostMetadata( name )
644 _ghost_type.destroy = &destroyGhost;
645 _ghost_type.name = _name.c_str();
646 _ghost_type.get_member = &getMember;
647 _ghost_type.set_member = &setMember;
650 static GhostPtr& getSingletonHolder()
652 static GhostPtr instance;
656 static naRef makeGhost(naContext c, void *ptr)
658 if( !Ghost::getRawPtr(ptr) )
661 naGhostType* ghost_type = 0;
662 if( Ghost::returns_dynamic_type::value )
663 // For pointer policies already returning instances of an object with
664 // the dynamic type of this Ghost's raw_type the type is always the
666 ghost_type = &getSingletonPtr()->_ghost_type;
668 // If wrapping eg. shared pointers the users passes an already
669 // existing instance of an object which will then be hold be a new
670 // shared pointer. We therefore have to check for the dynamic type
671 // of the object as it might differ from the passed static type.
672 ghost_type = getTypeFor<Ghost>( Ghost::getRawPtr(ptr) );
677 return naNewGhost2(c, ghost_type, ptr);
680 static void destroyGhost(void *ptr)
686 * Callback for retrieving a ghost member.
688 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
690 const std::string key_str = nasal::from_nasal<std::string>(c, key);
691 if( key_str == "parents" )
693 if( getSingletonPtr()->_parents.empty() )
696 *out = getSingletonPtr()->getParents(c);
700 typename MemberMap::iterator member =
701 getSingletonPtr()->_members.find(key_str);
703 if( member == getSingletonPtr()->_members.end() )
706 if( member->second.func )
707 *out = nasal::to_nasal(c, member->second.func);
708 else if( !member->second.getter.empty() )
709 *out = member->second.getter(c, *Ghost::getRawPtr(g));
711 return "Read-protected member";
717 * Callback for writing to a ghost member.
719 static void setMember(naContext c, void* g, naRef field, naRef val)
721 const std::string key = nasal::from_nasal<std::string>(c, field);
722 typename MemberMap::iterator member =
723 getSingletonPtr()->_members.find(key);
725 if( member == getSingletonPtr()->_members.end() )
726 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
727 if( member->second.setter.empty() )
728 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
730 member->second.setter(c, *Ghost::getRawPtr(g), val);
736 #endif /* SG_NASAL_GHOST_HXX_ */