summary refs log tree commit diff stats
path: root/src/script_system.cpp
blob: 505957bd2467bdaf4f5ab62731d6e28f38c6c211 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#include "script_system.h"
#include <iostream>
#include "game.h"
#include "message_system.h"
#include "animation_system.h"
#include "character_system.h"
#include "transform_system.h"
#include "effect_system.h"
#include "camera_system.h"
#include "behaviour_system.h"
#include "vector.h"

ScriptSystem::ScriptSystem(Game& game) : game_(game) {
  engine_.open_libraries(
    sol::lib::base,
    sol::lib::coroutine,
    sol::lib::math);

  engine_.new_usertype<vec2i>(
    "vec2i",
    sol::constructors<vec2i(int, int)>(),
    "x", [] (const vec2i& v) { return v.x(); },
    "y", [] (const vec2i& v) { return v.y(); });

  engine_.new_usertype<Zone>(
    "zone",
    "ul", &Zone::ul,
    "dr", &Zone::dr);

  engine_.new_usertype<SpriteFrame>(
    "spriteframe",
    "center", &SpriteFrame::center,
    "size", &SpriteFrame::size);

  engine_.new_usertype<Sprite>(
    "sprite",
    "alias", &Sprite::alias,
    "loc", &Sprite::loc,
    "dir", &Sprite::dir,
    "followers", &Sprite::followers,
    "characterState", &Sprite::characterState,
    "controllable", &Sprite::controllable,
    "animFinished", &Sprite::animFinished,
    "getCurrentFrame", [] (const Sprite& sprite) -> const SpriteFrame& {
      return sprite.frames[sprite.animations[sprite.animationId].frameIndices[sprite.animationFrame]];
    },
    "persistent", &Sprite::persistent,
    "paused", &Sprite::paused,
    "clipping", &Sprite::clipping,
    "cantCrouch", &Sprite::cantCrouch,
    "bobsWhenNormal", &Sprite::bobsWhenNormal,
    "animSlowdown", &Sprite::animSlowdown,
    "enclosureZone", &Sprite::enclosureZone,
    "movementSpeed", &Sprite::movementSpeed,
    "solid", &Sprite::solid,
    "behaviourType", &Sprite::behaviourType,
    "followSpriteId", &Sprite::followSpriteId);

  engine_.new_usertype<MessageSystem>(
    "message",
    "displayMessage", &MessageSystem::displayMessage,
    "showChoice", &MessageSystem::showChoice,
    "displayCutsceneBars", &MessageSystem::displayCutsceneBars,
    "hideCutsceneBars", &MessageSystem::hideCutsceneBars,
    "isMessageActive", sol::property(&MessageSystem::isMessageActive),
    "getChoiceSelection", &MessageSystem::getChoiceSelection);

  engine_.new_usertype<AnimationSystem>(
    "animation",
    "initSprite", &AnimationSystem::initSprite,
    "setSpriteAnimation", &AnimationSystem::setSpriteAnimation,
    "setSpriteDirection", &AnimationSystem::setSpriteDirection);

  engine_.new_usertype<CharacterSystem>(
    "character",
    "addSpriteToParty", &CharacterSystem::addSpriteToParty,
    "transplantParty", &CharacterSystem::transplantParty,
    "breakUpParty", &CharacterSystem::breakUpParty,
    "moveInDirection", &CharacterSystem::moveInDirection,
    "stopDirecting", &CharacterSystem::stopDirecting,
    "startRunning", &CharacterSystem::startRunning,
    "halt", &CharacterSystem::halt);

  engine_.new_usertype<TransformSystem>(
    "transform",
    "initSprite", [] (TransformSystem& transform, int spriteId, int x, int y, SpriteLayer layer) {
      transform.initSprite(spriteId, vec2i{x, y}, layer);
    },
    "undoCollision", &TransformSystem::undoCollision,
    "moveSprite", &TransformSystem::moveSprite);

  engine_.new_usertype<EffectSystem>(
    "effect",
    "fadeScreen", &EffectSystem::fadeScreen,
    "isScreenFadeComplete", &EffectSystem::isScreenFadeComplete,
    "fadeMap", &EffectSystem::fadeMap,
    "isMapFadeComplete", &EffectSystem::isMapFadeComplete,
    "shakeCamera", &EffectSystem::shakeCamera,
    "stopShakingCamera", &EffectSystem::stopShakingCamera,
    "circleTransition", &EffectSystem::circleTransition,
    "isCircleTransitionComplete", &EffectSystem::isCircleTransitionComplete);

  engine_.new_usertype<CameraSystem>(
    "camera",
    "panToSprite", &CameraSystem::panToSprite,
    "isPanning", &CameraSystem::isPanning,
    "unlockCamera", &CameraSystem::unlockCamera,
    "setFollowingSprite", &CameraSystem::setFollowingSprite);

  engine_.new_usertype<BehaviourSystem>(
    "behaviour",
    "directSpriteToLocation", &BehaviourSystem::directSpriteToLocation,
    "isFollowingPath", &BehaviourSystem::isFollowingPath);

  engine_.new_usertype<Mixer>(
    "mixer",
    "playSound", &Mixer::playSound,
    "loopSound", &Mixer::loopSound,
    "stopChannel", &Mixer::stopChannel,
    "playMusic", &Mixer::playMusic,
    "fadeoutMusic", &Mixer::fadeoutMusic,
    "isPlayingMusic", &Mixer::isPlayingMusic,
    "getPlayingTrack", &Mixer::getPlayingTrack);

  engine_.new_usertype<Map>(
    "map",
    "getName", &Map::getName,
    "getWarpPoint", &Map::getWarpPoint,
    "hasMusic", &Map::hasMusic,
    "getMusic", &Map::getMusic,
    "getZone", &Map::getZone);

  engine_.set_function(
    "message",
    [&] () -> MessageSystem& {
      return game_.getSystem<MessageSystem>();
    });

  engine_.set_function(
    "animation",
    [&] () -> AnimationSystem& {
      return game_.getSystem<AnimationSystem>();
    });

  engine_.set_function(
    "character",
    [&] () -> CharacterSystem& {
      return game_.getSystem<CharacterSystem>();
    });

  engine_.set_function(
    "transform",
    [&] () -> TransformSystem& {
      return game_.getSystem<TransformSystem>();
    });

  engine_.set_function(
    "effect",
    [&] () -> EffectSystem& {
      return game_.getSystem<EffectSystem>();
    });

  engine_.set_function(
    "camera",
    [&] () -> CameraSystem& {
      return game_.getSystem<CameraSystem>();
    });

  engine_.set_function(
    "behaviour",
    [&] () -> BehaviourSystem& {
      return game_.getSystem<BehaviourSystem>();
    });

  engine_.set_function(
    "mixer",
    [&] () -> Mixer& {
      return game_.getMixer();
    });

  engine_.set_function(
    "emplaceSprite",
    [&] (std::string alias) -> int {
      return game_.emplaceSprite(alias);
    });

  engine_.set_function(
    "destroySprite",
    [&] (int spriteId) {
      game_.destroySprite(spriteId);
    });

  engine_.set_function(
    "getSpriteByAlias",
    [&] (std::string alias) -> int {
      return game_.getSpriteByAlias(alias);
    });

  engine_.set_function(
    "getPlayerSprite",
    [&] () -> int {
      for (int id : game_.getSprites()) {
        Sprite& sprite = game_.getSprite(id);
        if (sprite.player) {
          return id;
        }
      }
      return -1;
    });

  engine_.set_function(
    "getSprite",
    [&] (int id) -> Sprite& {
      return game_.getSprite(id);
    });

  engine_.set_function(
    "getAllSprites",
    [&] () -> const std::set<int>& {
      return game_.getSprites();
    });

  engine_.set_function(
    "loadMap",
    [&] (std::string filename) {
      game_.loadMap(filename);
    });

  engine_.set_function(
    "getMap",
    [&] () -> const Map& {
      return game_.getMap();
    });

  engine_.set_function(
    "randomChance",
    [&] (double p) {
      return std::bernoulli_distribution(p)(game_.getRng());
    });

  engine_.set_function(
    "loadMapScripts",
    [&] (std::string filename) {
      loadMapScripts(filename);
    });

  engine_.set_function("directionFacingPoint", &directionFacingPoint);
  engine_.set_function("cardinalDirectionFacingPoint", &cardinalDirectionFacingPoint);

  engine_.script_file("../res/scripts/common.lua");
}

