4 * Created on: Aug 26, 2012
8 #include "Interpreter.h"
10 #include "ParsedSource.h"
11 #include "../battle/Hero.h"
12 #include "../battle/Monster.h"
13 #include "../battle/PartyLayout.h"
14 #include "../battle/Resources.h"
15 #include "../common/Ikari.h"
16 #include "../common/Item.h"
17 #include "../common/Script.h"
18 #include "../common/Spell.h"
19 #include "../common/Stats.h"
20 #include "../common/TargetingMode.h"
21 #include "../graphics/ComplexAnimation.h"
22 #include "../graphics/Font.h"
23 #include "../graphics/Frame.h"
24 #include "../graphics/Gauge.h"
25 #include "../graphics/Menu.h"
26 #include "../graphics/SimpleAnimation.h"
27 #include "../graphics/Sprite.h"
31 #include <SDL_image.h>
34 using battle::Monster;
35 using battle::PartyLayout;
41 using common::TargetingMode;
42 using graphics::Animation;
43 using graphics::Color;
45 using graphics::Frame;
46 using graphics::Gauge;
47 using graphics::ComplexAnimation;
48 using graphics::SimpleAnimation;
49 using graphics::Sprite;
50 using geometry::Vector;
58 Interpreter::~Interpreter() {
59 for (std::map<string, SDL_Surface *>::const_iterator i(imageCache.begin()), end(imageCache.end()); i != end; ++i) {
60 SDL_FreeSurface(i->second);
65 const Interpreter::ParsedDefinition &Interpreter::GetDefinition(const string &identifier) {
66 std::map<string, ParsedDefinition>::const_iterator i(parsedDefinitions.find(identifier));
67 if (i != parsedDefinitions.end()) {
69 } else if (source.IsDefined(identifier)) {
70 ReadDefinition(source.GetDefinition(identifier));
71 return parsedDefinitions.at(identifier);
73 throw Error("access to undefined object " + identifier);
78 void *Interpreter::GetObject(int typeId, const std::string &name) {
79 std::map<string, ParsedDefinition>::const_iterator i(parsedDefinitions.find(name));
80 if (i != parsedDefinitions.end()) {
81 const TypeDescription &requested(TypeDescription::Get(typeId));
82 const TypeDescription &actual(TypeDescription::Get(i->second.type));
83 if (requested.TypeId() == actual.TypeId()) {
84 return values[actual.TypeId()][i->second.id];
85 } else if (actual.IsSubtypeOf(requested)) {
86 char *sub(reinterpret_cast<char *>(values[actual.TypeId()][i->second.id]));
87 std::ptrdiff_t offset(actual.SupertypeOffset(requested));
90 throw Error("cannot cast " + actual.TypeName() + " to " + requested.TypeName());
93 throw Error("access to undefined object " + name);
98 void Interpreter::ReadSource() {
99 for (set<string>::const_iterator i(source.Exports().begin()), end(source.Exports().end()); i != end; ++i) {
100 ReadDefinition(source.GetDefinition(*i));
104 void Interpreter::ReadDefinition(const Definition &dfn) {
105 if (parsedDefinitions.find(dfn.Identifier()) != parsedDefinitions.end()) {
108 if (dfn.HasLiteralValue()) {
115 void Interpreter::ReadLiteral(const Definition &dfn) {
116 const string &typeName(dfn.GetLiteral()->IsArray() ? "Array" : dfn.GetLiteral()->GetTypeName());
117 int typeId(TypeDescription::GetTypeId(typeName));
118 int id(values[typeId].size());
119 const TypeDescription &td(TypeDescription::Get(typeId));
121 (dfn.GetLiteral()->GetType() == Literal::PATH
122 || dfn.GetLiteral()->GetType() == Literal::STRING)
123 ? dfn.GetLiteral()->GetString().size() : td.Size());
124 char *object(alloc.Alloc(size));
125 values[typeId].push_back(object);
126 parsedDefinitions.insert(make_pair(dfn.Identifier(), ParsedDefinition(&dfn, typeId, id)));
127 if (dfn.GetLiteral()->GetType() == Literal::OBJECT) {
128 ReadObject(typeId, id, object, *dfn.GetLiteral()->GetProperties());
130 ReadLiteral(typeId, id, object, *dfn.GetLiteral());
134 void Interpreter::ReadLiteral(int typeId, int id, char *object, const Literal &literal) {
135 switch (literal.GetType()) {
136 case Literal::ARRAY_VALUES:
137 throw Error("named value arrays are not supported, sorry");
139 case Literal::ARRAY_PROPS:
140 throw Error("named property list arrays are not supported, sorry");
142 case Literal::BOOLEAN:
143 new (object) bool(literal.GetBoolean());
146 new (object) Color(literal.GetRed(), literal.GetGreen(), literal.GetBlue(), literal.GetAlpha());
148 case Literal::NUMBER:
149 new (object) int(literal.GetNumber());
152 std::memcpy(object, literal.GetString().c_str(), literal.GetString().size());
153 object[literal.GetString().size()] = '\0';
155 case Literal::SCRIPT:
157 ReadScript(literal.GetScript(), reinterpret_cast<Script *>(object));
159 case Literal::STRING:
160 std::memcpy(object, literal.GetString().c_str(), literal.GetString().size());
161 object[literal.GetString().size()] = '\0';
163 case Literal::VECTOR:
164 new (object) Vector<int>(literal.GetX(), literal.GetY());
166 case Literal::OBJECT:
167 throw Error("illogical branch: read literal object as non-object literal");
172 void *Interpreter::GetObject(int typeId, const Value &v) {
174 if (v.GetLiteral().IsObject()) {
175 int typeId(TypeDescription::GetTypeId(v.GetLiteral().GetTypeName()));
176 const TypeDescription &td(TypeDescription::Get(typeId));
177 char *object(alloc.Alloc(td.Size()));
178 td.Construct(object);
179 int id(values[typeId].size());
180 values[typeId].push_back(object);
181 ReadObject(typeId, id, object, *v.GetLiteral().GetProperties());
184 int typeId(0), id(0);
185 switch (v.GetLiteral().GetType()) {
186 case Literal::ARRAY_VALUES:
187 throw Error("cannot copy value arrays, sorry");
189 case Literal::ARRAY_PROPS:
190 throw Error("cannot copy property list arrays, sorry");
192 case Literal::BOOLEAN:
194 typeId = TypeDescription::GetTypeId("Boolean");
195 id = values[typeId].size();
196 const TypeDescription &td(TypeDescription::Get(typeId));
197 char *object(alloc.Alloc(td.Size()));
198 values[typeId].push_back(new (object) bool(v.GetLiteral().GetBoolean()));
203 typeId = TypeDescription::GetTypeId("Color");
204 id = values[typeId].size();
205 const TypeDescription &td(TypeDescription::Get(typeId));
206 char *object(alloc.Alloc(td.Size()));
207 values[typeId].push_back(new (object) Color(v.GetLiteral().GetRed(), v.GetLiteral().GetGreen(), v.GetLiteral().GetBlue(), v.GetLiteral().GetAlpha()));
210 case Literal::NUMBER:
212 typeId = TypeDescription::GetTypeId("Number");
213 id = values[typeId].size();
214 const TypeDescription &td(TypeDescription::Get(typeId));
215 char *object(alloc.Alloc(td.Size()));
216 values[typeId].push_back(new (object) int(v.GetLiteral().GetNumber()));
221 typeId = TypeDescription::GetTypeId("Path");
222 id = values[typeId].size();
223 char *str(alloc.Alloc(v.GetLiteral().GetString().size() + 1));
224 std::memcpy(str, v.GetLiteral().GetString().c_str(), v.GetLiteral().GetString().size());
225 str[v.GetLiteral().GetString().size()] = '\0';
226 values[typeId].push_back(str);
229 case Literal::SCRIPT:
231 typeId = TypeDescription::GetTypeId("Script");
232 char *script(ReadScript(v.GetLiteral().GetScript()));
233 id = values[typeId].size();
234 values[typeId].push_back(script);
237 case Literal::STRING:
239 typeId = TypeDescription::GetTypeId("String");
240 id = values[typeId].size();
241 char *str(alloc.Alloc(v.GetLiteral().GetString().size() + 1));
242 std::memcpy(str, v.GetLiteral().GetString().c_str(), v.GetLiteral().GetString().size());
243 str[v.GetLiteral().GetString().size()] = '\0';
244 values[typeId].push_back(str);
247 case Literal::VECTOR:
249 typeId = TypeDescription::GetTypeId("Vector");
250 id = values[typeId].size();
251 const TypeDescription &td(TypeDescription::Get(typeId));
252 char *object(alloc.Alloc(td.Size()));
253 values[typeId].push_back(new (object) Vector<int>(v.GetLiteral().GetX(), v.GetLiteral().GetY()));
256 case Literal::OBJECT:
258 typeId = TypeDescription::GetTypeId(v.GetLiteral().GetTypeName());
259 const TypeDescription &td(TypeDescription::Get(typeId));
260 id = values[typeId].size();
261 char *object(alloc.Alloc(td.Size()));
262 td.Construct(object);
263 ReadObject(typeId, id, object, *v.GetLiteral().GetProperties());
267 return values[typeId][id];
270 ReadDefinition(source.GetDefinition(v.GetIdentifier()));
271 return GetObject(typeId, v.GetIdentifier());
276 void Interpreter::ReadObject(const Definition &dfn) {
277 int typeId(TypeDescription::GetTypeId(dfn.TypeName()));
278 const TypeDescription &td(TypeDescription::Get(typeId));
279 int id(values[typeId].size());
280 char *object(alloc.Alloc(td.Size()));
281 td.Construct(object);
282 values[typeId].push_back(object);
283 parsedDefinitions.insert(make_pair(dfn.Identifier(), ParsedDefinition(&dfn, typeId, id)));
284 ReadObject(typeId, id, object, *dfn.GetProperties());
288 void Interpreter::ReadObject(int typeId, int id, char *object, const PropertyList &props) {
289 const TypeDescription &td(TypeDescription::Get(typeId));
290 for (PropertyList::ConstIterator i(props.Begin()), end(props.End()); i != end; ++i) {
291 const FieldDescription &fd(td.GetField(i->first));
292 const TypeDescription &fieldType(TypeDescription::Get(fd.TypeId()));
293 if (CanLink(*i->second)) {
294 char *dest(object + fd.Offset());
295 if (fd.IsAggregate()) {
296 int arraySize(i->second->GetLiteral().ArraySize());
297 char *aggregate(alloc.Alloc(fieldType.Size() * arraySize));
298 char *iter(aggregate);
299 if (i->second->GetLiteral().GetType() == Literal::ARRAY_PROPS) {
300 const vector<PropertyList *> &list(i->second->GetLiteral().GetPropertyLists());
301 for (vector<PropertyList *>::const_iterator j(list.begin()), end(list.end()); j != end; ++j, iter += fieldType.Size()) {
302 fieldType.Construct(iter);
303 ReadObject(fieldType.TypeId(), -1, iter, **j);
306 const vector<Value *> &list(i->second->GetLiteral().GetValues());
307 for (vector<Value *>::const_iterator j(list.begin()), end(list.end()); j != end; ++j, iter += fieldType.Size()) {
308 fieldType.Construct(iter);
309 ReadLiteral(fieldType.TypeId(), -1, iter, (*j)->GetLiteral());
312 if (fd.IsReferenced()) {
313 std::memcpy(dest, &aggregate, sizeof(char *));
314 dest += sizeof(char *);
315 std::memcpy(dest, &arraySize, sizeof(int));
317 throw Error("aggregate type fields must be referenced");
319 } else if (i->second->IsLiteral() && !fd.IsReferenced()) {
321 if (i->second->GetLiteral().IsObject()) {
322 ReadObject(fd.TypeId(), -1, dest, *i->second->GetLiteral().GetProperties());
324 ReadLiteral(fd.TypeId(), -1, dest, i->second->GetLiteral());
327 char *src(reinterpret_cast<char *>(GetObject(fd.TypeId(), *i->second)));
328 if (fd.TypeId() == TypeDescription::GetTypeId("Image")) {
329 src = reinterpret_cast<char *>(GetImage(src));
331 if (fd.IsReferenced()) {
332 std::memcpy(dest, &src, sizeof(char *));
334 std::memcpy(dest, src, fieldType.Size());
338 Postpone(typeId, id, fd.Offset(), i->second->GetIdentifier(), fd.TypeId(), !fd.IsReferenced());
345 void Interpreter::ReadScript(const std::vector<ScriptToken *> &s, Script *script) {
347 for (vector<ScriptToken *>::const_iterator i(s.begin()), end(s.end()); i != end; ++i) {
348 if ((*i)->GetType() != ScriptToken::COMMAND) {
349 throw Error("unexpected script token");
352 const string &cmd((*i)->CommandName());
356 throw Error("unexpected script end after move");
358 const string ®((*i)->RegisterName());
361 size += sizeof(void *);
367 size += sizeof(Vector<int>);
370 throw Error("unknown register " + reg);
374 throw Error("unexpected script end after move");
376 } else if (cmd == "add") {
379 throw Error("unexpected script end after add");
381 const string ®((*i)->RegisterName());
387 size += sizeof(Vector<int>);
390 throw Error("expected register after add " + reg);
394 throw Error("unexpected script end after add");
396 } else if (cmd == "mod") {
399 throw Error("unexpected script end after mod");
404 throw Error("unexpected script end after mod");
406 } else if (cmd == "rand") {
409 throw Error("unexpected script end after rand");
414 throw Error("unexpected script end after rand");
416 } else if (cmd == "sysc") {
419 throw Error("unknown command " + cmd);
423 unsigned char *text(reinterpret_cast<unsigned char *>(alloc.Alloc(size)));
425 for (vector<ScriptToken *>::const_iterator i(s.begin()), end(s.end()); i != end; ++i) {
426 if ((*i)->GetType() != ScriptToken::COMMAND) {
427 throw Error("unexpected script token");
429 const string &cmd((*i)->CommandName());
432 const string ®((*i)->RegisterName());
435 text[cursor] = Script::CODE_MOVE_A0;
437 ReadScriptAddress(**i, text + cursor);
438 cursor += sizeof(void *);
439 } else if (reg == "a1") {
440 text[cursor] = Script::CODE_MOVE_A1;
442 ReadScriptAddress(**i, text + cursor);
443 cursor += sizeof(void *);
444 } else if (reg == "i0") {
445 text[cursor] = Script::CODE_MOVE_I0;
447 ReadScriptInteger(**i, text + cursor);
448 cursor += sizeof(int);
449 } else if (reg == "i1") {
450 text[cursor] = Script::CODE_MOVE_I1;
452 ReadScriptInteger(**i, text + cursor);
453 cursor += sizeof(int);
454 } else if (reg == "v0") {
455 text[cursor] = Script::CODE_MOVE_V0;
457 ReadScriptVector(**i, text + cursor);
458 cursor += sizeof(Vector<int>);
459 } else if (reg == "v1") {
460 text[cursor] = Script::CODE_MOVE_V1;
462 ReadScriptVector(**i, text + cursor);
463 cursor += sizeof(Vector<int>);
465 throw Error("unknown register " + reg);
467 } else if (cmd == "add") {
469 const string ®((*i)->RegisterName());
472 text[cursor] = Script::CODE_ADD_I0;
474 ReadScriptInteger(**i, text + cursor);
475 cursor += sizeof(int);
476 } else if (reg == "i1") {
477 text[cursor] = Script::CODE_ADD_I1;
479 ReadScriptInteger(**i, text + cursor);
480 cursor += sizeof(int);
481 } else if (reg == "v0") {
482 text[cursor] = Script::CODE_ADD_V0;
484 ReadScriptVector(**i, text + cursor);
485 cursor += sizeof(Vector<int>);
486 } else if (reg == "v1") {
487 text[cursor] = Script::CODE_ADD_V1;
489 ReadScriptVector(**i, text + cursor);
490 cursor += sizeof(Vector<int>);
492 throw Error("unexpected register " + reg);
494 } else if (cmd == "mod") {
496 const string ®((*i)->RegisterName());
499 text[cursor] = Script::CODE_MOD_I0;
501 ReadScriptInteger(**i, text + cursor);
502 cursor += sizeof(int);
503 } else if (reg == "i1") {
504 text[cursor] = Script::CODE_MOD_I1;
506 ReadScriptInteger(**i, text + cursor);
507 cursor += sizeof(int);
509 throw Error("unexpected register " + reg);
511 } else if (cmd == "rand") {
513 const string ®((*i)->RegisterName());
515 text[cursor] = Script::CODE_RAND_I0;
517 } else if (reg == "i1") {
518 text[cursor] = Script::CODE_RAND_I1;
521 throw Error("unexpected register " + reg);
523 } else if (cmd == "sysc") {
524 text[cursor] = Script::CODE_SYSCALL;
527 throw Error("unknown command " + cmd);
532 script->textlen = size;
535 char *Interpreter::ReadScript(const vector<ScriptToken *> &s) {
536 char *mem(alloc.Alloc(sizeof(Script)));
538 Script *script(reinterpret_cast<Script *>(mem));
539 ReadScript(s, script);
543 void Interpreter::ReadScriptAddress(const ScriptToken &t, unsigned char *dest) {
544 if (t.GetType() != ScriptToken::IDENTIFIER) {
545 throw Error("expected identifier for address");
547 if (source.IsDefined(t.GetIdentifier())) {
548 const ParsedDefinition &def(GetDefinition(t.GetIdentifier()));
549 void *addr(GetObject(def.type, t.GetIdentifier()));
550 *reinterpret_cast<void **>(dest) = addr;
552 throw Error("postponing values in scripts not implemented");
556 void Interpreter::ReadScriptInteger(const ScriptToken &t, unsigned char *dest) {
557 if (t.GetType() == ScriptToken::IDENTIFIER) {
558 if (source.IsDefined(t.GetIdentifier())) {
559 void *num(GetObject(TypeDescription::GetTypeId("Number"), t.GetIdentifier()));
560 *reinterpret_cast<int *>(dest) = *reinterpret_cast<int *>(num);
562 throw Error("postponing values in scripts not implemented");
564 } else if (t.GetType() == ScriptToken::LITERAL) {
565 *reinterpret_cast<int *>(dest) = t.GetLiteral()->GetNumber();
567 throw Error("expected identifier or integer literal");
571 void Interpreter::ReadScriptVector(const ScriptToken &t, unsigned char *dest) {
572 if (t.GetType() == ScriptToken::IDENTIFIER) {
573 if (source.IsDefined(t.GetIdentifier())) {
574 void *vec(GetObject(TypeDescription::GetTypeId("Vector"), t.GetIdentifier()));
575 *reinterpret_cast<Vector<int> *>(dest) = *reinterpret_cast<Vector<int> *>(vec);
577 throw Error("postponing values in scripts not implemented");
579 } else if (t.GetType() == ScriptToken::LITERAL) {
580 *reinterpret_cast<Vector<int> *>(dest) = Vector<int>(t.GetLiteral()->GetX(), t.GetLiteral()->GetY());
582 throw Error("expected identifier or vector literal");
587 SDL_Surface *Interpreter::GetImage(const string &path) {
588 std::map<string, SDL_Surface *>::const_iterator result(imageCache.find(path));
589 if (result != imageCache.end()) {
590 return result->second;
592 SDL_Surface *image(IMG_Load(path.c_str()));
593 imageCache.insert(make_pair(path, image));
599 bool Interpreter::CanLink(const Value &v) const {
600 return v.IsLiteral() || source.IsDefined(v.GetIdentifier());
603 void Interpreter::Postpone(int type, int id, std::ptrdiff_t offset, const std::string &identifier, int linkedType, bool inlined) {
604 char *str(alloc.Alloc(identifier.size() + 1));
605 std::memcpy(str, identifier.c_str(), identifier.size());
606 str[identifier.size()] = '\0';
607 postponedDefinitions.push_back(PostponedDefinition(type, id, offset, str, linkedType, inlined));
611 void Interpreter::CreateTypeDescriptions() {
613 TypeDescription &td(TypeDescription::CreateOrGet("Boolean"));
614 td.SetDescription("Logical value which can be either true or false.");
615 td.SetSize(sizeof(bool));
618 TypeDescription &td(TypeDescription::CreateOrGet("Color"));
620 "A color in RGB format with an optional alpha channel.\n"
621 "Components range from 0 to 255.\n"
622 "Alpha defaults to 255 if omitted.");
623 td.SetSize(sizeof(Color));
626 TypeDescription &td(TypeDescription::CreateOrGet("Image"));
627 td.SetDescription("Path to a PNG file with image data.");
628 td.SetSize(sizeof(SDL_Surface));
631 TypeDescription &td(TypeDescription::CreateOrGet("Number"));
632 td.SetDescription("A signed integer.");
633 td.SetSize(sizeof(int));
636 int stringId(TypeDescription::GetTypeId("String"));
637 TypeDescription &td(TypeDescription::CreateOrGet("Path"));
638 td.SetDescription("A path in the filesystem which is interpreted relative to the source file's location.");
640 td.AddSupertype(stringId, 0);
643 TypeDescription &td(TypeDescription::CreateOrGet("Script"));
644 td.SetDescription("Collection of commands that define a behaviour.");
645 td.SetSize(sizeof(Script));
648 TypeDescription &td(TypeDescription::CreateOrGet("String"));
649 td.SetDescription("Some characters.");
653 TypeDescription &td(TypeDescription::CreateOrGet("Vector"));
654 td.SetDescription("A pair of numbers usually describing a 2D translation or offset.");
655 td.SetSize(sizeof(Vector<int>));