more smaller fixes
[supertux.git] / src / scripting / script_interpreter.hpp
1 #ifndef __SCRIPT_INTERPRETER_H__
2 #define __SCRIPT_INTERPRETER_H__
3
4 #include <squirrel.h>
5 #include <iostream>
6 #include <sstream>
7 #include <string>
8 #include "timer.hpp"
9 #include "game_object.hpp"
10 #include "scripting/wrapper.hpp"
11 #include "scripting/wrapper_util.hpp"
12 #include "scripting/sound.hpp"
13 #include "scripting/level.hpp"
14 #include "scripting/squirrel_error.hpp"
15 #include "scripting/camera.hpp"
16
17 class Sector;
18
19 class ScriptInterpreter : public GameObject
20 {
21 public:
22   ScriptInterpreter(const std::string& working_dir);
23   ~ScriptInterpreter();
24
25   void register_sector(Sector* sector);
26
27   void draw(DrawingContext& );
28   void update(float );
29
30   void run_script(std::istream& in, const std::string& sourcename = "",
31           bool remove_when_terminated = true);
32
33   template<typename T>
34   void expose_object(T* object, const std::string& name, bool free = false)
35   {
36     sq_pushroottable(v);
37     sq_pushstring(v, name.c_str(), -1);
38
39     sq_pushroottable(v);
40     Scripting::create_squirrel_instance(v, object, free);
41     sq_remove(v, -2);
42                         
43     // register instance in root table
44     if(sq_createslot(v, -3) < 0) {
45       std::ostringstream msg;
46       msg << "Couldn't register object '" << name << "' in squirrel root table";
47       throw Scripting::SquirrelError(v, msg.str());
48     }
49     
50     sq_pop(v, 1);
51   }
52
53   void set_wakeup_time(float seconds);
54
55   /** helper function that parses a script, starts it and adds it to the sector
56    * specified
57    */
58   static void add_script_object(Sector* sector, const std::string& scriptname,
59       const std::string& script);
60
61   static ScriptInterpreter* current()
62   {
63     return _current;
64   }
65
66   const std::string& get_working_directory() const
67   {
68       return working_directory;
69   }
70
71 private:
72   HSQUIRRELVM v;
73   static ScriptInterpreter* _current;
74   Timer wakeup_timer;
75
76   /// this directory is used as base for all filenames used in scripts
77   std::string working_directory;
78   Scripting::Sound* sound;
79   Scripting::Level* level;
80   Scripting::Camera* camera;
81 };
82
83 #endif
84