void ScriptSystem::tick(double dt) {
  if (game_.isGameplayPaused()) return;

  for (Script& script : scripts_) {
    auto result = (*script.callable)(dt);
    if (!result.valid()) {
      sol::error e = result;
      throw e;
    }
  }

  scripts_.remove_if([] (const Script& script) {
    return (!*script.callable);
  });
}

void ScriptSystem::loadMapScripts(std::string mapName) {
  if (!loadedScripts_.count(mapName)) {
    engine_.script_file("../res/scripts/" + mapName + ".lua");
    loadedScripts_.insert(mapName);
  }
}

bool ScriptSystem::mapHasScript(std::string mapName, std::string scriptName) {
  loadMapScripts(mapName);

  return !!engine_.traverse_get<sol::function>(mapName, scriptName);
}

void ScriptSystem::runScript(std::string mapName, std::string scriptName) {
  loadMapScripts(mapName);

  Script newScript;
  newScript.runner.reset(new sol::thread(sol::thread::create(engine_.lua_state())));
  newScript.callable.reset(new sol::coroutine(newScript.runner->state().traverse_get<sol::function>(mapName, scriptName)));

  if (!*newScript.callable) {
    throw std::runtime_error("Error running script: " + mapName + "." + scriptName);
  }

  auto result = (*newScript.callable)();
  if (!result.valid()) {
    sol::error e = result;
    throw e;
  }

  if (*newScript.callable) {
    scripts_.push_back(std::move(newScript));
  }
}

void ScriptSystem::runDebugScript(std::string script) {
  Script newScript;
  newScript.runner.reset(new sol::thread(sol::thread::create(engine_.lua_state())));

  sol::load_result loaded_script = newScript.runner->state().load(script);
  if (!loaded_script.valid()) {
    std::cout << "Error running debug command: " << script << std::endl;
    return;
  }

  newScript.callable.reset(new sol::coroutine(loaded_script));

  if (!*newScript.callable) {
    std::cout << "Error running debug command: " << script << std::endl;
    return;
  }

  auto result = (*newScript.callable)();
  if (!result.valid()) {
    sol::error e = result;
    std::cout << e.what() << std::endl;
    return;
  }

  if (*newScript.callable) {
    scripts_.push_back(std::move(newScript));
  }
}