ScummVM API documentation
lingo.h
1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21 
22 #ifndef DIRECTOR_LINGO_LINGO_H
23 #define DIRECTOR_LINGO_LINGO_H
24 
25 namespace Audio {
26 class AudioStream;
27 }
28 namespace Common {
29 class SeekableReadStreamEndian;
30 }
31 
32 namespace Director {
33 
34 struct ChunkReference;
35 struct MenuReference;
36 struct PictureReference;
37 struct TheEntity;
38 struct TheEntityField;
39 struct LingoArchive;
40 struct LingoV4Bytecode;
41 struct LingoV4TheEntity;
42 struct Node;
43 struct Picture;
44 class AbstractObject;
45 class Cast;
46 class ScriptContext;
47 class DirectorEngine;
48 class Frame;
49 class LingoCompiler;
50 struct Breakpoint;
51 
52 typedef void (*inst)(void);
53 #define STOP (inst)0
54 #define ENTITY_INDEX(t,id) ((t) * 100000 + (id))
55 
56 int calcStringAlignment(const char *s);
57 int calcCodeAlignment(int l);
58 
59 typedef Common::Array<inst> ScriptData;
60 
61 struct FuncDesc {
62  Common::String name;
63  const char *proto;
64 
65  FuncDesc(Common::String n, const char *p) { name = n; proto = p; }
66 };
67 
69 
71 
72 struct BuiltinProto {
73  const char *name;
74  void (*func)(int);
75  int minArgs; // -1 -- arglist
76  int maxArgs;
77  int version;
78  SymbolType type;
79 };
80 
81 struct Symbol { /* symbol table entry */
82  Common::String *name;
83  SymbolType type;
84  union {
85  ScriptData *defn; /* HANDLER */
86  void (*func)(); /* OPCODE */
87  void (*bltin)(int); /* BUILTIN */
88  Common::String *s; /* STRING */
89  } u;
90 
91  int *refCount;
92 
93  int nargs; /* number of arguments */
94  int maxArgs; /* maximal number of arguments, for builtins */
95  int targetType; /* valid target objects, for method builtins */
96 
99  ScriptContext *ctx; /* optional script context to execute with */
100  AbstractObject *target; /* optional method target */
101  bool anonymous;
102 
103  Symbol();
104  Symbol(const Symbol &s);
105  Symbol& operator=(const Symbol &s);
106  bool operator==(Symbol &s) const;
107  void reset();
108  ~Symbol();
109 };
110 
111 struct PArray {
112  bool _sorted;
113  PropertyArray arr;
114 
115  PArray() : _sorted(false) {}
116 
117  PArray(int size) : _sorted(false), arr(size) {}
118 };
119 
120 struct FArray {
121  bool _sorted;
122  DatumArray arr;
123 
124  FArray() : _sorted(false) {}
125 
126  FArray(int size) : _sorted(false), arr(size) {}
127 };
128 
129 
130 struct Datum { /* interpreter stack type */
131  DatumType type;
132 
133  union {
134  int i; /* INT, ARGC, ARGCNORET */
135  double f; /* FLOAT */
136  Common::String *s; /* STRING, VARREF, OBJECT */
137  FArray *farr; /* ARRAY, POINT, RECT */
138  PArray *parr; /* PARRAY */
139  AbstractObject *obj; /* OBJECT */
140  ChunkReference *cref; /* CHUNKREF */
141  CastMemberID *cast; /* CASTREF, FIELDREF */
142  MenuReference *menu; /* MENUREF */
143  PictureReference *picture; /* PICTUREREF */
144  } u;
145 
146  int *refCount;
147 
148  bool ignoreGlobal; // True if this Datum should be ignored by showGlobals and clearGlobals
149 
150  Datum();
151  Datum(const Datum &d);
152  Datum& operator=(const Datum &d);
153  Datum(int val);
154  Datum(double val);
155  Datum(const Common::String &val);
156  Datum(AbstractObject *val);
157  Datum(CastMember *val);
158  Datum(const CastMemberID &val);
159  Datum(const Common::Point &point);
160  Datum(const Common::Rect &rect);
161  void reset();
162 
163  ~Datum() {
164  reset();
165  }
166 
167  Datum eval() const;
168  double asFloat() const;
169  int asInt() const;
170  Common::String asString(bool printonly = false) const;
171  CastMemberID asMemberID(CastType castType = kCastTypeAny, int castLib = 0) const;
172  Common::Point asPoint() const;
173  Datum clone() const;
174 
175  bool isRef() const;
176  bool isVarRef() const;
177  bool isCastRef() const;
178  bool isArray() const;
179  bool isNumeric() const;
180  bool isVoid() const { return type == VOID; }
181 
182  const char *type2str(bool ilk = false) const;
183 
184  int equalTo(const Datum &d, bool ignoreCase = false) const;
185  uint32 compareTo(const Datum &d) const;
186 
187  bool operator==(const Datum &d) const;
188  bool operator>(const Datum &d) const;
189  bool operator<(const Datum &d) const;
190  bool operator>=(const Datum &d) const;
191  bool operator<=(const Datum &d) const;
192 };
193 
195  Datum source;
196  ChunkType type;
197  int startChunk;
198  int endChunk;
199  int start;
200  int end;
201 
202  ChunkReference(const Datum &src, ChunkType t, int sc, int ec, int s, int e)
203  : source(src), type(t), startChunk(sc), endChunk(ec), start(s), end(e) {}
204 };
205 
207  int menuIdNum;
208  Common::String *menuIdStr;
209  int menuItemIdNum;
210  Common::String *menuItemIdStr;
211 
212  MenuReference();
213 };
214 
216  Picture *_picture = nullptr;
217  ~PictureReference();
218 };
219 
220 struct PCell {
221  Datum p;
222  Datum v;
223 
224  PCell();
225  PCell(const Datum &prop, const Datum &val);
226 };
227 
228 struct Builtin {
229  void (*func)(void);
230  int nargs;
231 
232  Builtin(void (*func1)(void), int nargs1) : func(func1), nargs(nargs1) {}
233 };
234 
242 typedef void (*XLibOpenerFunc)(ObjectType, const Common::Path &);
243 typedef void (*XLibCloserFunc)(ObjectType);
248 
251 
252 struct CFrame { /* proc/func call stack frame */
253  Symbol sp; /* symbol table entry */
254  int retPC; /* where to resume after return */
255  ScriptData *retScript; /* which script to resume after return */
256  ScriptContext *retContext; /* which script context to use after return */
257  DatumHash *retLocalVars;
258  Datum retMe; /* which me obj to use after return */
259  uint stackSizeBefore;
260  bool allowRetVal; /* whether to allow a return value */
261  Datum defaultRetVal; /* default return value */
262  int paramCount; /* original number of arguments submitted */
263  Common::Array<Datum> paramList; /* original argument list */
264 };
265 
266 struct LingoEvent {
267  LEvent event;
268  int eventId;
269  EventHandlerSourceType eventHandlerSourceType;
270  ScriptType scriptType;
271  bool passByDefault;
272  uint16 channelId;
273  CastMemberID scriptId;
274  Common::Point mousePos;
275  int behaviorIndex;
276  AbstractObject *scriptInstance;
277 
278  LingoEvent(LEvent e, int ei, ScriptType st, bool pass, CastMemberID si = CastMemberID(), Common::Point mp = Common::Point(-1, -1), int bi = -1) {
279  event = e;
280  eventId = ei;
281  eventHandlerSourceType = kNoneHandler;
282  scriptType = st;
283  passByDefault = pass;
284  channelId = 0;
285  scriptId = si;
286  mousePos = mp;
287  behaviorIndex = bi;
288  scriptInstance = nullptr;
289  }
290 
291  LingoEvent(LEvent e, int ei, EventHandlerSourceType ehst, bool pass, Common::Point mp = Common::Point(-1, -1), uint16 ci = 0, int bi = -1) {
292  event = e;
293  eventId = ei;
294  eventHandlerSourceType = ehst;
295  scriptType = kNoneScript;
296  passByDefault = pass;
297  channelId = ci;
298  scriptId = CastMemberID();
299  mousePos = mp;
300  behaviorIndex = bi;
301  scriptInstance = nullptr;
302  }
303 };
304 
305 
306 struct LingoArchive {
307  LingoArchive(Cast *c) : cast(c) {};
308  ~LingoArchive();
309 
310  Cast *cast;
311  ScriptContextHash lctxContexts;
312  ScriptContextHash scriptContexts[kMaxScriptType + 1];
313  FactoryContextHash factoryContexts;
315  Common::HashMap<uint32, Common::String> primaryEventHandlers;
316  SymbolHash functionHandlers;
317 
318  ScriptContext *getScriptContext(ScriptType type, uint16 id);
319  ScriptContext *findScriptContext(uint16 id);
320  Common::String getName(uint16 id);
321  Common::String formatFunctionList(const char *prefix);
322 
323  void addCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
324  void patchCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
325  void removeCode(ScriptType type, uint16 id);
326  void replaceCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr);
327  void addCodeV4(Common::SeekableReadStreamEndian &stream, uint16 lctxIndex, const Common::String &archName, uint16 version);
328  void addNamesV4(Common::SeekableReadStreamEndian &stream);
329 
330  // lingo-patcher.cpp
331  void patchScriptHandler(ScriptType type, CastMemberID id);
332 };
333 
334 struct LingoState {
335  // Execution state for a Lingo process, created every time
336  // a top-level handler is called (e.g. on mouseDown).
337  // Can be swapped out when another script gets called with priority.
338  // Call frames are pushed and popped from the callstack with
339  // pushContext and popContext.
340  Common::Array<CFrame *> callstack; // call stack
341  uint pc = 0; // current program counter
342  ScriptData *script = nullptr; // current Lingo script
343  ScriptContext *context = nullptr; // current Lingo script context
344  DatumHash *localVars = nullptr; // current local variables
345  Datum me; // current me object
346  StackData stack;
347 
348  ~LingoState();
349 };
350 
351 enum LingoExecState {
352  kRunning,
353  kPause,
354 };
355 
356 class Lingo {
357 
358 public:
359  Lingo(DirectorEngine *vm);
360  ~Lingo();
361 
362  void resetLingo();
363  void cleanupLingo();
364  void resetLingoGo();
365 
366  int getMenuNum();
367  int getMenuItemsNum(Datum &d);
368  int getXtrasNum();
369  int getCastLibsNum();
370  int getMembersNum(uint16 castLibID);
371 
372  void executeHandler(const Common::String &name, int numargs = 0);
373  void executeScript(ScriptType type, CastMemberID id);
374  Common::String formatStack();
375  void printStack(const char *s, uint pc);
376  Common::String formatCallStack(uint pc);
377  void printCallStack(uint pc);
378  Common::String formatFrame();
379  Common::String formatCurrentInstruction();
380  Common::String decodeInstruction(ScriptData *sd, uint pc, uint *newPC = NULL);
381  Common::String decodeScript(ScriptData *sd);
382  Common::String formatFunctionName(Symbol &sym);
383  Common::String formatFunctionBody(Symbol &sym);
384 
385  void reloadBuiltIns();
386  void initBuiltIns();
387  void initBuiltIns(const BuiltinProto protos[]);
388  void cleanupBuiltIns();
389  void cleanupBuiltIns(const BuiltinProto protos[]);
390  void initFuncs();
391  void cleanupFuncs();
392  void initBytecode();
393  void initMethods();
394  void cleanupMethods();
395  void initXLibs();
396  void cleanupXLibs();
397 
398  Common::String normalizeXLibName(Common::String name);
399  void openXLib(Common::String name, ObjectType type, const Common::Path &path);
400  void closeXLib(Common::String name);
401  void closeOpenXLibs();
402  void reloadOpenXLibs();
403 
404  void runTests();
405 
406  // lingo-events.cpp
407 private:
408  void initEventHandlerTypes();
409  bool processEvent(LEvent event, ScriptType st, CastMemberID scriptId, int channelId = -1, AbstractObject *obj = nullptr);
410 
411 public:
412  ScriptType event2script(LEvent ev);
413  Symbol getHandler(const Common::String &name);
414 
415  void processEvents(Common::Queue<LingoEvent> &queue, bool isInputEvent);
416 
417 public:
418  bool execute(int targetFrame = -1);
419  void switchStateFromWindow();
420  void freezeState();
421  void freezePlayState();
422  void pushContext(const Symbol funcSym, bool allowRetVal, Datum defaultRetVal, int paramCount, int nargs);
423  void popContext(bool aborting = false);
424  void cleanLocalVars();
425  void varAssign(const Datum &var, const Datum &value);
426  Datum varFetch(const Datum &var, bool silent = false);
427  Common::U32String evalChunkRef(const Datum &var);
428  Datum findVarV4(int varType, const Datum &id);
429  CastMemberID resolveCastMember(const Datum &memberID, const Datum &castLib, CastType type);
430  CastMemberID toCastMemberID(const Datum &member, const Datum &castLib);
431  void exposeXObject(const char *name, Datum obj);
432 
433  int getAlignedType(const Datum &d1, const Datum &d2, bool equality);
434 
435  Common::String formatAllVars();
436  void printAllVars();
437 
438  inst readInst() { return getInst(_state->pc++); }
439  inst getInst(uint pc) { return (*_state->script)[pc]; }
440  int readInt() { return getInt(_state->pc++); }
441  int getInt(uint pc);
442  double readFloat() { double d = getFloat(_state->pc); _state->pc += calcCodeAlignment(sizeof(double)); return d; }
443  double getFloat(uint pc) { return *(double *)(&((*_state->script)[_state->pc])); }
444  char *readString() { char *s = getString(_state->pc); _state->pc += calcStringAlignment(s); return s; }
445  char *getString(uint pc) { return (char *)(&((*_state->script)[_state->pc])); }
446 
447  Datum getVoid();
448  void pushVoid();
449 
450  void printArgs(const char *funcname, int nargs, const char *prefix = nullptr);
451  inline void printSTUBWithArglist(const char *funcname, int nargs) { printArgs(funcname, nargs, "STUB: "); }
452  void convertVOIDtoString(int arg, int nargs);
453  void dropStack(int nargs);
454  void drop(uint num);
455 
456  void lingoError(const char *s, ...);
457 
458  void func_mci(const Common::String &name);
459  void func_mciwait(const Common::String &name);
460  void func_beep(int repeats);
461  void func_goto(Datum &frame, Datum &movie, bool commandgo = false );
462  void func_gotoloop();
463  void func_gotonext();
464  void func_gotoprevious();
465  void func_play(Datum &frame, Datum &movie);
466  void func_playdone();
467  void func_cursor(Datum cursorDatum);
468  int func_marker(int m);
469  uint16 func_label(Datum &label);
470 
471  // lingo-the.cpp
472 public:
473  void initTheEntities();
474  void cleanUpTheEntities();
475  const char *entity2str(int id);
476  const char *field2str(int id);
477 
478  // global kTheEntity
479  Datum _actorList;
480  Common::u32char_type_t _itemDelimiter;
481  bool _exitLock;
482  bool _preLoadEventAbort; // no-op, everything is always preloaded
483  Datum _searchPath;
484  bool _trace; // state of movie's trace function
485  int _traceLoad; // internal Director verbosity level
486  bool _updateMovieEnabled;
487  bool _romanLingo;
488 
489  Datum getTheEntity(int entity, Datum &id, int field);
490  void setTheEntity(int entity, Datum &id, int field, Datum &d);
491  Datum getTheSprite(Datum &id, int field);
492  void setTheSprite(Datum &id, int field, Datum &d);
493  Datum getTheCast(Datum &id, int field);
494  void setTheCast(Datum &id, int field, Datum &d);
495  Datum getTheCastLib(Datum &id, int field);
496  void setTheCastLib(Datum &id, int field, Datum &d);
497  Datum getTheField(Datum &id1, int field);
498  void setTheField(Datum &id1, int field, Datum &d);
499  Datum getTheChunk(Datum &chunk, int field);
500  void setTheChunk(Datum &chunk, int field, Datum &d);
501  void getObjectProp(Datum &obj, Common::String &propName);
502  void setObjectProp(Datum &obj, Common::String &propName, Datum &d);
503  Datum getTheDate(int field);
504  Datum getTheTime(int field);
505  Datum getTheDeskTopRectList();
506 
507 private:
508  Common::StringArray _entityNames;
509  Common::StringArray _fieldNames;
510 
511 public:
512  LingoCompiler *_compiler;
513  LingoState *_state;
514 
515  int _currentChannelId;
516 
517  bool _freezeState;
518  bool _freezePlay;
519  bool _playDone;
520  bool _abort;
521  bool _expectError;
522  bool _caughtError;
523 
524  TheEntityHash _theEntities;
525  TheEntityFieldHash _theEntityFields;
526 
527  int _objectEntityId;
528 
529  SymbolHash _builtinCmds;
530  SymbolHash _builtinFuncs;
531  SymbolHash _builtinConsts;
532  SymbolHash _builtinListHandlers;
533  SymbolHash _methods;
534  XLibOpenerFuncHash _xlibOpeners;
535  XLibCloserFuncHash _xlibClosers;
536 
537  OpenXLibsHash _openXLibs;
538  OpenXLibsStateHash _openXLibsState;
539  Common::StringArray _openXtras;
540  Common::Array<Datum> _openXtraObjects;
541  OpenXLibsStateHash _openXtrasState;
542 
543  Common::String _floatPrecisionFormat;
544 
545 public:
546  void push(Datum d);
547  Datum pop();
548  Datum peek(uint offset);
549 
550 public:
551  Common::HashMap<uint32, const char *> _eventHandlerTypes;
554 
555  DatumHash _globalvars;
556 
557  FuncHash _functions;
558 
561 
562  uint _globalCounter;
563 
564  DirectorEngine *_vm;
565 
566  int _floatPrecision;
567 
568  Datum _theResult;
569 
570  // events
571  bool _passEvent;
572  Datum _perFrameHook;
573 
574  Datum _windowList;
575  Symbol _currentInputEvent;
576 
577  struct {
578  LingoExecState _state = kRunning;
579  bool (*_shouldPause)() = nullptr;
580  } _exec;
581 
582 public:
583  void executeImmediateScripts(Frame *frame);
584  void executePerFrameHook(int frame, int subframe, bool stepFrame = true);
585 
586  // lingo-utils.cpp
587 private:
588  Common::HashMap<uint32, Common::U32String> _charNormalizations;
589  void initCharNormalizations();
590 
591 public:
592  Common::String normalizeString(const Common::String &str);
593 
594 public:
595  void addBreakpoint(Breakpoint &bp);
596  bool delBreakpoint(int id);
597  Breakpoint *getBreakpoint(int id);
598 
599  const Common::Array<Breakpoint> &getBreakpoints() const { return _breakpoints; }
600  Common::Array<Breakpoint> &getBreakpoints() { return _breakpoints; }
601 
602 private:
603  int _bpNextId = 1;
604  Common::Array<Breakpoint> _breakpoints;
605 };
606 
607 extern Lingo *g_lingo;
608 
609 } // End of namespace Director
610 
611 #endif
Definition: lingo.h:111
Definition: cast.h:87
Definition: lingo.h:81
Definition: str.h:59
Definition: lingo.h:306
Definition: lingo.h:61
Definition: lingo.h:120
Definition: array.h:52
Definition: picture.h:33
Definition: lingo.h:252
Definition: rect.h:524
Definition: path.h:52
Definition: lingo.h:266
Definition: lingo.h:194
Definition: archive.h:36
Definition: queue.h:42
Definition: lingo.h:215
Definition: lingo.h:228
Definition: ustr.h:57
Definition: algorithm.h:29
Definition: rect.h:144
Definition: lingo-codegen.h:30
Definition: lingo.h:130
char32_t u32char_type_t
Definition: ustr.h:41
Definition: lingo.h:206
Definition: debugger.h:45
Definition: stream.h:944
Definition: director.h:157
Definition: lingo.h:72
Definition: lingo-object.h:42
Definition: lingo.h:220
Definition: lobject.h:332
Definition: frame.h:180
Definition: castmember.h:48
Definition: lingo.h:356
Definition: types.h:419
Definition: system.h:38
Definition: lingo-object.h:213
Definition: lingo.h:334