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 
181  const char *type2str(bool ilk = false) const;
182 
183  int equalTo(const Datum &d, bool ignoreCase = false) const;
184  uint32 compareTo(const Datum &d) const;
185 
186  bool operator==(const Datum &d) const;
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 };
192 
194  Datum source;
195  ChunkType type;
196  int startChunk;
197  int endChunk;
198  int start;
199  int end;
200 
201  ChunkReference(const Datum &src, ChunkType t, int sc, int ec, int s, int e)
202  : source(src), type(t), startChunk(sc), endChunk(ec), start(s), end(e) {}
203 };
204 
206  int menuIdNum;
207  Common::String *menuIdStr;
208  int menuItemIdNum;
209  Common::String *menuItemIdStr;
210 
211  MenuReference();
212 };
213 
215  Picture *_picture = nullptr;
216  ~PictureReference();
217 };
218 
219 struct PCell {
220  Datum p;
221  Datum v;
222 
223  PCell();
224  PCell(const Datum &prop, const Datum &val);
225 };
226 
227 struct Builtin {
228  void (*func)(void);
229  int nargs;
230 
231  Builtin(void (*func1)(void), int nargs1) : func(func1), nargs(nargs1) {}
232 };
233 
241 typedef void (*XLibOpenerFunc)(ObjectType, const Common::Path &);
242 typedef void (*XLibCloserFunc)(ObjectType);
247 
250 
251 struct CFrame { /* proc/func call stack frame */
252  Symbol sp; /* symbol table entry */
253  int retPC; /* where to resume after return */
254  ScriptData *retScript; /* which script to resume after return */
255  ScriptContext *retContext; /* which script context to use after return */
256  DatumHash *retLocalVars;
257  Datum retMe; /* which me obj to use after return */
258  uint stackSizeBefore;
259  bool allowRetVal; /* whether to allow a return value */
260  Datum defaultRetVal; /* default return value */
261  int paramCount; /* original number of arguments submitted */
262  Common::Array<Datum> paramList; /* original argument list */
263 };
264 
265 struct LingoEvent {
266  LEvent event;
267  int eventId;
268  EventHandlerSourceType eventHandlerSourceType;
269  ScriptType scriptType;
270  bool passByDefault;
271  uint16 channelId;
272  CastMemberID scriptId;
273  Common::Point mousePos;
274 
275  LingoEvent (LEvent e, int ei, ScriptType st, bool pass, CastMemberID si = CastMemberID(), Common::Point mp = Common::Point(-1, -1)) {
276  event = e;
277  eventId = ei;
278  eventHandlerSourceType = kNoneHandler;
279  scriptType = st;
280  passByDefault = pass;
281  channelId = 0;
282  scriptId = si;
283  mousePos = mp;
284  }
285 
286  LingoEvent (LEvent e, int ei, EventHandlerSourceType ehst, bool pass, Common::Point mp = Common::Point(-1, -1), uint16 ci = 0) {
287  event = e;
288  eventId = ei;
289  eventHandlerSourceType = ehst;
290  scriptType = kNoneScript;
291  passByDefault = pass;
292  channelId = ci;
293  scriptId = CastMemberID();
294  mousePos = mp;
295  }
296 };
297 
298 
299 struct LingoArchive {
300  LingoArchive(Cast *c) : cast(c) {};
301  ~LingoArchive();
302 
303  Cast *cast;
304  ScriptContextHash lctxContexts;
305  ScriptContextHash scriptContexts[kMaxScriptType + 1];
306  FactoryContextHash factoryContexts;
308  Common::HashMap<uint32, Common::String> primaryEventHandlers;
309  SymbolHash functionHandlers;
310 
311  ScriptContext *getScriptContext(ScriptType type, uint16 id);
312  ScriptContext *findScriptContext(uint16 id);
313  Common::String getName(uint16 id);
314  Common::String formatFunctionList(const char *prefix);
315 
316  void addCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
317  void patchCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
318  void removeCode(ScriptType type, uint16 id);
319  void replaceCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr);
320  void addCodeV4(Common::SeekableReadStreamEndian &stream, uint16 lctxIndex, const Common::String &archName, uint16 version);
321  void addNamesV4(Common::SeekableReadStreamEndian &stream);
322 
323  // lingo-patcher.cpp
324  void patchScriptHandler(ScriptType type, CastMemberID id);
325 };
326 
327 struct LingoState {
328  // Execution state for a Lingo process, created every time
329  // a top-level handler is called (e.g. on mouseDown).
330  // Can be swapped out when another script gets called with priority.
331  // Call frames are pushed and popped from the callstack with
332  // pushContext and popContext.
333  Common::Array<CFrame *> callstack; // call stack
334  uint pc = 0; // current program counter
335  ScriptData *script = nullptr; // current Lingo script
336  ScriptContext *context = nullptr; // current Lingo script context
337  DatumHash *localVars = nullptr; // current local variables
338  Datum me; // current me object
339  StackData stack;
340 
341  ~LingoState();
342 };
343 
344 enum LingoExecState {
345  kRunning,
346  kPause,
347 };
348 
349 class Lingo {
350 
351 public:
352  Lingo(DirectorEngine *vm);
353  ~Lingo();
354 
355  void resetLingo();
356  void cleanupLingo();
357  void resetLingoGo();
358 
359  int getMenuNum();
360  int getMenuItemsNum(Datum &d);
361  int getXtrasNum();
362  int getCastLibsNum();
363  int getMembersNum(uint16 castLibID);
364 
365  void executeHandler(const Common::String &name, int numargs = 0);
366  void executeScript(ScriptType type, CastMemberID id);
367  Common::String formatStack();
368  void printStack(const char *s, uint pc);
369  Common::String formatCallStack(uint pc);
370  void printCallStack(uint pc);
371  Common::String formatFrame();
372  Common::String formatCurrentInstruction();
373  Common::String decodeInstruction(ScriptData *sd, uint pc, uint *newPC = NULL);
374  Common::String decodeScript(ScriptData *sd);
375  Common::String formatFunctionName(Symbol &sym);
376  Common::String formatFunctionBody(Symbol &sym);
377 
378  void reloadBuiltIns();
379  void initBuiltIns();
380  void initBuiltIns(const BuiltinProto protos[]);
381  void cleanupBuiltIns();
382  void cleanupBuiltIns(const BuiltinProto protos[]);
383  void initFuncs();
384  void cleanupFuncs();
385  void initBytecode();
386  void initMethods();
387  void cleanupMethods();
388  void initXLibs();
389  void cleanupXLibs();
390 
391  Common::String normalizeXLibName(Common::String name);
392  void openXLib(Common::String name, ObjectType type, const Common::Path &path);
393  void closeXLib(Common::String name);
394  void closeOpenXLibs();
395  void reloadOpenXLibs();
396 
397  void runTests();
398 
399  // lingo-events.cpp
400 private:
401  void initEventHandlerTypes();
402  bool processEvent(LEvent event, ScriptType st, CastMemberID scriptId, int channelId = -1);
403 
404 public:
405  ScriptType event2script(LEvent ev);
406  Symbol getHandler(const Common::String &name);
407 
408  void processEvents(Common::Queue<LingoEvent> &queue, bool isInputEvent);
409 
410 public:
411  bool execute(int targetFrame = -1);
412  void switchStateFromWindow();
413  void freezeState();
414  void freezePlayState();
415  void pushContext(const Symbol funcSym, bool allowRetVal, Datum defaultRetVal, int paramCount, int nargs);
416  void popContext(bool aborting = false);
417  void cleanLocalVars();
418  void varAssign(const Datum &var, const Datum &value);
419  Datum varFetch(const Datum &var, bool silent = false);
420  Common::U32String evalChunkRef(const Datum &var);
421  Datum findVarV4(int varType, const Datum &id);
422  CastMemberID resolveCastMember(const Datum &memberID, const Datum &castLib, CastType type);
423  CastMemberID toCastMemberID(const Datum &member, const Datum &castLib);
424  void exposeXObject(const char *name, Datum obj);
425 
426  int getAlignedType(const Datum &d1, const Datum &d2, bool equality);
427 
428  Common::String formatAllVars();
429  void printAllVars();
430 
431  inst readInst() { return getInst(_state->pc++); }
432  inst getInst(uint pc) { return (*_state->script)[pc]; }
433  int readInt() { return getInt(_state->pc++); }
434  int getInt(uint pc);
435  double readFloat() { double d = getFloat(_state->pc); _state->pc += calcCodeAlignment(sizeof(double)); return d; }
436  double getFloat(uint pc) { return *(double *)(&((*_state->script)[_state->pc])); }
437  char *readString() { char *s = getString(_state->pc); _state->pc += calcStringAlignment(s); return s; }
438  char *getString(uint pc) { return (char *)(&((*_state->script)[_state->pc])); }
439 
440  Datum getVoid();
441  void pushVoid();
442 
443  void printArgs(const char *funcname, int nargs, const char *prefix = nullptr);
444  inline void printSTUBWithArglist(const char *funcname, int nargs) { printArgs(funcname, nargs, "STUB: "); }
445  void convertVOIDtoString(int arg, int nargs);
446  void dropStack(int nargs);
447  void drop(uint num);
448 
449  void lingoError(const char *s, ...);
450 
451  void func_mci(const Common::String &name);
452  void func_mciwait(const Common::String &name);
453  void func_beep(int repeats);
454  void func_goto(Datum &frame, Datum &movie, bool commandgo = false );
455  void func_gotoloop();
456  void func_gotonext();
457  void func_gotoprevious();
458  void func_play(Datum &frame, Datum &movie);
459  void func_playdone();
460  void func_cursor(Datum cursorDatum);
461  int func_marker(int m);
462  uint16 func_label(Datum &label);
463 
464  // lingo-the.cpp
465 public:
466  void initTheEntities();
467  void cleanUpTheEntities();
468  const char *entity2str(int id);
469  const char *field2str(int id);
470 
471  // global kTheEntity
472  Datum _actorList;
473  Common::u32char_type_t _itemDelimiter;
474  bool _exitLock;
475  bool _preLoadEventAbort; // no-op, everything is always preloaded
476  Datum _searchPath;
477  bool _trace; // state of movie's trace function
478  int _traceLoad; // internal Director verbosity level
479  bool _updateMovieEnabled;
480  bool _romanLingo;
481 
482  Datum getTheEntity(int entity, Datum &id, int field);
483  void setTheEntity(int entity, Datum &id, int field, Datum &d);
484  Datum getTheSprite(Datum &id, int field);
485  void setTheSprite(Datum &id, int field, Datum &d);
486  Datum getTheCast(Datum &id, int field);
487  void setTheCast(Datum &id, int field, Datum &d);
488  Datum getTheCastLib(Datum &id, int field);
489  void setTheCastLib(Datum &id, int field, Datum &d);
490  Datum getTheField(Datum &id1, int field);
491  void setTheField(Datum &id1, int field, Datum &d);
492  Datum getTheChunk(Datum &chunk, int field);
493  void setTheChunk(Datum &chunk, int field, Datum &d);
494  void getObjectProp(Datum &obj, Common::String &propName);
495  void setObjectProp(Datum &obj, Common::String &propName, Datum &d);
496  Datum getTheDate(int field);
497  Datum getTheTime(int field);
498  Datum getTheDeskTopRectList();
499 
500 private:
501  Common::StringArray _entityNames;
502  Common::StringArray _fieldNames;
503 
504 public:
505  LingoCompiler *_compiler;
506  LingoState *_state;
507 
508  int _currentChannelId;
509 
510  bool _freezeState;
511  bool _freezePlay;
512  bool _playDone;
513  bool _abort;
514  bool _expectError;
515  bool _caughtError;
516 
517  TheEntityHash _theEntities;
518  TheEntityFieldHash _theEntityFields;
519 
520  int _objectEntityId;
521 
522  SymbolHash _builtinCmds;
523  SymbolHash _builtinFuncs;
524  SymbolHash _builtinConsts;
525  SymbolHash _builtinListHandlers;
526  SymbolHash _methods;
527  XLibOpenerFuncHash _xlibOpeners;
528  XLibCloserFuncHash _xlibClosers;
529 
530  OpenXLibsHash _openXLibs;
531  OpenXLibsStateHash _openXLibsState;
532  Common::StringArray _openXtras;
533  OpenXLibsStateHash _openXtrasState;
534 
535  Common::String _floatPrecisionFormat;
536 
537 public:
538  void push(Datum d);
539  Datum pop();
540  Datum peek(uint offset);
541 
542 public:
543  Common::HashMap<uint32, const char *> _eventHandlerTypes;
546 
547  DatumHash _globalvars;
548 
549  FuncHash _functions;
550 
553 
554  uint _globalCounter;
555 
556  DirectorEngine *_vm;
557 
558  int _floatPrecision;
559 
560  Datum _theResult;
561 
562  // events
563  bool _passEvent;
564  Datum _perFrameHook;
565 
566  Datum _windowList;
567  Symbol _currentInputEvent;
568 
569  struct {
570  LingoExecState _state = kRunning;
571  bool (*_shouldPause)() = nullptr;
572  } _exec;
573 
574 public:
575  void executeImmediateScripts(Frame *frame);
576  void executePerFrameHook(int frame, int subframe, bool stepFrame = true);
577 
578  // lingo-utils.cpp
579 private:
580  Common::HashMap<uint32, Common::U32String> _charNormalizations;
581  void initCharNormalizations();
582 
583 public:
584  Common::String normalizeString(const Common::String &str);
585 
586 public:
587  void addBreakpoint(Breakpoint &bp);
588  bool delBreakpoint(int id);
589  Breakpoint *getBreakpoint(int id);
590 
591  const Common::Array<Breakpoint> &getBreakpoints() const { return _breakpoints; }
592  Common::Array<Breakpoint> &getBreakpoints() { return _breakpoints; }
593 
594 private:
595  int _bpNextId = 1;
596  Common::Array<Breakpoint> _breakpoints;
597 };
598 
599 extern Lingo *g_lingo;
600 
601 } // End of namespace Director
602 
603 #endif
Definition: lingo.h:111
Definition: cast.h:87
Definition: lingo.h:81
Definition: str.h:59
Definition: lingo.h:299
Definition: lingo.h:61
Definition: lingo.h:120
Definition: array.h:52
Definition: picture.h:33
Definition: lingo.h:251
Definition: rect.h:524
Definition: path.h:52
Definition: lingo.h:265
Definition: lingo.h:193
Definition: archive.h:36
Definition: queue.h:42
Definition: lingo.h:214
Definition: lingo.h:227
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:205
Definition: debugger.h:45
Definition: stream.h:944
Definition: director.h:156
Definition: lingo.h:72
Definition: lingo-object.h:42
Definition: lingo.h:219
Definition: lobject.h:332
Definition: frame.h:170
Definition: castmember.h:48
Definition: lingo.h:349
Definition: types.h:411
Definition: system.h:38
Definition: lingo-object.h:213
Definition: lingo.h:327