]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.hxx
Nasal: expose SGCondition using nasal::Ghost and improved error checking.
[flightgear.git] / src / Scripting / NasalSys.hxx
1 #ifndef __NASALSYS_HXX
2 #define __NASALSYS_HXX
3
4 #include <simgear/math/SGMath.hxx> // keep before any cppbind include to enable
5                                    // SGVec2<T> conversion.
6 #include <simgear/misc/sg_dir.hxx>
7 #include <simgear/misc/sg_path.hxx>
8 #include <simgear/nasal/cppbind/NasalHash.hxx>
9 #include <simgear/nasal/nasal.h>
10 #include <simgear/props/props.hxx>
11 #include <simgear/structure/subsystem_mgr.hxx>
12 #include <simgear/threads/SGQueue.hxx>
13
14 // Required only for MSVC
15 #ifdef _MSC_VER
16 #   include <Scripting/NasalModelData.hxx>
17 #endif
18
19 #include <map>
20
21
22 class FGNasalScript;
23 class FGNasalListener;
24 class SGCondition;
25 class FGNasalModelData;
26 class NasalCommand;
27 class FGNasalModuleListener;
28
29 namespace simgear { class BufferedLogCallback; }
30
31 SGPropertyNode* ghostToPropNode(naRef ref);
32
33 class FGNasalSys : public SGSubsystem
34 {
35 public:
36     FGNasalSys();
37     virtual ~FGNasalSys();
38     virtual void init();
39     virtual void shutdown();
40     
41     virtual void update(double dt);
42
43     // Loads a nasal script from an external file and inserts it as a
44     // global module of the specified name.
45     bool loadModule(SGPath file, const char* moduleName);
46
47     // Simple hook to run arbitrary source code.  Returns a bool to
48     // indicate successful execution.  Does *not* return any Nasal
49     // values, because handling garbage-collected objects from C space
50     // is deep voodoo and violates the "simple hook" idea.
51     bool parseAndRun(const char* sourceCode);
52
53     // Slightly more complicated hook to get a handle to a precompiled
54     // Nasal script that can be invoked via a call() method.  The
55     // caller is expected to delete the FGNasalScript returned from
56     // this function.  The "name" argument specifies the "file name"
57     // for the source code that will be printed in Nasal stack traces
58     // on error.
59  //   FGNasalScript* parseScript(const char* src, const char* name=0);
60
61     // Implementation of the settimer extension function
62     void setTimer(naContext c, int argc, naRef* args);
63
64     // Implementation of the setlistener extension function
65     naRef setListener(naContext c, int argc, naRef* args);
66     naRef removeListener(naContext c, int argc, naRef* args);
67
68     // Returns a ghost wrapper for the current _cmdArg
69     naRef cmdArgGhost();
70
71     void setCmdArg(SGPropertyNode* aNode);
72     
73     /**
74      * create Nasal props.Node for an SGPropertyNode*
75      * This is the actual ghost, wrapped in a Nasal sugar class.
76      */
77     naRef wrappedPropsNode(SGPropertyNode* aProps);
78     
79     // Callbacks for command and timer bindings
80     virtual bool handleCommand( const char* moduleName,
81                                 const char* fileName,
82                                 const char* src,
83                                 const SGPropertyNode* arg = 0 );
84     virtual bool handleCommand(const SGPropertyNode* arg);
85
86     bool createModule(const char* moduleName, const char* fileName,
87                       const char* src, int len, const SGPropertyNode* cmdarg=0,
88                       int argc=0, naRef*args=0);
89
90     void deleteModule(const char* moduleName);
91
92     void addCommand(naRef func, const std::string& name);
93     void removeCommand(const std::string& name);
94     
95     /**
96      * Set member of specified hash to given value
97      */
98     void hashset(naRef hash, const char* key, naRef val);
99
100     /**
101      * Set member of globals hash to given value
102      */
103     void globalsSet(const char* key, naRef val);
104
105     naRef call(naRef code, int argc, naRef* args, naRef locals);
106     naRef callWithContext(naContext ctx, naRef code, int argc, naRef* args, naRef locals);
107   
108     naRef callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals);
109     naRef callMethodWithContext(naContext ctx, naRef code, naRef self, int argc, naRef* args, naRef locals);
110   
111     naRef propNodeGhost(SGPropertyNode* handle);
112   
113     void registerToLoad(FGNasalModelData* data);
114     void registerToUnload(FGNasalModelData* data);
115
116     // can't call this 'globals' due to naming clash
117     naRef nasalGlobals() const
118     { return _globals; }
119
120     nasal::Hash getGlobals() const
121     { return nasal::Hash(_globals, _context); }
122   
123     // This mechanism is here to allow naRefs to be passed to
124     // locations "outside" the interpreter.  Normally, such a
125     // reference would be garbage collected unexpectedly.  By passing
126     // it to gcSave and getting a key/handle, it can be cached in a
127     // globals.__gcsave hash.  Be sure to release it with gcRelease
128     // when done.
129     int gcSave(naRef r);
130     void gcRelease(int key);
131     
132     /// retrive the associated log object, for displaying log
133     /// output somewhere (a UI, presumably)
134     simgear::BufferedLogCallback* log() const
135     { return _log; }
136 private:
137     //friend class FGNasalScript;
138     friend class FGNasalListener;
139     friend class FGNasalModuleListener;
140
141     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _loadList;
142     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _unloadList;
143
144     // Delay removing items of the _loadList to ensure the are already attached
145     // to the scene graph (eg. enables to retrieve world position in load
146     // callback).
147     bool _delay_load;
148
149     //
150     // FGTimer subclass for handling Nasal timer callbacks.
151     // See the implementation of the settimer() extension function for
152     // more notes.
153     //
154     struct NasalTimer {
155         virtual void timerExpired();
156         virtual ~NasalTimer() {}
157         naRef handler;
158         int gcKey;
159         FGNasalSys* nasal;
160     };
161
162     // Listener
163     std::map<int, FGNasalListener *> _listener;
164     std::vector<FGNasalListener *> _dead_listener;
165     
166     std::vector<FGNasalModuleListener*> _moduleListeners;
167     
168     static int _listenerId;
169
170     void loadPropertyScripts();
171     void loadPropertyScripts(SGPropertyNode* n);
172     void loadScriptDirectory(simgear::Dir nasalDir);
173     void addModule(std::string moduleName, simgear::PathList scripts);
174     static void logError(naContext);
175     naRef parse(naContext ctx, const char* filename, const char* buf, int len);
176     naRef genPropsModule();
177
178     bool _inited;
179     naContext _context;
180     naRef _globals,
181           _string;
182
183     SGPropertyNode_ptr _cmdArg;
184
185     simgear::BufferedLogCallback* _log;
186     
187     typedef std::map<std::string, NasalCommand*> NasalCommandDict;
188     NasalCommandDict _commands;
189     
190     naRef _wrappedNodeFunc;
191 public:
192     void handleTimer(NasalTimer* t);
193 };
194
195 #if 0
196 class FGNasalScript {
197 public:
198     ~FGNasalScript() { _nas->gcRelease(_gcKey); }
199
200     bool call() {
201         naRef n = naNil();
202         naCall(_nas->_context, _code, 0, &n, naNil(), naNil());
203         return naGetError(_nas->_context) == 0;
204     }
205     
206     FGNasalSys* sys() const { return _nas; }
207 private:
208     friend class FGNasalSys;
209     naRef _code;
210     int _gcKey;
211     FGNasalSys* _nas;
212 };
213 #endif
214
215 #endif // __NASALSYS_HXX