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;
88 typedef boost::false_type returns_dynamic_type;
91 * Create a shared pointer on the heap to handle the reference counting for
92 * the passed shared pointer while it is used in Nasal space.
94 static T* createInstance(const T& ptr)
99 static pointer getPtr(void* ptr)
102 return *static_cast<T*>(ptr);
107 static raw_type* getRawPtr(void* ptr)
110 return static_cast<T*>(ptr)->get();
115 static raw_type* getRawPtr(const T& ptr)
122 * Policy for creating ghost instances as raw objects on the heap.
125 struct RawPointerPolicy
127 typedef typename GhostTypeTraits<T>::raw_type raw_type;
128 typedef raw_type* pointer;
129 typedef boost::true_type returns_dynamic_type;
132 * Create a new object instance on the heap
134 static T* createInstance()
139 static pointer getPtr(void* ptr)
141 BOOST_STATIC_ASSERT((boost::is_same<pointer, T*>::value));
142 return static_cast<T*>(ptr);
145 static raw_type* getRawPtr(void* ptr)
147 BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
148 return static_cast<T*>(ptr);
155 * Metadata for Ghost object types
161 * Add a nasal base class to the ghost. Will be available in the ghosts
164 void addNasalBase(const naRef& parent)
166 assert( naIsHash(parent) );
167 _parents.push_back(parent);
170 bool isBaseOf(naGhostType* ghost_type) const
172 if( ghost_type == &_ghost_type )
175 for( DerivedList::const_iterator derived = _derived_classes.begin();
176 derived != _derived_classes.end();
179 if( (*derived)->isBaseOf(ghost_type) )
188 typedef std::vector<const GhostMetadata*> DerivedList;
190 const std::string _name;
191 naGhostType _ghost_type;
192 DerivedList _derived_classes;
193 std::vector<naRef> _parents;
195 explicit GhostMetadata(const std::string& name):
201 void addDerived(const GhostMetadata* derived)
204 _derived_classes.push_back(derived);
210 "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
214 naRef getParents(naContext c)
216 return nasal::to_nasal(c, _parents);
222 * Context passed to a function/method being called from Nasal
226 CallContext(naContext c, int argc, naRef* args):
238 * Class for exposing C++ objects to Nasal
241 * // Example class to be exposed to Nasal
248 * naRef myMember(naContext c, int argc, naRef* args);
251 * void exposeClasses()
253 * // Register a nasal ghost type for MyClass. This needs to be done only
254 * // once before creating the first ghost instance.
255 * Ghost<MyClass>::init("MyClass")
256 * // Members can be exposed by getters and setters
257 * .member("x", &MyClass::getX, &MyClass::setX)
258 * // For readonly variables only pass a getter
259 * .member("x_readonly", &MyClass::getX)
260 * // It is also possible to expose writeonly members
261 * .member("x_writeonly", &MyClass::setX)
262 * // Methods use a slightly different syntax - The pointer to the member
263 * // function has to be passed as template argument
264 * .method<&MyClass::myMember>("myMember");
270 public internal::GhostMetadata,
271 protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
272 SharedPointerPolicy<T>,
273 RawPointerPolicy<T> >::type
276 typedef T value_type;
277 typedef typename GhostTypeTraits<T>::raw_type raw_type;
278 typedef typename Ghost::pointer pointer;
279 typedef naRef (raw_type::*member_func_t)(const CallContext&);
280 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
281 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
282 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
285 * A ghost member. Can consist either of getter and/or setter functions
286 * for exposing a data variable or a single callable function.
294 member_t( const getter_t& getter,
295 const setter_t& setter,
296 naCFunction func = 0 ):
302 member_t(naCFunction func):
311 typedef std::map<std::string, member_t> MemberMap;
314 * Register a new ghost type.
316 * @note Only intialize each ghost type once!
318 * @param name Descriptive name of the ghost type.
320 static Ghost& init(const std::string& name)
322 assert( !getSingletonPtr() );
324 getSingletonHolder().reset( new Ghost(name) );
325 return *getSingletonPtr();
329 * Register a base class for this ghost. The base class needs to be
330 * registers on its own before it can be used as base class.
332 * @tparam BaseGhost Type of base class already wrapped into Ghost class
336 * Ghost<MyBase>::init("MyBase");
337 * Ghost<MyClass>::init("MyClass")
338 * .bases<Ghost<MyBase> >();
341 template<class BaseGhost>
342 typename boost::enable_if_c
343 < boost::is_base_of<GhostMetadata, BaseGhost>::value
344 && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
349 BaseGhost* base = BaseGhost::getSingletonPtr();
353 // Both ways of retrieving the address of a static member function
354 // should be legal but not all compilers know this.
355 // g++-4.4.7+ has been tested to work with both versions
356 #if defined(GCC_VERSION) && GCC_VERSION < 40407
357 // The old version of g++ used on Jenkins (16.11.2012) only compiles
359 &getTypeFor<BaseGhost>
361 // VS (2008, 2010, ... ?) only allow this version.
362 &Ghost::getTypeFor<BaseGhost>
366 // Replace any getter that is not available in the current class.
367 // TODO check if this is the correct behavior of function overriding
368 for( typename BaseGhost::MemberMap::const_iterator member =
369 base->_members.begin();
370 member != base->_members.end();
373 if( _members.find(member->first) == _members.end() )
374 _members[member->first] = member_t
376 member->second.getter,
377 member->second.setter,
386 * Register a base class for this ghost. The base class needs to be
387 * registers on its own before it can be used as base class.
389 * @tparam Base Type of base class (Base as used in Ghost<Base>)
392 * Ghost<MyBase>::init("MyBase");
393 * Ghost<MyClass>::init("MyClass")
398 typename boost::enable_if_c
399 < !boost::is_base_of<GhostMetadata, Base>::value
400 && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
405 return bases< Ghost<Base> >();
409 * Register an existing Nasal class/hash as base class for this ghost.
411 * @param parent Nasal hash/class
413 Ghost& bases(const naRef& parent)
415 addNasalBase(parent);
420 * Register a member variable by passing a getter and/or setter method.
422 * @param field Name of member
423 * @param getter Getter for variable
424 * @param setter Setter for variable (Pass 0 to prevent write access)
428 Ghost& member( const std::string& field,
429 Var (raw_type::*getter)() const,
430 void (raw_type::*setter)(Var) = 0 )
435 naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
437 // Getter signature: naRef(naContext, raw_type&)
438 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
443 Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
445 // Setter signature: void(naContext, raw_type&, naRef)
446 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
449 return member(field, m.getter, m.setter);
453 * Register a write only member variable.
455 * @param field Name of member
456 * @param setter Setter for variable
459 Ghost& member( const std::string& field,
460 void (raw_type::*setter)(Var) )
462 return member<Var>(field, 0, setter);
466 * Register a member variable by passing a getter and/or setter method.
468 * @param field Name of member
469 * @param getter Getter for variable
470 * @param setter Setter for variable (Pass empty to prevent write access)
473 Ghost& member( const std::string& field,
474 const getter_t& getter,
475 const setter_t& setter = setter_t() )
477 if( !getter.empty() || !setter.empty() )
478 _members[field] = member_t(getter, setter);
484 "Member '" << field << "' requires a getter or setter"
490 * Register a member function.
492 * @note Because only function pointers can be registered as Nasal
493 * functions it is needed to pass the function pointer as template
494 * argument. This allows us to create a separate instance of the
495 * MemberFunctionWrapper for each registered function and therefore
496 * provides us with the needed static functions to be passed on to
499 * @tparam func Pointer to member function being registered.
505 * naRef myMethod(naContext c, int argc, naRef* args);
508 * Ghost<MyClass>::init("Test")
509 * .method<&MyClass::myMethod>("myMethod");
512 template<member_func_t func>
513 Ghost& method(const std::string& name)
515 _members[name].func = &MemberFunctionWrapper<func>::call;
520 * Register a free function as member function. The object instance is
521 * passed as additional first argument.
523 * @tparam func Pointer to free function being registered.
525 * @note Due to a severe bug in Visual Studio it is not possible to create
526 * a specialization of #method for free function pointers and
527 * member function pointers at the same time. Do overcome this
528 * limitation we had to use a different name for this function.
532 * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
534 * Ghost<MyClass>::init("Test")
535 * .method_func<&myMethod>("myMethod");
538 template<free_func_t func>
539 Ghost& method_func(const std::string& name)
541 _members[name].func = &FreeFunctionWrapper<func>::call;
545 // TODO use variadic template when supporting C++11
547 * Create a Nasal instance of this ghost.
549 * @param c Active Nasal context
551 static naRef create( naContext c )
553 return makeGhost(c, Ghost::createInstance());
557 * Create a Nasal instance of this ghost.
559 * @param c Active Nasal context
560 * @param a1 Parameter used for creating new instance
563 static naRef create( naContext c, const A1& a1 )
565 return makeGhost(c, Ghost::createInstance(a1));
569 * Nasal callback for creating a new instance of this ghost.
571 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
576 static bool isBaseOf(naGhostType* ghost_type)
581 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
584 static bool isBaseOf(naRef obj)
586 return isBaseOf( naGhost_type(obj) );
590 * Convert Nasal object to C++ object. To get a valid object the passed
591 * Nasal objects has to be derived class of the target class (Either
592 * derived in C++ or in Nasal using a 'parents' vector)
594 static pointer fromNasal(naContext c, naRef me)
596 // Check if it's a ghost and if it can be converted
597 if( isBaseOf( naGhost_type(me) ) )
598 return Ghost::getPtr( naGhost_ptr(me) );
600 // Now if it is derived from a ghost (hash with ghost in parent vector)
601 // TODO handle recursive parents
602 else if( naIsHash(me) )
604 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
605 if( !naIsVector(na_parents) )
607 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
611 typedef std::vector<naRef> naRefs;
612 naRefs parents = from_nasal<naRefs>(c, na_parents);
613 for( naRefs::const_iterator parent = parents.begin();
614 parent != parents.end();
617 if( isBaseOf(naGhost_type(*parent)) )
618 return Ghost::getPtr( naGhost_ptr(*parent) );
630 typedef naGhostType* (*type_checker_t)(const raw_type*);
631 typedef std::vector<type_checker_t> DerivedList;
632 DerivedList _derived_types;
634 void addDerived( const internal::GhostMetadata* derived_meta,
635 const type_checker_t& derived_info )
637 GhostMetadata::addDerived(derived_meta);
638 _derived_types.push_back(derived_info);
641 template<class BaseGhost>
643 typename boost::enable_if
644 < boost::is_polymorphic<typename BaseGhost::raw_type>,
647 getTypeFor(const typename BaseGhost::raw_type* base)
649 // Check first if passed pointer can by converted to instance of class
652 < typename BaseGhost::raw_type,
653 typename Ghost::raw_type
655 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
658 // Now check if we can further downcast to one of our derived classes.
659 for( typename DerivedList::reverse_iterator
660 derived = getSingletonPtr()->_derived_types.rbegin();
661 derived != getSingletonPtr()->_derived_types.rend();
664 naGhostType* ghost_type =
665 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
670 // If base is not an instance of any derived class, this class has to
671 // be the dynamic type.
672 return &getSingletonPtr()->_ghost_type;
675 template<class BaseGhost>
677 typename boost::disable_if
678 < boost::is_polymorphic<typename BaseGhost::raw_type>,
681 getTypeFor(const typename BaseGhost::raw_type* base)
683 // For non polymorphic classes there is no possibility to get the actual
684 // dynamic type, therefore we can only use its static type.
685 return &BaseGhost::getSingletonPtr()->_ghost_type;
688 static Ghost* getSingletonPtr()
690 return getSingletonHolder().get();
693 static raw_type& requireObject(naContext c, naRef me)
695 raw_type* obj = Ghost::getRawPtr( fromNasal(c, me) );
696 naGhostType* ghost_type = naGhost_type(me);
702 "method called on object of wrong type: is '%s' expected '%s'",
703 ghost_type ? ghost_type->name : "unknown",
704 getSingletonPtr()->_ghost_type.name
711 * Wrapper class to enable registering pointers to member functions as
712 * Nasal function callbacks. We need to use the function pointer as
713 * template parameter to ensure every registered function gets a static
714 * function which can be passed to Nasal.
716 template<member_func_t func>
717 struct MemberFunctionWrapper
720 * Called from Nasal upon invocation of the according registered
721 * function. Forwards the call to the passed object instance.
723 static naRef call(naContext c, naRef me, int argc, naRef* args)
725 return (requireObject(c, me).*func)(CallContext(c, argc, args));
730 * Wrapper class to enable registering pointers to free functions (only
731 * external linkage). We need to use the function pointer as template
732 * parameter to ensure every registered function gets a static function
733 * which can be passed to Nasal. Even though we just wrap another simple
734 * function pointer this intermediate step is need to be able to retrieve
735 * the object the function call belongs to and pass it along as argument.
737 template<free_func_t func>
738 struct FreeFunctionWrapper
741 * Called from Nasal upon invocation of the according registered
742 * function. Forwards the call to the passed function pointer and passes
743 * the required parameters.
745 static naRef call(naContext c, naRef me, int argc, naRef* args)
747 return func(requireObject(c, me), CallContext(c, argc, args));
751 typedef std::auto_ptr<Ghost> GhostPtr;
754 explicit Ghost(const std::string& name):
755 GhostMetadata( name )
757 _ghost_type.destroy = &destroyGhost;
758 _ghost_type.name = _name.c_str();
759 _ghost_type.get_member = &getMember;
760 _ghost_type.set_member = &setMember;
763 static GhostPtr& getSingletonHolder()
765 static GhostPtr instance;
769 static naRef makeGhost(naContext c, void *ptr)
771 if( !Ghost::getRawPtr(ptr) )
774 naGhostType* ghost_type = 0;
775 if( Ghost::returns_dynamic_type::value )
776 // For pointer policies already returning instances of an object with
777 // the dynamic type of this Ghost's raw_type the type is always the
779 ghost_type = &getSingletonPtr()->_ghost_type;
781 // If wrapping eg. shared pointers the users passes an already
782 // existing instance of an object which will then be hold be a new
783 // shared pointer. We therefore have to check for the dynamic type
784 // of the object as it might differ from the passed static type.
785 ghost_type = getTypeFor<Ghost>( Ghost::getRawPtr(ptr) );
790 return naNewGhost2(c, ghost_type, ptr);
793 static void destroyGhost(void *ptr)
799 * Callback for retrieving a ghost member.
801 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
803 const std::string key_str = nasal::from_nasal<std::string>(c, key);
804 if( key_str == "parents" )
806 if( getSingletonPtr()->_parents.empty() )
809 *out = getSingletonPtr()->getParents(c);
813 typename MemberMap::iterator member =
814 getSingletonPtr()->_members.find(key_str);
816 if( member == getSingletonPtr()->_members.end() )
819 if( member->second.func )
820 *out = nasal::to_nasal(c, member->second.func);
821 else if( !member->second.getter.empty() )
822 *out = member->second.getter(c, *Ghost::getRawPtr(g));
824 return "Read-protected member";
830 * Callback for writing to a ghost member.
832 static void setMember(naContext c, void* g, naRef field, naRef val)
834 const std::string key = nasal::from_nasal<std::string>(c, field);
835 typename MemberMap::iterator member =
836 getSingletonPtr()->_members.find(key);
838 if( member == getSingletonPtr()->_members.end() )
839 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
840 if( member->second.setter.empty() )
841 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
843 member->second.setter(c, *Ghost::getRawPtr(g), val);
849 #endif /* SG_NASAL_GHOST_HXX_ */