@m2c2kit/core 0.1.10 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,1685 +1,2881 @@
1
- import { Canvas, CanvasKit, Image, FontMgr, Typeface } from 'canvaskit-wasm';
1
+ import { Image, CanvasKit, FontMgr, Typeface, Canvas, Surface, EmbindObject, Font, Paint, ParagraphBuilder, Paragraph, Path, PaintStyle } from 'canvaskit-wasm';
2
2
 
3
- declare class GlobalVariables {
4
- now: number;
5
- deltaTime: number;
6
- canvasScale: number;
7
- rootScale: number;
8
- canvasCssWidth: number;
9
- canvasCssHeight: number;
3
+ declare class GlobalVariables {
4
+ now: number;
5
+ deltaTime: number;
6
+ canvasScale: number;
7
+ rootScale: number;
8
+ canvasCssWidth: number;
9
+ canvasCssHeight: number;
10
10
  }
11
11
 
12
- declare global {
13
- var Globals: GlobalVariables;
14
- }
12
+ declare global {
13
+ var Globals: GlobalVariables;
14
+ }
15
15
  //# sourceMappingURL=Globals.d.ts.map
16
16
 
17
- interface EntityEvent {
18
- target: Entity;
19
- }
20
-
21
- interface EntityEventListener {
22
- eventType: string;
23
- entityName: string;
24
- callback: (event: EntityEvent) => void;
25
- }
26
-
27
- /**
28
- * Position in two-dimensional space.
29
- */
30
- interface Point {
31
- /** Horizonal coordinate */
32
- x: number;
33
- /** Vertical coordinate */
34
- y: number;
35
- }
36
-
37
- interface TapEvent extends EntityEvent {
38
- /** Point that was tapped on entity, relative to the entity coordinate system */
39
- point: Point;
40
- }
41
-
42
- interface DrawableOptions {
43
- anchorPoint?: Point;
44
- zPosition?: number;
45
- }
46
-
47
- interface Constraints {
48
- /** Constrain the top (vertical axis) of this entity to the top of the specified entity. The tops of both will appear at the same vertical location */
49
- topToTopOf?: Entity | string;
50
- /** Constrain the top (vertical axis) of this entity to the bottom of the specified entity. This entity will appear immediately below the specified entity */
51
- topToBottomOf?: Entity | string;
52
- /** Constrain the bottom (vertical axis) of this entity to the top of the specified entity. This entity will appear immediately above of the specified entity */
53
- bottomToTopOf?: Entity | string;
54
- /** Constrain the bottom (vertical axis) of this entity to the bottom of the specified entity. The bottoms of both will appear at the same vertical location */
55
- bottomToBottomOf?: Entity | string;
56
- /** Constrain the start (horizontal axis) of this entity to the start of the specified entity. The start of both will appear at the same horizontal location */
57
- startToStartOf?: Entity | string;
58
- /** Constrain the start (horizontal axis) of this entity to the end of the specified entity. This entity will appear immediately to the right of the specified entity */
59
- startToEndOf?: Entity | string;
60
- /** Constrain the end (horizontal axis) of this entity to the end of the specified entity. The end of both will appear at the same horizontal location */
61
- endToEndOf?: Entity | string;
62
- /** Constrain the end (horizontal axis) of this entity to the start of the specified entity. This entity will appear immediately to the left of the specified entity */
63
- endToStartOf?: Entity | string;
64
- /** When opposing horizontal constraints are applied, the default is to center the entity within the constraints (horizontalBias = .5). Setting horizontalBias less than .5 will pull the entity towards the start (to the left). Setting horizontalBias greater than .5 will pull the entity towards the end (to the right) */
65
- horizontalBias?: number;
66
- /** When opposing vertical constraints are applied, the default is to center the entity within the constraints (verticalBias = .5). Setting verticalBias less than .5 will pull the entity towards the top. Setting verticalBias greater than .5 will pull the entity towards the bottom */
67
- verticalBias?: number;
68
- [key: string]: Entity | string | number | undefined;
69
- }
70
-
71
- /**
72
- * The Layout allows relative positioning via constraints.
73
- * This is not fully implemented yet: DO NOT USE!
74
- * We use it internally for instructions.
75
- */
76
- interface Layout {
77
- height?: number;
78
- width?: number;
79
- marginStart?: number;
80
- marginEnd?: number;
81
- marginTop?: number;
82
- marginBottom?: number;
83
- constraints?: Constraints;
84
- }
85
-
86
- /**
87
- * Color in red (0-255), green (0-255), blue (0-255), alpha (0-1) format. Must be numeric array of length 4.
88
- */
89
- declare type RgbaColor = [number, number, number, number];
90
-
91
- interface TextOptions {
92
- /** Text to be displayed */
93
- text?: string;
94
- /** Name of font to use for text. Must have been previously loaded */
95
- fontName?: string;
96
- /** Color of text. Default is Constants.DEFAULT_FONT_COLOR (WebColors.Black) */
97
- fontColor?: RgbaColor;
98
- /** Size of text. Default is Constants.DEFAULT_FONT_SIZE (16) */
99
- fontSize?: number;
100
- }
101
-
102
- /**
103
- * Width and height on two-dimensional space
104
- */
105
- interface Size {
106
- /** Horizonal width, x-axis */
107
- width: number;
108
- /** Vertical height, y-axis */
109
- height: number;
110
- }
111
-
112
- interface EntityOptions {
113
- /** Name of the entity. Only needed if the entity will be referred to by name in a later function */
114
- name?: string;
115
- /** Position of the entity within its parent coordinate system. Default is (0, 0) */
116
- position?: Point;
117
- /** Scale of the entity. Default is 1.0 */
118
- scale?: number;
119
- /** Does the entity respond to user events, such as taps? Default is false */
120
- isUserInteractionEnabled?: boolean;
121
- /** Is the entity, and its children, hidden? (not displayed). Default is false */
122
- hidden?: boolean;
123
- /** FOR INTERNAL USE ONLY */
124
- layout?: Layout;
125
- }
126
-
127
- declare enum EntityType {
128
- entity = "Entity",
129
- scene = "Scene",
130
- sprite = "Sprite",
131
- label = "Label",
132
- textline = "TextLine",
133
- shape = "Shape",
134
- composite = "Composite"
135
- }
136
-
137
- declare function handleInterfaceOptions(entity: Entity, options: EntityOptions): void;
138
- declare abstract class Entity implements EntityOptions {
139
- type: EntityType;
140
- isDrawable: boolean;
141
- isShape: boolean;
142
- isText: boolean;
143
- name: string;
144
- position: Point;
145
- scale: number;
146
- isUserInteractionEnabled: boolean;
147
- hidden: boolean;
148
- layout: Layout;
149
- parent?: Entity;
150
- children: Entity[];
151
- absolutePosition: Point;
152
- size: Size;
153
- absoluteScale: number;
154
- actions: Action[];
155
- queuedAction?: Action;
156
- originalActions: Action[];
157
- eventListeners: EntityEventListener[];
158
- readonly uuid: string;
159
- needsInitialization: boolean;
160
- userData: any;
161
- loopMessages: Set<string>;
162
- constructor(options?: EntityOptions);
163
- initialize(): void;
164
- /**
165
- * Overrides toString() and returns a human-friendly description of the entity.
166
- *
167
- * @remarks Inspiration from https://stackoverflow.com/a/35361695
168
- */
169
- toString: () => string;
170
- /**
171
- * Adds a child to this parent entity. Thows exception if the child's name is not unique with respect to other children of this parent.
172
- *
173
- * @param child - The child entity to add
174
- */
175
- addChild(child: Entity): void;
176
- /**
177
- * Removes all children from the entity
178
- */
179
- removeAllChildren(): void;
180
- /**
181
- * Removes the specific child from this parent entity. Throws exception if this parent does not contain the child.
182
- *
183
- * @param child
184
- */
185
- removeChild(child: Entity): void;
186
- /**
187
- * Searches all descendants by name and returns first matching entity. Descendants are children and children of children, recursively.
188
- *
189
- * @param name - Name of the descendant entity to return
190
- * @returns
191
- */
192
- descendant<T extends Entity>(name: string): T;
193
- /**
194
- * Returns all descendant entities. Descendants are children and children of children, recursively.
195
- */
196
- get descendants(): Array<Entity>;
197
- /**
198
- * Takes the callback function to be executed when the user taps down on the entity. A TapDown is either a mouse click within the bounds of an entity OR the beginning of touches within the bounds of an entity.
199
- *
200
- * @param callback - function to execute
201
- * @param replaceExistingCallback - should the provided callback replace any existing callbacks? Usually we want to have only one callback defined, instead of chaining multiple ones. It is strongly recommended not to change this, unless you have a special use case. Default is true.
202
- */
203
- onTapDown(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
204
- private parseLayoutConstraints;
205
- private calculateYFromConstraint;
206
- private calculateXFromConstraint;
207
- update(): void;
208
- /**
209
- * Draws each child entity that is Drawable and is not hidden, by zPosition order (highest zPosition on top).
210
- *
211
- * @param canvas - CanvasKit canvas
212
- */
213
- drawChildren(canvas: Canvas): void;
214
- /**
215
- * Runs an action on this entity.
216
- *
217
- * @remarks If the entity is part of an active scene, the action runs immediately. Otherwise, the action will run when the entity's scene becomes active. Calling run() multiple times on an entity will add to existing actions, not replace them.
218
- *
219
- * @param action - The action to run
220
- * @param key - key (string identifier) used to identify the action. Only needed if the action will be referred to later
221
- */
222
- run(action: Action, key?: string): void;
223
- /**
224
- * Remove an action from this entity. If the action is running, it will be stopped.
225
- *
226
- * @param key - key (string identifier) of the action to remove
227
- */
228
- removeAction(key: string): void;
229
- /**
230
- * Remove all actions from this entity. If actions are running, they will be stopped.
231
- */
232
- removeAllActions(): void;
233
- /**
234
- * Duplicates an entity using deep copy.
235
- *
236
- * @remarks This is a deep recursive clone (entity and children).
237
- * The uuid property of all duplicated entities will be newly created,
238
- * because uuid must be unique.
239
- *
240
- * @param newName - optional name of the new, duplicated entity. If not
241
- * provided, name will be the new uuid
242
- */
243
- abstract duplicate(newName?: string): Entity;
244
- protected getEntityOptions(): EntityOptions;
245
- protected getDrawableOptions(): DrawableOptions;
246
- protected getTextOptions(): TextOptions;
247
- /**
248
- * Gets the scene that contains this entity by searching up the ancestor tree recursively. Throws exception if entity is not part of a scene.
249
- *
250
- * @returns Scene that contains this entity
251
- */
252
- get canvasKit(): CanvasKit;
253
- get parentSceneAsEntity(): Entity;
254
- /**
255
- * For a given directed acyclic graph, topological ordering of the vertices will be identified using BFS
256
- * @param adjList Adjacency List that represent a graph with vertices and edges
257
- */
258
- private findTopologicalSort;
259
- }
260
-
261
- interface MoveActionOptions {
262
- /** Destination point. The point is relative to the entity's parent coordinate system */
263
- point: Point;
264
- /** Duration of move, in milliseconds */
265
- duration: number;
266
- /** Should the action run during screen transitions? Default is no */
267
- runDuringTransition?: boolean;
268
- }
269
-
270
- interface WaitActionOptions {
271
- /** Duration of wait, in milliseconds */
272
- duration: number;
273
- /** Should the action run during screen transitions? Default is no */
274
- runDuringTransition?: boolean;
275
- }
276
-
277
- interface CustomActionOptions {
278
- /** callback - The callback function to be executed */
279
- callback: () => void;
280
- /** Should the action run during screen transitions? Default is no */
281
- runDuringTransition?: boolean;
282
- }
283
-
284
- interface ScaleActionOptions {
285
- /** The scaling ratio. 1 is no change, greater than 1 is make bigger, less than 1 is make smaller */
286
- scale: number;
287
- /** Duration of scale, in milliseconds */
288
- duration: number;
289
- /** Should the action run during screen transitions? Default is no */
290
- runDuringTransition?: boolean;
291
- }
292
-
293
- interface IActionContainer {
294
- children?: Array<Action>;
295
- }
296
-
297
- declare enum ActionType {
298
- sequence = "Sequence",
299
- group = "Group",
300
- wait = "Wait",
301
- custom = "Custom",
302
- move = "Move",
303
- scale = "Scale"
304
- }
305
-
306
- declare abstract class Action {
307
- abstract type: ActionType;
308
- startOffset: number;
309
- endOffset: number;
310
- started: boolean;
311
- running: boolean;
312
- completed: boolean;
313
- runStartTime: number;
314
- duration: number;
315
- runDuringTransition: boolean;
316
- parent?: Action;
317
- isParent: boolean;
318
- isChild: boolean;
319
- key?: string;
320
- constructor(runDuringTransition?: boolean);
321
- /**
322
- * Creates an action that will move an entity to a point on the screen.
323
- *
324
- * @param options - {@link MoveActionOptions}
325
- * @returns The move action
326
- */
327
- static Move(options: MoveActionOptions): Action;
328
- /**
329
- * Creates an action that will wait a given duration before it is considered complete.
330
- *
331
- * @param options - {@link WaitActionOptions}
332
- * @returns The wait action
333
- */
334
- static Wait(options: WaitActionOptions): Action;
335
- /**
336
- * Creates an action that will execute a callback function.
337
- *
338
- * @param options - {@link CustomActionOptions}
339
- * @returns The custom action
340
- */
341
- static Custom(options: CustomActionOptions): Action;
342
- /**
343
- * Creates an action that will scale the entity's size.
344
- *
345
- * @remarks Scaling is relative to any inherited scaling, which is multiplicative. For example, if the entity's parent is scaled to 2.0 and this entity's action scales to 3.0, then the entity will appear 6 times as large as original.
346
- *
347
- * @param options - {@link ScaleActionOptions}
348
- * @returns The scale action
349
- */
350
- static Scale(options: ScaleActionOptions): Action;
351
- /**
352
- * Creates an array of actions that will be run in order.
353
- *
354
- * @remarks The next action will not begin until the current one has finished. The sequence will be considered completed when the last action has completed.
355
- *
356
- * @param actions - One or more actions that form the sequence
357
- * @returns
358
- */
359
- static Sequence(actions: Array<Action>): Action;
360
- /**
361
- * Create an array of actions that will be run simultaneously.
362
- *
363
- * @remarks All actions within the group will begin to run at the same time. The group will be considered completed when the longest-running action has completed.
364
- *
365
- * @param actions - One or more actions that form the group
366
- * @returns
367
- */
368
- static Group(actions: Array<Action>): Action;
369
- initialize(entity: Entity, key?: string): Array<Action>;
370
- static cloneAction(action: Action, key?: string): Action;
371
- static evaluateAction(action: Action, entity: Entity, now: number, dt: number): void;
372
- private calculateDuration;
373
- private calculateStartEndOffsets;
374
- private flattenActions;
375
- private assignParents;
376
- }
377
- declare class SequenceAction extends Action implements IActionContainer {
378
- type: ActionType;
379
- children: Array<Action>;
380
- constructor(actions: Array<Action>);
381
- }
382
- declare class GroupAction extends Action implements IActionContainer {
383
- type: ActionType;
384
- children: Action[];
385
- constructor(actions: Array<Action>);
386
- }
387
- declare class CustomAction extends Action {
388
- type: ActionType;
389
- callback: () => void;
390
- constructor(callback: () => void, runDuringTransition?: boolean);
391
- }
392
- declare class WaitAction extends Action {
393
- type: ActionType;
394
- constructor(duration: number, runDuringTransition: boolean);
395
- }
396
- declare class MoveAction extends Action {
397
- type: ActionType;
398
- point: Point;
399
- dx: number;
400
- dy: number;
401
- constructor(point: Point, duration: number, runDuringTransition: boolean);
402
- }
403
- declare class ScaleAction extends Action {
404
- type: ActionType;
405
- scale: number;
406
- delta: number;
407
- constructor(scale: number, duration: number, runDuringTransition?: boolean);
408
- }
409
-
410
- declare enum ActivityType {
411
- game = "Game",
412
- survey = "Survey"
413
- }
414
-
415
- declare class LoadedImage {
416
- name: string;
417
- image: Image;
418
- width: number;
419
- height: number;
420
- constructor(name: string, image: Image, width: number, height: number);
421
- }
422
-
423
- /**
424
- * Image that can be rendered by a browser from a URL or from a
425
- * HTML svg tag in string form. Provide either url or svgString, not both.
426
- */
427
- interface BrowserImage {
428
- /** Name that will be used to refer to the image. Must be unique among all
429
- * images within a game */
430
- name: string;
431
- /** Width to scale image to */
432
- width: number;
433
- /** Height to scale image to */
434
- height: number;
435
- /** The HTML SVG tag, in string form, that will be rendered and loaded.
436
- * Must begin with &#60;svg> and end with &#60;/svg> */
437
- svgString?: string;
438
- /** URL of image asset (svg, png, jpg) to render and load */
439
- url?: string;
440
- }
441
-
442
- interface GameImages {
443
- uuid: string;
444
- images: Array<BrowserImage>;
445
- }
446
-
447
- declare class ImageManager {
448
- canvasKit?: CanvasKit;
449
- private renderedImages;
450
- private loadedImages;
451
- private _scratchCanvas?;
452
- private ctx?;
453
- private scale?;
454
- /**
455
- * Returns a CanvasKit Image that was previously rendered by the ImageManager.
456
- *
457
- * @remarks Typically, this won't be called directly because a programmer
458
- * will use a higher-level abstraction (m2c2kit Sprite).
459
- *
460
- * @param gameUuid - The game that the image resource is part of
461
- * @param imageName - The name given to the rendered image
462
- * @returns A CanvasKit Image
463
- */
464
- getLoadedImage(gameUuid: string, imageName: string): LoadedImage;
465
- /**
466
- * Adds a CanvasKit Image to the images available to a given game.
467
- *
468
- * @remarks Typically, a programmer won't call this because images will be
469
- * automatically rendered and loaded in the Activity async init.
470
- * The only time this function is called in-game is when our internal
471
- * methods add screenshot images needed for transitions.
472
- *
473
- * @param loadedImage - An image that has been converted to a CanvasKit Image
474
- * @param gameUuid - The game that the Image is part of
475
- */
476
- addLoadedImage(loadedImage: LoadedImage, gameUuid: string): void;
477
- /**
478
- * Renders game images from their original format (png, jpg, svg) to
479
- * CanvasKit Image.
480
- *
481
- * @remarks Typically, a programmer won't call this because the Session
482
- * object will manage this. Rendering is an async activity, and thus
483
- * this method returns a promise. Rendering of all images is done in
484
- * parallel.
485
- *
486
- * @param allGamesImages - An array of GameImages data structures that
487
- * specify the image's desired size, it's name, and where the image to be
488
- * rendered is located (e.g., embedded svgString or url)
489
- * @returns A promise that completes when all game images have rendered
490
- */
491
- renderImages(allGamesImages: Array<GameImages>): Promise<void[]>;
492
- /**
493
- * Adds all rendered CanvasKit Images to the images available to m2c2kit.
494
- *
495
- * @remarks Typically, a programmer won't call this because the Session
496
- * object will manage this.
497
- */
498
- loadAllGamesRenderedImages(): void;
499
- /**
500
- * Our private method rendering an image to a CanvasKit Image
501
- *
502
- * @remarks This is complex because there is a separate flow to render
503
- * svg images versus other (e.g., jpg, png). Svg images may be provided
504
- * in a url or inline. In addition, there is a Firefox svg rendering issue,
505
- * see below, that must be handled.
506
- * Additional complexity comes from the potentially multiple async steps and
507
- * the multiple errors that can happen throughout.
508
- *
509
- * @param gameUuid
510
- * @param browserImage
511
- * @returns A promise of type void
512
- */
513
- private renderBrowserImage;
514
- private convertRenderedDataUrlImageToCanvasKitImage;
515
- /**
516
- * Returns the scratchCanvas, which is an extra, non-visible canvas in the
517
- * DOM we use so the native browser can render images like svg, png, jpg,
518
- * that we later will convert to CanvasKit Image.
519
- */
520
- private get scratchCanvas();
521
- private dataURLtoArrayBuffer;
522
- }
523
-
524
- interface GameFontUrls {
525
- uuid: string;
526
- fontUrls: Array<string>;
527
- }
528
-
529
- declare class FontManager {
530
- canvasKit?: CanvasKit;
531
- fontMgr?: FontMgr;
532
- private gameTypefaces;
533
- private allGamesFontData?;
534
- /**
535
- * Gets a typeface that was previously loaded for the specified game.
536
- *
537
- * @param gameUuid
538
- * @param fontFamily
539
- * @returns the requested Typeface
540
- */
541
- getTypeface(gameUuid: string, fontFamily: string): Typeface;
542
- /**
543
- * Fetches all fonts for all games.
544
- *
545
- * @param allGamesFontUrls
546
- * @returns
547
- */
548
- fetchFonts(allGamesFontUrls: Array<GameFontUrls>): Promise<void>;
549
- /**
550
- * Takes the fonts, which have been previously fetched and converted into
551
- * Array Buffers using FontManager.fetchFonts(), and makes them available
552
- * to our engine
553
- */
554
- loadAllGamesFontData(): void;
555
- /**
556
- * For the specified game, fetches all fonts in the array of urls and
557
- * stores fonts as array buffers.
558
- *
559
- * @param gameUuid
560
- * @param fontUrls - array of font urls
561
- * @returns
562
- */
563
- private fetchGameFontsAsArrayBuffers;
564
- /**
565
- * For the specified game, loads all fonts from array buffers and makes
566
- * fonts available within canvaskit as a Typeface
567
- *
568
- * @param gameUuid
569
- * @param fonts - array of fonts in array buffer form
570
- */
571
- private loadGameFonts;
572
- }
573
-
574
- interface EventBase {
575
- eventType: EventType;
576
- }
577
- /** Note: I would have named it Event, but that would collide with
578
- * the existing, and much more well-known, Web API Event */
579
- declare enum EventType {
580
- activityData = "ActivityData",
581
- activityLifecycle = "ActivityLifecycle",
582
- sessionLifecycle = "SessionLifecycle"
583
- }
584
-
585
- interface ActivityEvent extends EventBase {
586
- uuid: string;
587
- name: string;
588
- }
589
-
590
- interface ActivityData {
591
- [key: string]: string | number | boolean | object | undefined | null;
592
- }
593
-
594
- interface ActivityDataEvent extends ActivityEvent {
595
- newData: ActivityData;
596
- newDataSchema: any;
597
- data: ActivityData;
598
- dataSchema: any;
599
- activityConfiguration: any;
600
- }
601
-
602
- interface ActivityLifecycleEvent extends ActivityEvent {
603
- /** the activity started. */
604
- started?: boolean;
605
- /** the activity ended. the user fully completed the activity and */
606
- ended?: boolean;
607
- /** the activity ended. the user canceled without fully completing the activity */
608
- userCanceled?: boolean;
609
- }
610
-
611
- interface ActivityCallbacks {
612
- /** Callback executed when the activity lifecycle changes, such as when it ends. */
613
- onActivityLifecycleChange?: (event: ActivityLifecycleEvent) => void;
614
- /** Callback executed when an activity creates some data. */
615
- onActivityDataCreate?: (event: ActivityDataEvent) => void;
616
- }
617
-
618
- interface SessionEvent extends EventBase {
619
- }
620
-
621
- interface SessionLifecycleEvent extends SessionEvent {
622
- initialized?: boolean;
623
- ended?: boolean;
624
- started?: boolean;
625
- }
626
-
627
- interface SessionCallbacks {
628
- /** Callback executed when the session lifecycle changes, such as when it is initialized. */
629
- onSessionLifecycleChange?: (event: SessionLifecycleEvent) => void;
630
- }
631
-
632
- interface SessionOptions {
633
- /** The activities that compose this session */
634
- activities: Array<Activity>;
635
- /** Callbacks executed when activity events occurs, such as when activity creates data or ends */
636
- activityCallbacks?: ActivityCallbacks;
637
- /** Callbacks executed when session events occur */
638
- sessionCallbacks?: SessionCallbacks;
639
- }
640
-
641
- declare class Session {
642
- options: SessionOptions;
643
- fontManager: FontManager;
644
- imageManager: ImageManager;
645
- currentActivity?: Activity;
646
- uuid: string;
647
- private canvasKit?;
648
- /**
649
- * A Session contains one or more activities; currently, the only
650
- * class that implements Activity is Game, but Survey is planned.
651
- * The session manages the start and stop of activities, and
652
- * advancement to next activity
653
- *
654
- * @param options
655
- */
656
- constructor(options: SessionOptions);
657
- /**
658
- * Asynchronously initializes the m2c2kit engine and loads assets
659
- */
660
- init(): Promise<void>;
661
- /**
662
- * Starts the session and starts the first activity.
663
- */
664
- start(): void;
665
- /**
666
- * Declares the session ended and sends callback.
667
- */
668
- end(): void;
669
- /**
670
- * Stops the current activity and advances to next activity in the session.
671
- * If there is no activity after the current activity, throws error
672
- */
673
- advanceToNextActivity(): void;
674
- /**
675
- * Gets the next activity after the current one, or undefined if
676
- * this is the last activity.
677
- */
678
- get nextActivity(): Activity | undefined;
679
- private logStartingActivity;
680
- /**
681
- * Gets asynchronous assets, including initialization of canvaskit wasm,
682
- * fetching of fonts from specified urls, and rendering and fetching
683
- * of images
684
- * @returns
685
- */
686
- private getAsynchronousAssets;
687
- private loadCanvasKit;
688
- private loadAssets;
689
- private assignCanvasKit;
690
- private getFontsConfigurationFromGames;
691
- private getImagesConfigurationFromGames;
692
- }
693
-
694
- interface Activity {
695
- /** The type of activity: Game or Survey */
696
- type: ActivityType;
697
- /** Initializes the activity. */
698
- init(): void;
699
- /** Starts the activity */
700
- start(): void;
701
- /** Stops the activity */
702
- stop(): void;
703
- /** The activity's parent session */
704
- session: Session;
705
- /** The activity's unique identifier. NOTE: This is newly generated each session. The uuid for an activity will vary across sessions. */
706
- uuid: string;
707
- /** The activity's human friendly name */
708
- name: string;
709
- /** Set activity parameters if defaults are not desired*/
710
- setParameters(newParameters: any): void;
711
- }
712
-
713
- interface IDrawable {
714
- draw(canvas: Canvas): void;
715
- anchorPoint: Point;
716
- zPosition: number;
717
- }
718
-
719
- interface CompositeOptions extends EntityOptions, DrawableOptions {
720
- }
721
-
722
- declare abstract class Composite extends Entity implements IDrawable {
723
- readonly type = EntityType.composite;
724
- compositeType: string;
725
- isDrawable: boolean;
726
- anchorPoint: Point;
727
- zPosition: number;
728
- /**
729
- * Base Drawable object for creating custom entities ("composites") composed of primitive entities.
730
- *
731
- * @param options
732
- */
733
- constructor(options?: CompositeOptions);
734
- initialize(): void;
735
- update(): void;
736
- draw(canvas: Canvas): void;
737
- }
738
-
739
- /**
740
- * Reasonable defaults to use if values are not specified.
741
- */
742
- declare class Constants {
743
- static readonly FPS_DISPLAY_TEXT_FONT_SIZE = 12;
744
- static readonly FPS_DISPLAY_TEXT_COLOR: RgbaColor;
745
- static readonly FPS_DISPLAY_UPDATE_INTERVAL = 500;
746
- static readonly DEFAULT_SCENE_BACKGROUND_COLOR: RgbaColor;
747
- static readonly DEFAULT_SHAPE_FILL_COLOR: RgbaColor;
748
- static readonly DEFAULT_FONT_COLOR: RgbaColor;
749
- static readonly DEFAULT_FONT_SIZE = 16;
750
- static readonly LIMITED_FPS_RATE = 5;
751
- }
752
-
753
- /**
754
- * This enum is used interally for processing the layout constraints. We use
755
- * an enum to avoid magic strings.
756
- */
757
- declare enum ConstraintType {
758
- topToTopOf = "topToTopOf",
759
- topToBottomOf = "topToBottomOf",
760
- bottomToTopOf = "bottomToTopOf",
761
- bottomToBottomOf = "bottomToBottomOf",
762
- startToStartOf = "startToStartOf",
763
- startToEndOf = "startToEndOf",
764
- endToEndOf = "endToEndOf",
765
- endToStartOf = "endToStartOf"
766
- }
767
-
768
- declare enum Dimensions {
769
- MATCH_CONSTRAINT = 0
770
- }
771
-
772
- interface FontData {
773
- gameUuid: string;
774
- fontUrl: string;
775
- fontArrayBuffer: ArrayBuffer;
776
- }
777
-
778
- interface SceneOptions extends EntityOptions, DrawableOptions {
779
- /** Background color of the scene. Default is Constants.DEFAULT_SCENE_BACKGROUND_COLOR (WebColors.WhiteSmoke) */
780
- backgroundColor?: RgbaColor;
781
- }
782
-
783
- declare class Scene extends Entity implements IDrawable, SceneOptions {
784
- readonly type = EntityType.scene;
785
- isDrawable: boolean;
786
- anchorPoint: {
787
- x: number;
788
- y: number;
789
- };
790
- zPosition: number;
791
- private _backgroundColor;
792
- _active: boolean;
793
- _transitioning: boolean;
794
- _setupCallback?: (scene: Scene) => void;
795
- _appearCallback?: (scene: Scene) => void;
796
- private _game?;
797
- private backgroundPaint?;
798
- /**
799
- * Top-level entity that holds all other entities, such as sprites, rectangles, or labels, that will be displayed on the screen
800
- *
801
- * @remarks The scene is the game screen or stage, and fills the entire available screen. There are usually multiple screens to contain multiple stages of the game, such as various instruction pages or phases of a game.
802
- *
803
- * @param options - {@link SceneOptions}
804
- */
805
- constructor(options?: SceneOptions);
806
- initialize(): void;
807
- set game(game: Game);
808
- get game(): Game;
809
- get backgroundColor(): RgbaColor;
810
- set backgroundColor(backgroundColor: RgbaColor);
811
- /**
812
- * Duplicates an entity using deep copy.
813
- *
814
- * @remarks This is a deep recursive clone (entity and children).
815
- * The uuid property of all duplicated entities will be newly created,
816
- * because uuid must be unique.
817
- *
818
- * @param newName - optional name of the new, duplicated entity. If not
819
- * provided, name will be the new uuid
820
- */
821
- duplicate(newName?: string): Scene;
822
- /**
823
- * Code that will be called every time the screen is presented.
824
- *
825
- * @remarks Use this callback to set entities to their initial state, if that state might be changed later. For example, if a scene allows players to place dots on a grid, the setup() method should ensure the grid is clear of any prior dots from previous times this scene may have been displayed. In addition, if entities should vary in each iteration, that should be done here.
826
- *
827
- * @param callback
828
- */
829
- onSetup(callback: (scene: Scene) => void): void;
830
- /**
831
- *
832
- * Code that will be called after the scene has finished any transitions and has fully appeared on the screen.
833
- *
834
- * @param callback
835
- */
836
- onAppear(callback: (scene: Scene) => void): void;
837
- draw(canvas: Canvas): void;
838
- }
839
-
840
- declare abstract class Transition {
841
- abstract type: TransitionType;
842
- duration: number;
843
- /**
844
- * Creates a scene transition in which the outgoing scene slides out and the incoming scene slides in, as if the incoming scene pushes it.
845
- *
846
- * @param direction - TransitionDirection in which the push action goes
847
- * @param duration - Duration, in millis, of the transition
848
- * @returns
849
- */
850
- static push(direction: TransitionDirection, duration: number): PushTransition;
851
- }
852
- declare class PushTransition extends Transition {
853
- type: TransitionType;
854
- direction: TransitionDirection;
855
- constructor(direction: TransitionDirection, duration: number);
856
- }
857
- declare enum TransitionType {
858
- push = "Push"
859
- }
860
- declare enum TransitionDirection {
861
- up = "Up",
862
- down = "Down",
863
- right = "Right",
864
- left = "Left"
865
- }
866
- declare class SceneTransition {
867
- scene: Scene;
868
- transition?: Transition | undefined;
869
- constructor(scene: Scene, transition?: Transition | undefined);
870
- }
871
-
872
- interface TrialSchema {
873
- [key: string]: PropertySchema;
874
- }
875
- interface PropertySchema {
876
- type: "number" | "string" | "boolean" | "object" | "array";
877
- description?: string;
878
- }
879
-
880
- interface GameParameters {
881
- [key: string]: DefaultParameter;
882
- }
883
- interface DefaultParameter {
884
- value: any;
885
- type?: "number" | "string" | "boolean" | "object";
886
- description?: string;
887
- }
888
-
889
- /**
890
- * Options to specify HTML canvas, set game canvas size, and load game assets.
891
- */
892
- interface GameOptions {
893
- /** Human-friendly name of this game */
894
- name: string;
895
- /** Version of this game */
896
- version?: string;
897
- /** Uri (repository, webpage, or other location where full information about the game can be found) */
898
- uri?: string;
899
- /** Brief description of game */
900
- shortDescription?: string;
901
- /** Full description of game */
902
- longDescription?: string;
903
- /** Id of the HTML canvas that game will be drawn on. If not provided, the first canvas found will be used */
904
- canvasId?: string;
905
- /** Width of game canvas */
906
- width: number;
907
- /** Height of game canvas */
908
- height: number;
909
- /** Stretch to fill screen? Default is false */
910
- stretch?: boolean;
911
- /** Schema of trial data; JSON object where key is variable name, value is data type */
912
- trialSchema?: TrialSchema;
913
- /** Default game parameters; JSON object where key is the game parameter, value is default value */
914
- parameters?: GameParameters;
915
- /** String array of urls from which to load fonts. The first element will be the default font */
916
- fontUrls?: Array<string>;
917
- /** Array of BrowserImage objects to render and load */
918
- images?: Array<BrowserImage>;
919
- /** Show FPS in upper left corner? Default is false */
920
- showFps?: boolean;
921
- /** Color of the html body, if the game does not fill the screen. Useful for showing scene boundaries. Default is the scene background color */
922
- bodyBackgroundColor?: RgbaColor;
923
- /** Adapt execution for unit testing? Default is false */
924
- _unitTesting?: boolean;
925
- }
926
-
927
- interface GameData extends ActivityData {
928
- trials: Array<TrialData>;
929
- metadata: Metadata;
930
- }
931
-
932
- interface TrialData {
933
- [key: string]: string | number | boolean | undefined | null;
934
- }
935
- interface Metadata {
936
- userAgent?: string;
937
- devicePixelRatio?: number;
938
- screen?: screenMetadata;
939
- }
940
- /**
941
- * screenMetadata is similar to window.Screen, except we don't want the
942
- * methods on the window.Screen.ScreenOrientation
943
- */
944
- interface screenMetadata {
945
- readonly availHeight: number;
946
- readonly availWidth: number;
947
- readonly colorDepth: number;
948
- readonly height: number;
949
- /** ScreenOrientation has some methods on it; we only want these two properties
950
- * However, when unit testing, orientation is not available to us. Thus, make this
951
- * property optional
952
- */
953
- readonly orientation?: Pick<ScreenOrientation, "type" | "angle">;
954
- readonly pixelDepth: number;
955
- readonly width: number;
956
- }
957
- declare class Game implements Activity {
958
- readonly type = ActivityType.game;
959
- _canvasKit?: CanvasKit;
960
- _session?: Session;
961
- uuid: string;
962
- name: string;
963
- options: GameOptions;
964
- constructor(options: GameOptions);
965
- init(): void;
966
- setParameters(newParameters: any): void;
967
- get canvasKit(): CanvasKit;
968
- set canvasKit(canvasKit: CanvasKit);
969
- get session(): Session;
970
- set session(session: Session);
971
- entryScene?: Scene | string;
972
- data: GameData;
973
- trialIndex: number;
974
- private htmlCanvas?;
975
- private surface?;
976
- private showFps?;
977
- private bodyBackgroundColor?;
978
- private currentScene?;
979
- private priorUpdateTime?;
980
- private fpsTextFont?;
981
- private fpsTextPaint?;
982
- private drawnFrames;
983
- private lastFpsUpdate;
984
- private nextFpsUpdate;
985
- private fps;
986
- private animationFramesRequested;
987
- private limitFps;
988
- private unitTesting;
989
- private gameStopRequested;
990
- canvasCssWidth: number;
991
- canvasCssHeight: number;
992
- private scenes;
993
- private incomingSceneTransitions;
994
- private currentSceneSnapshot?;
995
- private pendingScreenshot?;
996
- /**
997
- * Adds a scene to the game.
998
- *
999
- * @remarks A scene, and its children entities, cannot be presented unless it has been added to the game object.
1000
- *
1001
- * @param scene
1002
- */
1003
- addScene(scene: Scene): void;
1004
- /**
1005
- * Adds multiple scenes to the game.
1006
- *
1007
- * @param scenes
1008
- */
1009
- addScenes(scenes: Array<Scene>): void;
1010
- /**
1011
- * Specifies the scene that will be presented upon the next frame draw.
1012
- *
1013
- * @param scene
1014
- * @param transition
1015
- */
1016
- presentScene(scene: string | Scene, transition?: Transition): void;
1017
- /**
1018
- * Gets the value of the game parameter. If parameterName
1019
- * is not found, then throw exception.
1020
- * @param parameterName - the name of the game parameter whose value is requested
1021
- * @returns
1022
- */
1023
- getParameter<T>(parameterName: string): T;
1024
- /**
1025
- * Starts the game loop. If entryScene is undefined, the game object's entryScene must be set.
1026
- *
1027
- * @param entryScene - The scene (Scene object or its string name) to display when the game starts
1028
- */
1029
- start(entryScene?: Scene | string): void;
1030
- stop(): void;
1031
- initData(): void;
1032
- private getScreenMetadata;
1033
- /**
1034
- * Adds data to the game's TrialData object.
1035
- *
1036
- * @remarks The variableName must be previously defined in the trialSchema object passed in during game initialization. see {@link GameInitOptions.trialSchema}. The type of the value must match what was defined in the trialSchema, otherwise an error is thrown.
1037
- *
1038
- * @param variableName - variable to be set
1039
- * @param value - value of the variable to set
1040
- */
1041
- addTrialData(variableName: string, value: any): void;
1042
- /**
1043
- * Should be called when the current trial has completed. It will
1044
- * also increment the trial index.
1045
- * Calling this will trigger the onActivityDataCreate callback function,
1046
- * if one was provided in SessionOptions. This is how the game communicates
1047
- * trial data to the parent session, which can then save or process the data.
1048
- * It is the responsibility of the the game programmer to call this at
1049
- * the appropriate time. It is not triggered automatically.
1050
- */
1051
- trialComplete(): void;
1052
- /**
1053
- * Should be called when the current game has ended. This will trigger
1054
- * the onActivityLifecycleChange callback function, if one was provided in
1055
- * SessionOptions. This is how the game can communicate its ended or
1056
- * "finished" state to the parent session.
1057
- * It is the responsibility of the the game programmer to call this at
1058
- * the appropriate time. It is not triggered automatically.
1059
- */
1060
- end(): void;
1061
- private setupHtmlCanvases;
1062
- private setupCanvasKitSurface;
1063
- private setupFpsFont;
1064
- private setupEventHandlers;
1065
- private loop;
1066
- private updateGameTime;
1067
- private handleIncomingSceneTransitions;
1068
- private update;
1069
- private draw;
1070
- private takeCurrentSceneSnapshot;
1071
- private handlePendingScreenshot;
1072
- /**
1073
- * Takes screenshot of canvas
1074
- *
1075
- * @remarks Coordinates should be provided unscaled; that is, the method
1076
- * will handle any scaling that happened due to device pixel ratios
1077
- * not equal to 1. This returns a promise because the screenshot request
1078
- * must be queued and completed once a draw cycle has completed. See
1079
- * the loop() method.
1080
- *
1081
- * @param sx - Upper left coordinate of screenshot
1082
- * @param sy - Upper right coordinate of screenshot
1083
- * @param sw - width of area to screenshot
1084
- * @param sh - hegith of area to screenshot
1085
- * @returns Promise of Uint8Array of image data
1086
- */
1087
- takeScreenshot(sx?: number, sy?: number, sw?: number, sh?: number): Promise<Uint8Array | null>;
1088
- private animateSceneTransition;
1089
- private drawFps;
1090
- /**
1091
- * Creates an event listener for an entity based on the entity name
1092
- *
1093
- * @remarks Typically, event listeners will be created using a method specific to the event, such as onTapDown(). This alternative allows creation with entity name.
1094
- *
1095
- * @param eventType - the type of event to listen for, e.g., "tapdown"
1096
- * @param entityName - the entity name for which an event will be listened
1097
- * @param callback
1098
- * @param replaceExistingCallback
1099
- */
1100
- createEventListener(eventType: string, entityName: string, callback: (event: EntityEvent) => void, replaceExistingCallback?: boolean): void;
1101
- /**
1102
- * Returns array of all entities that have been added to the game object.
1103
- */
1104
- get entities(): Array<Entity>;
1105
- private htmlCanvasMouseDownHandler;
1106
- private htmlCanvasTouchStartHandler;
1107
- private sceneCanReceiveUserInteraction;
1108
- private processTaps;
1109
- private handleEntityTapped;
1110
- private tapIsWithinEntityBounds;
1111
- private calculateEntityAbsoluteBoundingBox;
1112
- }
1113
-
1114
- interface IText {
1115
- text?: string;
1116
- fontName?: string;
1117
- fontColor?: RgbaColor;
1118
- fontSize?: number;
1119
- }
1120
-
1121
- declare enum LabelHorizontalAlignmentMode {
1122
- center = 0,
1123
- left = 1,
1124
- right = 2
1125
- }
1126
-
1127
- interface LabelOptions extends EntityOptions, DrawableOptions, TextOptions {
1128
- /** Horizontal alignment of label text. see {@link LabelHorizontalAlignmentMode}. Default is LabelHorizontalAlignmentMode.center */
1129
- horizontalAlignmentMode?: LabelHorizontalAlignmentMode;
1130
- /** Maximum width of label text before wrapping occurs. Default is the canvas width */
1131
- preferredMaxLayoutWidth?: number;
1132
- /** Background color of label text. Default is no background color */
1133
- backgroundColor?: RgbaColor;
1134
- }
1135
-
1136
- declare class Label extends Entity implements IDrawable, IText, LabelOptions {
1137
- readonly type = EntityType.label;
1138
- isDrawable: boolean;
1139
- isText: boolean;
1140
- anchorPoint: {
1141
- x: number;
1142
- y: number;
1143
- };
1144
- zPosition: number;
1145
- private _text;
1146
- private _fontName;
1147
- private _fontColor;
1148
- private _fontSize;
1149
- private _horizontalAlignmentMode;
1150
- private _preferredMaxLayoutWidth;
1151
- private _backgroundColor?;
1152
- private paragraph?;
1153
- private paraStyle?;
1154
- /**
1155
- * Single or multi-line text formatted and rendered on the screen.
1156
- *
1157
- * @remarks Label (in contrast to TextLine) has enhanced text support for line wrapping, centering/alignment, and background colors.
1158
- *
1159
- * @param options - {@link LabelOptions}
1160
- */
1161
- constructor(options?: LabelOptions);
1162
- initialize(): void;
1163
- get text(): string;
1164
- set text(text: string);
1165
- get fontName(): string | undefined;
1166
- set fontName(fontName: string | undefined);
1167
- get fontColor(): RgbaColor;
1168
- set fontColor(fontColor: RgbaColor);
1169
- get fontSize(): number;
1170
- set fontSize(fontSize: number);
1171
- get horizontalAlignmentMode(): LabelHorizontalAlignmentMode;
1172
- set horizontalAlignmentMode(horizontalAlignmentMode: LabelHorizontalAlignmentMode);
1173
- get preferredMaxLayoutWidth(): number | undefined;
1174
- set preferredMaxLayoutWidth(preferredMaxLayoutWidth: number | undefined);
1175
- get backgroundColor(): RgbaColor | undefined;
1176
- set backgroundColor(backgroundColor: RgbaColor | undefined);
1177
- /**
1178
- * Duplicates an entity using deep copy.
1179
- *
1180
- * @remarks This is a deep recursive clone (entity and children).
1181
- * The uuid property of all duplicated entities will be newly created,
1182
- * because uuid must be unique.
1183
- *
1184
- * @param newName - optional name of the new, duplicated entity. If not
1185
- * provided, name will be the new uuid
1186
- */
1187
- duplicate(newName?: string): Label;
1188
- update(): void;
1189
- draw(canvas: Canvas): void;
1190
- }
1191
-
1192
- /**
1193
- * This class is used internally for processing layout constraints that
1194
- * have been defined according to the Contraints interface.
1195
- *
1196
- * Imagine we have two entities, A and B. B's position is set
1197
- * using its position property. A's position is set using the layout
1198
- * constraint "bottomToTopOf B." A is the focal entity in this example.
1199
- * What this means is that A's y coordinate will be computed such that
1200
- * the bottom of A is the top of B. If A and B are squares, then A sits
1201
- * on top of B with no gap.
1202
- */
1203
- declare class LayoutConstraint {
1204
- type: ConstraintType;
1205
- alterEntity: Entity;
1206
- verticalConstraint: boolean;
1207
- focalEntityMinimum: boolean;
1208
- alterEntityMinimum: boolean;
1209
- verticalTypes: ConstraintType[];
1210
- focalEntityMinimumTypes: ConstraintType[];
1211
- alterEntityMinimumTypes: ConstraintType[];
1212
- constructor(type: ConstraintType, alterEntity: Entity);
1213
- }
1214
-
1215
- declare class RandomDraws {
1216
- /**
1217
- * Draws a single random integer from a uniform distribution of integers in
1218
- * the specified range.
1219
- *
1220
- * @param minimumInclusive - Lower bound of range
1221
- * @param maximumInclusive - Upper bound of range
1222
- * @returns A sampled integer
1223
- */
1224
- static SingleFromRange(minimumInclusive: number, maximumInclusive: number): number;
1225
- /**
1226
- * Draws random integers, without replacement, from a uniform distribution
1227
- * of integers in the specified range.
1228
- *
1229
- * @param n - Number of draws
1230
- * @param minimumInclusive - Lower bound of range
1231
- * @param maximumInclusive - Upper bound of range
1232
- * @returns An array of integers
1233
- */
1234
- static FromRangeWithoutReplacement(n: number, minimumInclusive: number, maximumInclusive: number): Array<number>;
1235
- /**
1236
- * Draw random grid cell locations, without replacement, from a uniform
1237
- * distribution of all grid cells. Grid cell locations are zero-based,
1238
- * i.e., upper-left is (0,0).
1239
- *
1240
- * @param n - Number of draws
1241
- * @param rows - Number of rows in grid; must be at least 1
1242
- * @param columns - Number of columns in grid; must be at least 1
1243
- * @param predicate - Optional lambda function that takes a grid row number
1244
- * and grid column number pair and returns a boolean to indicate if the pair
1245
- * should be allowed. For example, if one wanted to constrain the random
1246
- * grid location to be along the diagonal, the predicate would be:
1247
- * (row, column) => row === column
1248
- * @returns Array of grid cells. Each cell is object in form of:
1249
- * {row: number, column: number}. Grid cell locations are zero-based
1250
- */
1251
- static FromGridWithoutReplacement(n: number, rows: number, columns: number, predicate?: (row: number, column: number) => boolean): Array<{
1252
- row: number;
1253
- column: number;
1254
- }>;
1255
- }
1256
-
1257
- interface RectOptions {
1258
- /** Position of rectangle */
1259
- origin?: Point;
1260
- /** Size of rectangle */
1261
- size?: Size;
1262
- /** X coordinate of rectangle position; this can be used instead of setting the origin property */
1263
- x?: number;
1264
- /** Y coordinate of rectangle position; this can be used instead of setting the origin property */
1265
- y?: number;
1266
- /** Width of rectangle; this can be used instead of setting the size property */
1267
- width?: number;
1268
- /** Height of rectangle; this can be used instead of setting the size property */
1269
- height?: number;
1270
- }
1271
-
1272
- declare enum ShapeType {
1273
- undefined = "Undefined",
1274
- rectangle = "Rectangle",
1275
- circle = "Circle"
1276
- }
1277
-
1278
- interface ShapeOptions extends EntityOptions, DrawableOptions {
1279
- shapeType?: ShapeType;
1280
- /** If provided, shape will be a circle with given radius */
1281
- circleOfRadius?: number;
1282
- /** If provided, shape will be a rectangle as specified in {@link Rect} */
1283
- rect?: RectOptions;
1284
- /** Radius of rectangle's corners */
1285
- cornerRadius?: number;
1286
- /** Color with which to fill shape. Default is Constants.DEFAULT_SHAPE_FILL_COLOR (WebColors.Red) */
1287
- fillColor?: RgbaColor;
1288
- /** Color with which to outline shape. Default is no color */
1289
- strokeColor?: RgbaColor;
1290
- /** Width of outline. Default is undefined */
1291
- lineWidth?: number;
1292
- }
1293
-
1294
- declare class Shape extends Entity implements IDrawable, ShapeOptions {
1295
- readonly type = EntityType.shape;
1296
- isDrawable: boolean;
1297
- isShape: boolean;
1298
- anchorPoint: {
1299
- x: number;
1300
- y: number;
1301
- };
1302
- zPosition: number;
1303
- shapeType: ShapeType;
1304
- circleOfRadius?: number;
1305
- rect?: RectOptions;
1306
- cornerRadius: number;
1307
- private _fillColor;
1308
- private _strokeColor?;
1309
- lineWidth?: number;
1310
- private fillColorPaint?;
1311
- private strokeColorPaint?;
1312
- /**
1313
- * Rectangular or circular shape
1314
- *
1315
- * @param options - {@link ShapeOptions}
1316
- */
1317
- constructor(options?: ShapeOptions);
1318
- initialize(): void;
1319
- get fillColor(): RgbaColor;
1320
- set fillColor(fillColor: RgbaColor);
1321
- get strokeColor(): RgbaColor | undefined;
1322
- set strokeColor(strokeColor: RgbaColor | undefined);
1323
- /**
1324
- * Duplicates an entity using deep copy.
1325
- *
1326
- * @remarks This is a deep recursive clone (entity and children).
1327
- * The uuid property of all duplicated entities will be newly created,
1328
- * because uuid must be unique.
1329
- *
1330
- * @param newName - optional name of the new, duplicated entity. If not
1331
- * provided, name will be the new uuid
1332
- */
1333
- duplicate(newName?: string): Shape;
1334
- update(): void;
1335
- draw(canvas: Canvas): void;
1336
- }
1337
-
1338
- interface SpriteOptions extends EntityOptions, DrawableOptions {
1339
- /** Name of image to use for sprite. Must have been previously loaded */
1340
- imageName?: string;
1341
- }
1342
-
1343
- declare class Sprite extends Entity implements IDrawable, SpriteOptions {
1344
- readonly type = EntityType.sprite;
1345
- isDrawable: boolean;
1346
- anchorPoint: {
1347
- x: number;
1348
- y: number;
1349
- };
1350
- zPosition: number;
1351
- private _imageName;
1352
- private loadedImage?;
1353
- /**
1354
- * Visual image displayed on the screen.
1355
- *
1356
- * @remarks Sprites must be loaded during the Game.init() method prior to their use.
1357
- *
1358
- * @param options - {@link SpriteOptions}
1359
- */
1360
- constructor(options?: SpriteOptions);
1361
- initialize(): void;
1362
- set imageName(imageName: string);
1363
- get imageName(): string;
1364
- /**
1365
- * Duplicates an entity using deep copy.
1366
- *
1367
- * @remarks This is a deep recursive clone (entity and children).
1368
- * The uuid property of all duplicated entities will be newly created,
1369
- * because uuid must be unique.
1370
- *
1371
- * @param newName - optional name of the new, duplicated entity. If not
1372
- * provided, name will be the new uuid
1373
- */
1374
- duplicate(newName?: string): Sprite;
1375
- update(): void;
1376
- draw(canvas: Canvas): void;
1377
- }
1378
-
1379
- interface StoryOptions {
1380
- sceneNamePrefix: string;
1381
- }
1382
-
1383
- declare abstract class Story {
1384
- static Create(options: StoryOptions): Array<Scene>;
1385
- }
1386
-
1387
- interface TextLineOptions extends EntityOptions, DrawableOptions, TextOptions {
1388
- width?: number;
1389
- }
1390
-
1391
- declare class TextLine extends Entity implements IDrawable, IText, TextLineOptions {
1392
- readonly type = EntityType.textline;
1393
- isDrawable: boolean;
1394
- isText: boolean;
1395
- zPosition: number;
1396
- anchorPoint: {
1397
- x: number;
1398
- y: number;
1399
- };
1400
- private _text;
1401
- private _fontName;
1402
- private _fontColor;
1403
- private _fontSize;
1404
- private paint?;
1405
- private font?;
1406
- /**
1407
- * Single-line text rendered on the screen.
1408
- *
1409
- * @remarks TextLine has no paragraph formatting options; Label will be preferred in most use cases.
1410
- *
1411
- * @param options - {@link TextLineOptions}
1412
- */
1413
- constructor(options?: TextLineOptions);
1414
- get text(): string;
1415
- set text(text: string);
1416
- get fontName(): string | undefined;
1417
- set fontName(fontName: string | undefined);
1418
- get fontColor(): RgbaColor;
1419
- set fontColor(fontColor: RgbaColor);
1420
- get fontSize(): number;
1421
- set fontSize(fontSize: number);
1422
- update(): void;
1423
- initialize(): void;
1424
- /**
1425
- * Duplicates an entity using deep copy.
1426
- *
1427
- * @remarks This is a deep recursive clone (entity and children).
1428
- * The uuid property of all duplicated entities will be newly created,
1429
- * because uuid must be unique.
1430
- *
1431
- * @param newName - optional name of the new, duplicated entity. If not
1432
- * provided, name will be the new uuid
1433
- */
1434
- duplicate(newName?: string): TextLine;
1435
- draw(canvas: Canvas): void;
1436
- }
1437
-
1438
- declare class Timer {
1439
- private startTime;
1440
- private stopTime;
1441
- private stopped;
1442
- /**
1443
- * cumulativeElapsed is a cumulative total of elapsed time while the timer
1444
- * was in previous started (running) states, NOT INCLUDING the possibily
1445
- * active run's duration
1446
- */
1447
- private cumulativeElapsed;
1448
- private name;
1449
- private static _timers;
1450
- constructor(name: string);
1451
- /**
1452
- * Aliases performance.now()
1453
- *
1454
- * @remarks The m2c2kit Timer class is designed to measure elapsed durations
1455
- * after a designated start point for a uniquely named timer. However, if a
1456
- * timestamp based on the
1457
- * [time origin](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
1458
- * is needed, this method can be used.
1459
- *
1460
- * @returns a [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp)
1461
- */
1462
- static now(): number;
1463
- /**
1464
- * Starts a millisecond-resolution timer based on
1465
- * [performance.now()](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now).
1466
- *
1467
- * @remarks The method throws an error if a timer with the given
1468
- * name is already in a started state.
1469
- *
1470
- * @param name - The name of the timer to be started
1471
- */
1472
- static start(name: string): void;
1473
- /**
1474
- * Stops a timer.
1475
- *
1476
- * @remarks The method throws an error if a timer with the given
1477
- * name is already in a stopped state, or if a timer with the
1478
- * given name has not been started.
1479
- *
1480
- * @param name - The name of the timer to be stopped
1481
- */
1482
- static stop(name: string): void;
1483
- /**
1484
- * Restarts a timer.
1485
- *
1486
- * @remarks The timer elapsed duration is set to 0 and it starts anew.
1487
- * The method throws an error if a timer with the given
1488
- * name does not exist (if there is not a started or stopped timer
1489
- * with the given name).
1490
- *
1491
- * @param name - The name of the timer to be restarted
1492
- */
1493
- static restart(name: string): void;
1494
- /**
1495
- * Returns the total time elapsed, in milliseconds, of the timer.
1496
- *
1497
- * @remarks The total time elapsed will include all durations from multiple
1498
- * starts and stops of the timer, if applicable. A timer's elapsed duration
1499
- * can be read while it is in started or stopped state. The method throws
1500
- * an error if a timer with the given name does not exist.
1501
- *
1502
- * @param name - The name of the timer whose elapsed duration is requested
1503
- */
1504
- static elapsed(name: string): number;
1505
- /**
1506
- * Removes a timer.
1507
- *
1508
- * @remarks After removal, no additional methods can be used with a timer
1509
- * of the given name, other than to start a new timer with the given name,
1510
- * whose duration will begin at 0 again. The method throws an error if
1511
- * a timer with the given name does not exist.
1512
- *
1513
- * @param name - The name of the timer to be removed
1514
- */
1515
- static remove(name: string): void;
1516
- /**
1517
- * Remove all timers.
1518
- *
1519
- * @remarks This method will {@link remove} any timers in a started or
1520
- * stopped state. This method is idempotent; method is safe to call even
1521
- * if there are no timers to remove; no errors are thrown if there are
1522
- * not any timers that can be removed.
1523
- */
1524
- static removeAll(): void;
1525
- /**
1526
- * Checks if a timer of the given name exists.
1527
- *
1528
- * @remarks The method checks if there is a timer with the given name.
1529
- *
1530
- * @param name - The name of the timer to check for existence
1531
- * @returns boolean
1532
- */
1533
- static exists(name: string): boolean;
1534
- }
1535
-
1536
- declare class Uuid {
1537
- static generate(): string;
1538
- }
1539
-
1540
- declare class WebColors {
1541
- static Transparent: RgbaColor;
1542
- static MediumVioletRed: RgbaColor;
1543
- static DeepPink: RgbaColor;
1544
- static PaleVioletRed: RgbaColor;
1545
- static HotPink: RgbaColor;
1546
- static LightPink: RgbaColor;
1547
- static Pink: RgbaColor;
1548
- static DarkRed: RgbaColor;
1549
- static Red: RgbaColor;
1550
- static Firebrick: RgbaColor;
1551
- static Crimson: RgbaColor;
1552
- static IndianRed: RgbaColor;
1553
- static LightCoral: RgbaColor;
1554
- static Salmon: RgbaColor;
1555
- static DarkSalmon: RgbaColor;
1556
- static LightSalmon: RgbaColor;
1557
- static OrangeRed: RgbaColor;
1558
- static Tomato: RgbaColor;
1559
- static DarkOrange: RgbaColor;
1560
- static Coral: RgbaColor;
1561
- static Orange: RgbaColor;
1562
- static DarkKhaki: RgbaColor;
1563
- static Gold: RgbaColor;
1564
- static Khaki: RgbaColor;
1565
- static PeachPuff: RgbaColor;
1566
- static Yellow: RgbaColor;
1567
- static PaleGoldenrod: RgbaColor;
1568
- static Moccasin: RgbaColor;
1569
- static PapayaWhip: RgbaColor;
1570
- static LightGoldenrodYellow: RgbaColor;
1571
- static LemonChiffon: RgbaColor;
1572
- static LightYellow: RgbaColor;
1573
- static Maroon: RgbaColor;
1574
- static Brown: RgbaColor;
1575
- static SaddleBrown: RgbaColor;
1576
- static Sienna: RgbaColor;
1577
- static Chocolate: RgbaColor;
1578
- static DarkGoldenrod: RgbaColor;
1579
- static Peru: RgbaColor;
1580
- static RosyBrown: RgbaColor;
1581
- static Goldenrod: RgbaColor;
1582
- static SandyBrown: RgbaColor;
1583
- static Tan: RgbaColor;
1584
- static Burlywood: RgbaColor;
1585
- static Wheat: RgbaColor;
1586
- static NavajoWhite: RgbaColor;
1587
- static Bisque: RgbaColor;
1588
- static BlanchedAlmond: RgbaColor;
1589
- static Cornsilk: RgbaColor;
1590
- static DarkGreen: RgbaColor;
1591
- static Green: RgbaColor;
1592
- static DarkOliveGreen: RgbaColor;
1593
- static ForestGreen: RgbaColor;
1594
- static SeaGreen: RgbaColor;
1595
- static Olive: RgbaColor;
1596
- static OliveDrab: RgbaColor;
1597
- static MediumSeaGreen: RgbaColor;
1598
- static LimeGreen: RgbaColor;
1599
- static Lime: RgbaColor;
1600
- static SpringGreen: RgbaColor;
1601
- static MediumSpringGreen: RgbaColor;
1602
- static DarkSeaGreen: RgbaColor;
1603
- static MediumAquamarine: RgbaColor;
1604
- static YellowGreen: RgbaColor;
1605
- static LawnGreen: RgbaColor;
1606
- static Chartreuse: RgbaColor;
1607
- static LightGreen: RgbaColor;
1608
- static GreenYellow: RgbaColor;
1609
- static PaleGreen: RgbaColor;
1610
- static Teal: RgbaColor;
1611
- static DarkCyan: RgbaColor;
1612
- static LightSeaGreen: RgbaColor;
1613
- static CadetBlue: RgbaColor;
1614
- static DarkTurquoise: RgbaColor;
1615
- static MediumTurquoise: RgbaColor;
1616
- static Turquoise: RgbaColor;
1617
- static Aqua: RgbaColor;
1618
- static Cyan: RgbaColor;
1619
- static Aquamarine: RgbaColor;
1620
- static PaleTurquoise: RgbaColor;
1621
- static LightCyan: RgbaColor;
1622
- static Navy: RgbaColor;
1623
- static DarkBlue: RgbaColor;
1624
- static MediumBlue: RgbaColor;
1625
- static Blue: RgbaColor;
1626
- static MidnightBlue: RgbaColor;
1627
- static RoyalBlue: RgbaColor;
1628
- static SteelBlue: RgbaColor;
1629
- static DodgerBlue: RgbaColor;
1630
- static DeepSkyBlue: RgbaColor;
1631
- static CornflowerBlue: RgbaColor;
1632
- static SkyBlue: RgbaColor;
1633
- static LightSkyBlue: RgbaColor;
1634
- static LightSteelBlue: RgbaColor;
1635
- static LightBlue: RgbaColor;
1636
- static PowderBlue: RgbaColor;
1637
- static Indigo: RgbaColor;
1638
- static Purple: RgbaColor;
1639
- static DarkMagenta: RgbaColor;
1640
- static DarkViolet: RgbaColor;
1641
- static DarkSlateBlue: RgbaColor;
1642
- static BlueViolet: RgbaColor;
1643
- static DarkOrchid: RgbaColor;
1644
- static Fuchsia: RgbaColor;
1645
- static Magenta: RgbaColor;
1646
- static SlateBlue: RgbaColor;
1647
- static MediumSlateBlue: RgbaColor;
1648
- static MediumOrchid: RgbaColor;
1649
- static MediumPurple: RgbaColor;
1650
- static Orchid: RgbaColor;
1651
- static Violet: RgbaColor;
1652
- static Plum: RgbaColor;
1653
- static Thistle: RgbaColor;
1654
- static Lavender: RgbaColor;
1655
- static MistyRose: RgbaColor;
1656
- static AntiqueWhite: RgbaColor;
1657
- static Linen: RgbaColor;
1658
- static Beige: RgbaColor;
1659
- static WhiteSmoke: RgbaColor;
1660
- static LavenderBlush: RgbaColor;
1661
- static OldLace: RgbaColor;
1662
- static AliceBlue: RgbaColor;
1663
- static Seashell: RgbaColor;
1664
- static GhostWhite: RgbaColor;
1665
- static Honeydew: RgbaColor;
1666
- static FloralWhite: RgbaColor;
1667
- static Azure: RgbaColor;
1668
- static MintCream: RgbaColor;
1669
- static Snow: RgbaColor;
1670
- static Ivory: RgbaColor;
1671
- static White: RgbaColor;
1672
- static Black: RgbaColor;
1673
- static DarkSlateGray: RgbaColor;
1674
- static DimGray: RgbaColor;
1675
- static SlateGray: RgbaColor;
1676
- static Gray: RgbaColor;
1677
- static LightSlateGray: RgbaColor;
1678
- static DarkGray: RgbaColor;
1679
- static Silver: RgbaColor;
1680
- static LightGray: RgbaColor;
1681
- static Gainsboro: RgbaColor;
1682
- static RebeccaPurple: RgbaColor;
1683
- }
1684
-
1685
- export { Action, Activity, ActivityDataEvent, ActivityLifecycleEvent, ActivityType, BrowserImage, Composite, CompositeOptions, Constants, ConstraintType, Constraints, CustomAction, CustomActionOptions, DefaultParameter, Dimensions, DrawableOptions, Entity, EntityEventListener, EntityOptions, EntityType, EventBase, EventType, FontData, FontManager, Game, GameData, GameOptions, GameParameters, GlobalVariables, GroupAction, IDrawable, IText, ImageManager, Label, LabelHorizontalAlignmentMode, LabelOptions, Layout, LayoutConstraint, LoadedImage, Metadata, MoveAction, MoveActionOptions, Point, PropertySchema, PushTransition, RandomDraws, RectOptions, RgbaColor, ScaleAction, ScaleActionOptions, Scene, SceneOptions, SceneTransition, SequenceAction, Session, SessionLifecycleEvent, SessionOptions, Shape, ShapeOptions, ShapeType, Size, Sprite, SpriteOptions, Story, StoryOptions, TextLine, TextLineOptions, TextOptions, Timer, Transition, TransitionDirection, TransitionType, TrialData, TrialSchema, Uuid, WaitAction, WaitActionOptions, WebColors, handleInterfaceOptions };
17
+ /**
18
+ * The type of activity.
19
+ *
20
+ * @remarks Currently, m2c2kit has only Game and Survey activities.
21
+ */
22
+ declare enum ActivityType {
23
+ Game = "Game",
24
+ Survey = "Survey"
25
+ }
26
+
27
+ /** Base interface for all Activity events. */
28
+ interface ActivityEvent extends EventBase {
29
+ target: Activity;
30
+ }
31
+
32
+ /** Data from activities are stored as key (string) value pairs. */
33
+ interface ActivityKeyValueData {
34
+ [key: string]: string | number | boolean | object | undefined | null;
35
+ }
36
+
37
+ /** A snapshot of performance at a single point in time.
38
+ *
39
+ * @remarks This describes performance of the application internals, not the
40
+ * participant. Do not store participant data here. Use snake case because
41
+ * these data will be directly exported to persistence.
42
+ */
43
+ interface ActivityMetric {
44
+ [key: string]: string | number | boolean | object | undefined | null;
45
+ activity_type: ActivityType;
46
+ activity_uuid: string;
47
+ iso8601_timestamp: string;
48
+ }
49
+
50
+ interface JsonSchema {
51
+ /** Data type of the value or array of acceptable data types. */
52
+ type?: JsonSchemaDataType | JsonSchemaDataType[];
53
+ /** Values the schema can have. */
54
+ enum?: unknown[];
55
+ /** Annotation to indicate the type of string value, e.g., "date-time" or "email". */
56
+ format?: string;
57
+ /** Intent of the schema. */
58
+ title?: string;
59
+ /** Description of the schema. */
60
+ description?: string;
61
+ /** If the value is an object, the properties in JsonSchema. */
62
+ properties?: {
63
+ [key: string]: JsonSchema;
64
+ };
65
+ /** If the value is an array, the array items in JsonSchema. */
66
+ items?: JsonSchema;
67
+ /** Required properties. */
68
+ required?: string[];
69
+ /** Reference to object definitions. */
70
+ $ref?: string;
71
+ /** Object definitions. */
72
+ $defs?: object;
73
+ /** Comment string. */
74
+ $comment?: string;
75
+ /** Dialect of JSON Schema. */
76
+ $schema?: string;
77
+ /** Default value. */
78
+ default?: any;
79
+ }
80
+ type JsonSchemaDataType = "string" | "number" | "integer" | "object" | "array" | "boolean" | "null";
81
+
82
+ /**
83
+ * All the data created by an activity.
84
+ */
85
+ interface ActivityResults {
86
+ /** All the data created by the activity. */
87
+ data: ActivityKeyValueData;
88
+ /** JSON schema describing the structure of the data. */
89
+ dataSchema: JsonSchema;
90
+ /** Parameters under which the activity was run. */
91
+ activityConfiguration: unknown;
92
+ /** JSON schema describing the activity parameters. */
93
+ activityConfigurationSchema: JsonSchema;
94
+ /** Metrics describing internal application performance. */
95
+ activityMetrics?: Array<ActivityMetric>;
96
+ }
97
+
98
+ /**
99
+ * Dispatched when new data is created by an activity.
100
+ *
101
+ * @remarks Event contains all the data created by an activity, with
102
+ * separate properties for the newly created data. ActivityResultsEvent
103
+ * inherts "data" from ActivityResults, which contains the complete data
104
+ * up to this point (both new and existing data).
105
+ */
106
+ interface ActivityResultsEvent extends ActivityEvent, ActivityResults {
107
+ /** New data created by the activity, which dispatched this event */
108
+ newData: ActivityKeyValueData;
109
+ /** JSON schema describing the new data */
110
+ newDataSchema: JsonSchema;
111
+ /** ISO 8601 timestamp of the event. Specifically, value of "new Date().toISOString()" executed on the device when the ActivityResultsEvent occured. */
112
+ iso8601Timestamp: string;
113
+ }
114
+
115
+ /**
116
+ * An interface for persisting data.
117
+ *
118
+ * @remarks This interface saves activity results as well as saves and
119
+ * retrieves arbitrary key-value items that activities can use.
120
+ *
121
+ * The underlying persistence provider of the store must
122
+ * be previously set in the activity's `Session` before use. The
123
+ * implementation of the store is not provided by the \@m2c2kit/core library.
124
+ *
125
+ * @example
126
+ * ```
127
+ * import { LocalDatabase } from "@m2c2kit/db";
128
+ * ...
129
+ * const db: IDataStore = new LocalDatabase();
130
+ * session.dataStore = db;
131
+ * session.init();
132
+ * ```
133
+ */
134
+ interface IDataStore {
135
+ /** Saves activity results in the data store. */
136
+ saveActivityResults(ev: ActivityResultsEvent): Promise<string>;
137
+ /** Sets the value of an item. The key will be saved to the store as provided;
138
+ * if namespacing or other formatting is desired, it must be done before
139
+ * calling this method. activityId can be used by the store for indexing. */
140
+ setItem(key: string, value: string | number | boolean | object | undefined | null, activityId: string): Promise<string>;
141
+ /** Gets the value of an item by its key. */
142
+ getItem<T extends string | number | boolean | object | undefined | null>(key: string): Promise<T>;
143
+ /** Deletes an item by its key. */
144
+ deleteItem(key: string): Promise<void>;
145
+ /** Deletes all items. */
146
+ clearItemsByActivityId(activityId: string): Promise<void>;
147
+ /** Returns keys of all items. */
148
+ itemsKeysByActivityId(activityId: string): Promise<string[]>;
149
+ /** Determines if the key exists. */
150
+ itemExists(key: string): Promise<boolean>;
151
+ }
152
+
153
+ declare class LoadedImage {
154
+ name: string;
155
+ image: Image;
156
+ width: number;
157
+ height: number;
158
+ constructor(name: string, image: Image, width: number, height: number);
159
+ }
160
+
161
+ /**
162
+ * Image that can be rendered by a browser from a URL or from a
163
+ * HTML svg tag in string form. Provide either url or svgString, not both.
164
+ */
165
+ interface BrowserImage {
166
+ /** Name that will be used to refer to the image. Must be unique among all
167
+ * images within a game */
168
+ imageName: string;
169
+ /** Width to scale image to */
170
+ width: number;
171
+ /** Height to scale image to */
172
+ height: number;
173
+ /** The HTML SVG tag, in string form, that will be rendered and loaded.
174
+ * Must begin with &#60;svg> and end with &#60;/svg> */
175
+ svgString?: string;
176
+ /** URL of image asset (svg, png, jpg) to render and load */
177
+ url?: string;
178
+ }
179
+
180
+ interface GameImages {
181
+ uuid: string;
182
+ images: Array<BrowserImage>;
183
+ }
184
+
185
+ declare class LoadedImages {
186
+ [gameUuid: string]: {
187
+ [name: string]: LoadedImage;
188
+ };
189
+ }
190
+ declare class ImageManager {
191
+ canvasKit?: CanvasKit;
192
+ private renderedImages;
193
+ loadedImages: LoadedImages;
194
+ private _scratchCanvas?;
195
+ private ctx?;
196
+ private scale?;
197
+ /**
198
+ * Returns a CanvasKit Image that was previously rendered by the ImageManager.
199
+ *
200
+ * @remarks Typically, this won't be called directly because a programmer
201
+ * will use a higher-level abstraction (m2c2kit Sprite).
202
+ *
203
+ * @param gameUuid - The game that the image resource is part of
204
+ * @param imageName - The name given to the rendered image
205
+ * @returns A CanvasKit Image
206
+ */
207
+ getLoadedImage(gameUuid: string, imageName: string): LoadedImage;
208
+ /**
209
+ * Adds a CanvasKit Image to the images available to a given game.
210
+ *
211
+ * @remarks Typically, a programmer won't call this because images will be
212
+ * automatically rendered and loaded in the Activity async init.
213
+ * The only time this function is called in-game is when our internal
214
+ * methods add screenshot images needed for transitions.
215
+ *
216
+ * @param loadedImage - An image that has been converted to a CanvasKit Image
217
+ * @param gameUuid - The game that the Image is part of
218
+ */
219
+ addLoadedImage(loadedImage: LoadedImage, gameUuid: string): void;
220
+ /**
221
+ * Renders game images from their original format (png, jpg, svg) to
222
+ * CanvasKit Image.
223
+ *
224
+ * @remarks Typically, a programmer won't call this because the Session
225
+ * object will manage this. Rendering is an async activity, and thus
226
+ * this method returns a promise. Rendering of all images is done in
227
+ * parallel.
228
+ *
229
+ * @param allGamesImages - An array of GameImages data structures that
230
+ * specify the image's desired size, it's name, and where the image to be
231
+ * rendered is located (e.g., embedded svgString or url)
232
+ * @returns A promise that completes when all game images have rendered
233
+ */
234
+ renderImages(allGamesImages: Array<GameImages>): Promise<void[]>;
235
+ /**
236
+ * Adds all rendered CanvasKit Images to the images available to m2c2kit.
237
+ *
238
+ * @remarks Typically, a programmer won't call this because the Session
239
+ * object will manage this.
240
+ */
241
+ loadAllGamesRenderedImages(): void;
242
+ /**
243
+ * Our private method rendering an image to a CanvasKit Image
244
+ *
245
+ * @remarks This is complex because there is a separate flow to render
246
+ * svg images versus other (e.g., jpg, png). Svg images may be provided
247
+ * in a url or inline. In addition, there is a Firefox svg rendering issue,
248
+ * see below, that must be handled.
249
+ * Additional complexity comes from the potentially multiple async steps and
250
+ * the multiple errors that can happen throughout.
251
+ *
252
+ * @param gameUuid
253
+ * @param browserImage
254
+ * @returns A promise of type void
255
+ */
256
+ private renderBrowserImage;
257
+ private inferImageSubtypeFromUrl;
258
+ private convertRenderedDataUrlImageToCanvasKitImage;
259
+ /**
260
+ * Returns the scratchCanvas, which is an extra, non-visible canvas in the
261
+ * DOM we use so the native browser can render images like svg, png, jpg,
262
+ * that we later will convert to CanvasKit Image.
263
+ */
264
+ private get scratchCanvas();
265
+ private dataURLtoArrayBuffer;
266
+ removeScratchCanvas(): void;
267
+ }
268
+
269
+ interface GameFontUrls {
270
+ uuid: string;
271
+ fontUrls: Array<string>;
272
+ }
273
+
274
+ /**
275
+ * This class contains all the fonts for all the games in the activity.
276
+ * Fonts have been converted to canvaskit Typeface
277
+ */
278
+ declare class GameTypefaces {
279
+ [gameUuid: string]: {
280
+ [fontFamily: string]: Typeface;
281
+ };
282
+ }
283
+ /**
284
+ * Class for loading, preparing, and providing fonts to games.
285
+ *
286
+ * @remarks FOR INTERNAL USE ONLY
287
+ */
288
+ declare class FontManager {
289
+ canvasKit?: CanvasKit;
290
+ fontMgr?: FontMgr;
291
+ gameTypefaces: GameTypefaces;
292
+ private allGamesFontData?;
293
+ /**
294
+ * Gets a typeface that was previously loaded for the specified game.
295
+ *
296
+ * @param gameUuid
297
+ * @param fontFamily
298
+ * @returns the requested Typeface
299
+ */
300
+ getTypeface(gameUuid: string, fontFamily: string): Typeface;
301
+ /**
302
+ * Gets names of fonts loaded for the specified game.
303
+ *
304
+ * @param gameUuid
305
+ * @returns array of font family names
306
+ */
307
+ getFontNames(gameUuid: string): Array<string>;
308
+ /**
309
+ * Fetches all fonts for all games.
310
+ *
311
+ * @param allGamesFontUrls
312
+ * @returns
313
+ */
314
+ fetchFonts(allGamesFontUrls: Array<GameFontUrls>): Promise<void>;
315
+ /**
316
+ * Takes the fonts, which have been previously fetched and converted into
317
+ * Array Buffers using FontManager.fetchFonts(), and makes them available
318
+ * to our engine
319
+ */
320
+ loadAllGamesFontData(): void;
321
+ /**
322
+ * For the specified game, fetches all fonts in the array of urls and
323
+ * stores fonts as array buffers.
324
+ *
325
+ * @param gameUuid
326
+ * @param fontUrls - array of font urls
327
+ * @returns
328
+ */
329
+ private fetchGameFontsAsArrayBuffers;
330
+ /**
331
+ * For the specified game, loads all fonts from array buffers and makes
332
+ * fonts available within canvaskit as a Typeface
333
+ *
334
+ * @param gameUuid
335
+ * @param fonts - array of fonts in array buffer form
336
+ */
337
+ private loadGameFonts;
338
+ }
339
+
340
+ /**
341
+ * Notifies when an activity starts, ends, cancels, or
342
+ * creates data.
343
+ */
344
+ interface ActivityLifecycleEvent extends ActivityEvent {
345
+ results?: ActivityResults;
346
+ }
347
+
348
+ interface ActivityCallbacks {
349
+ /** Callback executed when the activity lifecycle changes, such as when it ends. */
350
+ onActivityLifecycle?: (event: ActivityLifecycleEvent) => void;
351
+ /** Callback executed when an activity creates some data. */
352
+ onActivityResults?: (event: ActivityResultsEvent) => void;
353
+ }
354
+
355
+ /** Base interface for all Session events. */
356
+ interface SessionEvent extends EventBase {
357
+ target: Session;
358
+ }
359
+
360
+ /**
361
+ * Notifies when a session starts, ends, or initializes.
362
+ */
363
+ interface SessionLifecycleEvent extends SessionEvent {
364
+ }
365
+
366
+ interface SessionCallbacks {
367
+ /** Callback executed when the session lifecycle changes, such as when it is initialized. */
368
+ onSessionLifecycle?: (event: SessionLifecycleEvent) => void;
369
+ }
370
+
371
+ interface SessionOptions {
372
+ /** The activities that compose this session */
373
+ activities: Array<Activity>;
374
+ /** Callbacks executed when activity events occurs, such as when activity creates data or ends */
375
+ activityCallbacks?: ActivityCallbacks;
376
+ /** Callbacks executed when session events occur */
377
+ sessionCallbacks?: SessionCallbacks;
378
+ /** Url of the canvaskit.wasm binary. Always set to the default value of "assets/canvaskit.wasm" */
379
+ canvasKitWasmUrl: "assets/canvaskit.wasm";
380
+ /** Use a specified session UUID, rather than create a new one */
381
+ sessionUuid?: string;
382
+ /** NOT IMPLEMENTED YET: Orientation the screen should be locked to for this session. Value will be passed into the ScreenOrientation.lock() Web API. */
383
+ orientation?: "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary";
384
+ }
385
+
386
+ declare class Session {
387
+ options: SessionOptions;
388
+ fontManager: FontManager;
389
+ imageManager: ImageManager;
390
+ currentActivity?: Activity;
391
+ uuid: string;
392
+ dataStore?: IDataStore;
393
+ private sessionDictionary;
394
+ private canvasKit?;
395
+ private version;
396
+ /**
397
+ * A Session contains one or more activities. The session manages the start
398
+ * and stop of activities, and advancement to next activity
399
+ *
400
+ * @param options
401
+ */
402
+ constructor(options: SessionOptions);
403
+ /**
404
+ * Asynchronously initializes the m2c2kit engine and loads assets
405
+ */
406
+ init(): Promise<void>;
407
+ /**
408
+ * Starts the session and starts the first activity.
409
+ */
410
+ start(): Promise<void>;
411
+ /**
412
+ * Declares the session ended and sends callback.
413
+ */
414
+ end(): void;
415
+ private stop;
416
+ /**
417
+ * Frees up resources that were allocated to run the session.
418
+ *
419
+ * @remarks This will be done automatically by the m2c2kit library;
420
+ * the end-user must not call this.
421
+ */
422
+ private dispose;
423
+ /**
424
+ * Stops the current activity and goes to the activity with the provided id.
425
+ *
426
+ * @param options
427
+ */
428
+ goToActivity(options: GoToActivityOptions): Promise<void>;
429
+ /**
430
+ * Stops the current activity and advances to next activity in the session.
431
+ * If there is no activity after the current activity, throws error.
432
+ */
433
+ goToNextActivity(): Promise<void>;
434
+ /**
435
+ * Stops the current activity and advances to next activity in the session.
436
+ * If there is no activity after the current activity, throws error.
437
+ *
438
+ * @deprecated Use goToNextActivity() instead.
439
+ */
440
+ advanceToNextActivity(): Promise<void>;
441
+ /**
442
+ * Gets the next activity after the current one, or undefined if
443
+ * this is the last activity.
444
+ */
445
+ get nextActivity(): Activity | undefined;
446
+ /**
447
+ * Saves an item to the session's key-value dictionary.
448
+ *
449
+ * @remarks The session dictionary is not persisted. It is available only
450
+ * during the actively running session. It is useful for storing temporary
451
+ * data to coordinate between activities.
452
+ *
453
+ * @param key - item key
454
+ * @param value - item value
455
+ */
456
+ dictionarySetItem(key: string, value: SessionDictionaryValues): void;
457
+ /**
458
+ * Gets an item value from the session's key-value dictionary.
459
+ *
460
+ * @remarks The session dictionary is not persisted. It is available only
461
+ * during the actively running session. It is useful for storing temporary
462
+ * data to coordinate between activities.
463
+ *
464
+ * @param key - item key
465
+ * @returns value of the item
466
+ */
467
+ dictionaryGetItem<T extends SessionDictionaryValues>(key: string): T;
468
+ /**
469
+ * Deletes an item value from the session's key-value dictionary.
470
+ *
471
+ * @remarks The session dictionary is not persisted. It is available only
472
+ * during the actively running session. It is useful for storing temporary
473
+ * data to coordinate between activities.
474
+ *
475
+ * @param key - item key
476
+ * @returns true if the item was deleted, false if it did not exist
477
+ */
478
+ dictionaryDeleteItem(key: string): boolean;
479
+ /**
480
+ * Determines if a key exists in the activity's key-value dictionary.
481
+ *
482
+ * @remarks The session dictionary is not persisted. It is available only
483
+ * during the actively running session. It is useful for storing temporary
484
+ * data to coordinate between activities.
485
+ *
486
+ * @param key - item key
487
+ * @returns true if the key exists, false otherwise
488
+ */
489
+ dictionaryItemExists(key: string): boolean;
490
+ /**
491
+ * Gets asynchronous assets, including initialization of canvaskit wasm,
492
+ * fetching of fonts from specified urls, and rendering and fetching
493
+ * of images
494
+ * @returns
495
+ */
496
+ private getAsynchronousAssets;
497
+ private loadCanvasKit;
498
+ private loadAssets;
499
+ private assignCanvasKit;
500
+ private getFontsConfigurationFromGames;
501
+ private getImagesConfigurationFromGames;
502
+ }
503
+ interface GoToActivityOptions {
504
+ /** ActivityId of the activity to go to. */
505
+ id: string;
506
+ }
507
+ /**
508
+ * Types of values that can be stored in the session dictonary.
509
+ */
510
+ type SessionDictionaryValues = string | number | boolean | object | null | undefined;
511
+
512
+ interface Activity {
513
+ /** The type of activity: Game or Survey */
514
+ type: ActivityType;
515
+ /** Initializes the activity. All code to create the activity's appearance and behavior must be placed in this method. This method is asynchronous, and must be awaited. When writing a new game by extending the `Game` class, this method will be overridden, but the base method must still be called with `await super.init()`. */
516
+ init(): Promise<void>;
517
+ /** Starts the activity */
518
+ start(): Promise<void>;
519
+ /** Stops the activity */
520
+ stop(): void;
521
+ /** The activity's parent session */
522
+ session: Session;
523
+ /** The activity's unique identifier. NOTE: This is newly generated each session. The uuid for an activity will vary across sessions. */
524
+ uuid: string;
525
+ /** Human-friendly name of this activity */
526
+ name: string;
527
+ /** Short identifier of this activity */
528
+ id: string;
529
+ /** The value of performance.now() immediately before the activity begins */
530
+ beginTimestamp: number;
531
+ /** The value of new Date().toISOString() immediately before the activity begins */
532
+ beginIso8601Timestamp: string;
533
+ /** Sets additional activity parameters if defaults are not sufficient. */
534
+ setParameters(additionalParameters: unknown): void;
535
+ /** Additional activity parameters that were set. */
536
+ readonly additionalParameters?: unknown;
537
+ /** Optional store to use for saving data. The implementation of the store is not provided by the \@m2c2kit/core library. */
538
+ dataStore?: IDataStore;
539
+ }
540
+
541
+ /**
542
+ * Base interface for all m2c2kit events.
543
+ *
544
+ * @remarks I would have named it Event, but that would collide with
545
+ * the existing DOM Event
546
+ */
547
+ interface EventBase {
548
+ /** Type of event. */
549
+ type: EventType;
550
+ /** The object on which the event occurred. */
551
+ target: Entity | Session | Activity;
552
+ /** Has the event been taken care of by the listener and not be dispatched to other targets? */
553
+ handled?: boolean;
554
+ }
555
+ /**
556
+ * The different events that are dispatched by m2c2kit.
557
+ */
558
+ declare enum EventType {
559
+ SessionInitialize = "SessionInitialize",
560
+ SessionStart = "SessionStart",
561
+ SessionEnd = "SessionEnd",
562
+ ActivityStart = "ActivityStart",
563
+ ActivityEnd = "ActivityEnd",
564
+ ActivityCancel = "ActivityCancel",
565
+ ActivityData = "ActivityData",
566
+ TapDown = "TapDown",
567
+ TapUp = "TapUp",
568
+ TapUpAny = "TapUpAny",
569
+ TapLeave = "TapLeave",
570
+ PointerDown = "PointerDown",
571
+ PointerUp = "PointerUp",
572
+ PointerMove = "PointerMove",
573
+ Drag = "Drag",
574
+ DragStart = "DragStart",
575
+ DragEnd = "DragEnd",
576
+ CompositeCustom = "CompositeCustom"
577
+ }
578
+
579
+ /** Base interface for all Entity events. */
580
+ interface EntityEvent extends EventBase {
581
+ /** The Entity on which the event occurred. */
582
+ target: Entity;
583
+ /** For composites that raise events, type of the composite custom event. */
584
+ compositeType?: string;
585
+ }
586
+
587
+ interface EntityEventListener {
588
+ type: EventType;
589
+ /** For composites that raise events, type of the composite custom event. */
590
+ compositeType?: string;
591
+ entityUuid: string;
592
+ callback: (event: EntityEvent) => void;
593
+ }
594
+
595
+ /**
596
+ * Position in two-dimensional space.
597
+ */
598
+ interface Point {
599
+ /** Horizonal coordinate */
600
+ x: number;
601
+ /** Vertical coordinate */
602
+ y: number;
603
+ }
604
+
605
+ /**
606
+ * Describes an interaction between the pointer (mouse, touches) and an entity.
607
+ *
608
+ * @remarks I would have named it PointerEvent, but that would collide with
609
+ * the existing DOM PointerEvent.
610
+ */
611
+ interface M2PointerEvent extends EntityEvent {
612
+ /** Point that was tapped on entity, relative to the entity coordinate system */
613
+ point: Point;
614
+ /** Buttons being pressed when event was fired. Taken from DOM MouseEvent.buttons */
615
+ buttons: number;
616
+ }
617
+
618
+ /**
619
+ * Desrcibes an interaction of a pointer (mouse, touches) pressing an entity.
620
+ *
621
+ * @remarks Unlike M2PointerEvent, TapEvent considers how the pointer, while
622
+ * in the down state, moves in relation to the bounds of the entity.
623
+ */
624
+ interface TapEvent extends EntityEvent {
625
+ /** Point that was tapped on entity, relative to the entity coordinate system */
626
+ point: Point;
627
+ /** Buttons being pressed when event was fired. Taken from DOM MouseEvent.buttons */
628
+ buttons: number;
629
+ }
630
+
631
+ interface DrawableOptions {
632
+ /** Point within the entity that determines its position. Default is \{ x: 0.5, y: 0.5 \}, which centers the entity on its position */
633
+ anchorPoint?: Point;
634
+ /** Value along the z-axis to determine drawing and tap order. Larger values are on top. */
635
+ zPosition?: number;
636
+ }
637
+
638
+ /**
639
+ * Constraints for defining relative layouts.
640
+ *
641
+ * @remarks FOR INTERNAL USE ONLY
642
+ */
643
+ interface Constraints {
644
+ /** Constrain the top (vertical axis) of this entity to the top of the specified entity. The tops of both will appear at the same vertical location */
645
+ topToTopOf?: Entity | string;
646
+ /** Constrain the top (vertical axis) of this entity to the bottom of the specified entity. This entity will appear immediately below the specified entity */
647
+ topToBottomOf?: Entity | string;
648
+ /** Constrain the bottom (vertical axis) of this entity to the top of the specified entity. This entity will appear immediately above of the specified entity */
649
+ bottomToTopOf?: Entity | string;
650
+ /** Constrain the bottom (vertical axis) of this entity to the bottom of the specified entity. The bottoms of both will appear at the same vertical location */
651
+ bottomToBottomOf?: Entity | string;
652
+ /** Constrain the start (horizontal axis) of this entity to the start of the specified entity. The start of both will appear at the same horizontal location */
653
+ startToStartOf?: Entity | string;
654
+ /** Constrain the start (horizontal axis) of this entity to the end of the specified entity. This entity will appear immediately to the right of the specified entity */
655
+ startToEndOf?: Entity | string;
656
+ /** Constrain the end (horizontal axis) of this entity to the end of the specified entity. The end of both will appear at the same horizontal location */
657
+ endToEndOf?: Entity | string;
658
+ /** Constrain the end (horizontal axis) of this entity to the start of the specified entity. This entity will appear immediately to the left of the specified entity */
659
+ endToStartOf?: Entity | string;
660
+ /** When opposing horizontal constraints are applied, the default is to center the entity within the constraints (horizontalBias = .5). Setting horizontalBias less than .5 will pull the entity towards the start (to the left). Setting horizontalBias greater than .5 will pull the entity towards the end (to the right) */
661
+ horizontalBias?: number;
662
+ /** When opposing vertical constraints are applied, the default is to center the entity within the constraints (verticalBias = .5). Setting verticalBias less than .5 will pull the entity towards the top. Setting verticalBias greater than .5 will pull the entity towards the bottom */
663
+ verticalBias?: number;
664
+ [key: string]: Entity | string | number | undefined;
665
+ }
666
+
667
+ /**
668
+ * The Layout allows relative positioning via constraints.
669
+ * This is not fully implemented yet: DO NOT USE!
670
+ * We use it internally for instructions.
671
+ */
672
+ interface Layout {
673
+ height?: number;
674
+ width?: number;
675
+ marginStart?: number;
676
+ marginEnd?: number;
677
+ marginTop?: number;
678
+ marginBottom?: number;
679
+ constraints?: Constraints;
680
+ }
681
+
682
+ /**
683
+ * Color in red (0-255), green (0-255), blue (0-255), alpha (0-1) format. Must be numeric array of length 4.
684
+ */
685
+ type RgbaColor = [number, number, number, number];
686
+
687
+ interface TextOptions {
688
+ /** Text to be displayed */
689
+ text?: string;
690
+ /** Name of font to use for text. Must have been previously loaded */
691
+ fontName?: string;
692
+ /** Color of text. Default is Constants.DEFAULT_FONT_COLOR (WebColors.Black) */
693
+ fontColor?: RgbaColor;
694
+ /** Size of text. Default is Constants.DEFAULT_FONT_SIZE (16) */
695
+ fontSize?: number;
696
+ }
697
+
698
+ /**
699
+ * Width and height on two-dimensional space
700
+ */
701
+ interface Size {
702
+ /** Horizonal width, x-axis */
703
+ width: number;
704
+ /** Vertical height, y-axis */
705
+ height: number;
706
+ }
707
+
708
+ interface EntityOptions {
709
+ /** Name of the entity. Only needed if the entity will be referred to by name in a later function */
710
+ name?: string;
711
+ /** Position of the entity within its parent coordinate system. Default is (0, 0) */
712
+ position?: Point;
713
+ /** Scale of the entity. Default is 1.0 */
714
+ scale?: number;
715
+ /** Does the entity respond to user events, such as taps? Default is false */
716
+ isUserInteractionEnabled?: boolean;
717
+ /** Can the entity be dragged? */
718
+ draggable?: boolean;
719
+ /** Is the entity, and its children, hidden? (not displayed). Default is false */
720
+ hidden?: boolean;
721
+ /** FOR INTERNAL USE ONLY */
722
+ layout?: Layout;
723
+ }
724
+
725
+ declare enum EntityType {
726
+ Entity = "Entity",
727
+ Scene = "Scene",
728
+ Sprite = "Sprite",
729
+ Label = "Label",
730
+ TextLine = "TextLine",
731
+ Shape = "Shape",
732
+ Composite = "Composite"
733
+ }
734
+
735
+ type EasingFunction = (
736
+ /** elapsed time since start of action */
737
+ t: number,
738
+ /** start value of value to be eased */
739
+ b: number,
740
+ /** total change of value to be eased */
741
+ c: number,
742
+ /** total duration of action */
743
+ d: number) => number;
744
+ /**
745
+ * The Easings class has static methods for creating easings to be used in actions.
746
+ */
747
+ declare class Easings {
748
+ static none: EasingFunction;
749
+ static linear: EasingFunction;
750
+ static quadraticIn: EasingFunction;
751
+ static quadraticOut: EasingFunction;
752
+ static quadraticInOut: EasingFunction;
753
+ static cubicIn: EasingFunction;
754
+ static cubicOut: EasingFunction;
755
+ static cubicInOut: EasingFunction;
756
+ static quarticIn: EasingFunction;
757
+ static quarticOut: EasingFunction;
758
+ static quarticInOut: EasingFunction;
759
+ static quinticIn: EasingFunction;
760
+ static quinticOut: EasingFunction;
761
+ static quinticInOut: EasingFunction;
762
+ static sinusoidalIn: EasingFunction;
763
+ static sinusoidalOut: EasingFunction;
764
+ static sinusoidalInOut: EasingFunction;
765
+ static exponentialIn: EasingFunction;
766
+ static exponentialOut: EasingFunction;
767
+ static exponentialInOut: EasingFunction;
768
+ static circularIn: EasingFunction;
769
+ static circularOut: EasingFunction;
770
+ static circularInOut: EasingFunction;
771
+ }
772
+
773
+ interface IDrawable {
774
+ draw(canvas: Canvas): void;
775
+ warmup(canvas: Canvas): void;
776
+ /**
777
+ * Frees up resources that were allocated for this drawable entity.
778
+ *
779
+ * @remarks This will be done automatically by the m2c2kit library;
780
+ * the end-user must not call this.
781
+ */
782
+ dispose(): void;
783
+ anchorPoint: Point;
784
+ zPosition: number;
785
+ }
786
+
787
+ interface SceneOptions extends EntityOptions, DrawableOptions {
788
+ /** Background color of the scene. Default is Constants.DEFAULT_SCENE_BACKGROUND_COLOR (WebColors.White) */
789
+ backgroundColor?: RgbaColor;
790
+ }
791
+
792
+ declare class Scene extends Entity implements IDrawable, SceneOptions {
793
+ readonly type = EntityType.Scene;
794
+ isDrawable: boolean;
795
+ anchorPoint: {
796
+ x: number;
797
+ y: number;
798
+ };
799
+ zPosition: number;
800
+ private _backgroundColor;
801
+ _active: boolean;
802
+ _transitioning: boolean;
803
+ _setupCallback?: (scene: Scene) => void;
804
+ _appearCallback?: (scene: Scene) => void;
805
+ private backgroundPaint?;
806
+ /**
807
+ * Top-level entity that holds all other entities, such as sprites, rectangles, or labels, that will be displayed on the screen
808
+ *
809
+ * @remarks The scene is the game screen or stage, and fills the entire available screen. There are usually multiple screens to contain multiple stages of the game, such as various instruction pages or phases of a game.
810
+ *
811
+ * @param options - {@link SceneOptions}
812
+ */
813
+ constructor(options?: SceneOptions);
814
+ initialize(): void;
815
+ dispose(): void;
816
+ set game(game: Game);
817
+ /**
818
+ * The game which this scene is a part of.
819
+ *
820
+ * @remarks Throws error if scene is not part of the game object.
821
+ */
822
+ get game(): Game;
823
+ get backgroundColor(): RgbaColor;
824
+ set backgroundColor(backgroundColor: RgbaColor);
825
+ /**
826
+ * Duplicates an entity using deep copy.
827
+ *
828
+ * @remarks This is a deep recursive clone (entity and children).
829
+ * The uuid property of all duplicated entities will be newly created,
830
+ * because uuid must be unique.
831
+ *
832
+ * @param newName - optional name of the new, duplicated entity. If not
833
+ * provided, name will be the new uuid
834
+ */
835
+ duplicate(newName?: string): Scene;
836
+ /**
837
+ * Code that will be called every time the scene is presented.
838
+ *
839
+ * @remarks Use this callback to set entities to their initial state, if
840
+ * that state might be changed later. For example, if a scene allows
841
+ * players to place dots on a grid, the setup() method should ensure the
842
+ * grid is clear of any prior dots from previous times this scene may
843
+ * have been displayed. In addition, if entities should vary in each
844
+ * iteration, that should be done here.
845
+ *
846
+ * @param callback
847
+ */
848
+ onSetup(callback: (scene: Scene) => void): void;
849
+ /**
850
+ *
851
+ * Code that will be called after the scene has finished any transitions
852
+ * and has fully appeared on the screen.
853
+ *
854
+ * @param callback
855
+ */
856
+ onAppear(callback: (scene: Scene) => void): void;
857
+ draw(canvas: Canvas): void;
858
+ warmup(canvas: Canvas): void;
859
+ }
860
+
861
+ interface SlideTransitionOptions {
862
+ /** Direction in which the slide action goes */
863
+ direction: TransitionDirection;
864
+ /** Duration, in millis, of the transition */
865
+ duration: number;
866
+ /** Easing function for movement; default is linear */
867
+ easing?: EasingFunction;
868
+ }
869
+ /**
870
+ * The Transition class has static methods for creating animations that run as one scene transitions to another.
871
+ */
872
+ declare abstract class Transition {
873
+ abstract type: TransitionType;
874
+ abstract easing: EasingFunction;
875
+ abstract duration: number;
876
+ /**
877
+ * Creates a scene transition in which the outgoing scene slides out and the incoming scene slides in, as if the incoming scene pushes it.
878
+ *
879
+ * @param options - {@link SlideTransitionOptions}
880
+ * @returns
881
+ */
882
+ static slide(options: SlideTransitionOptions): SlideTransition;
883
+ /**
884
+ * Creates a scene transition with no animation or duration. The next scene is immediately drawn.
885
+ */
886
+ static none(): NoneTransition;
887
+ }
888
+ declare class NoneTransition extends Transition {
889
+ type: TransitionType;
890
+ easing: EasingFunction;
891
+ duration: number;
892
+ constructor();
893
+ }
894
+ declare class SlideTransition extends Transition {
895
+ type: TransitionType;
896
+ easing: EasingFunction;
897
+ duration: number;
898
+ direction: TransitionDirection;
899
+ constructor(direction: TransitionDirection, duration: number, easing: EasingFunction);
900
+ }
901
+ declare enum TransitionType {
902
+ Slide = "Slide",
903
+ None = "None"
904
+ }
905
+ declare enum TransitionDirection {
906
+ Up = "Up",
907
+ Down = "Down",
908
+ Right = "Right",
909
+ Left = "Left"
910
+ }
911
+ declare class SceneTransition {
912
+ scene: Scene;
913
+ transition: Transition;
914
+ constructor(scene: Scene, transition: Transition);
915
+ }
916
+
917
+ /**
918
+ * TrialSchema defines the data that are generated for each trial. They are
919
+ * key-value pairs in which the key is the variable name, and the value is
920
+ * JSON Schema that defines the type of the variable.
921
+ */
922
+ interface TrialSchema {
923
+ [key: string]: JsonSchema;
924
+ }
925
+
926
+ /**
927
+ * GameParameters are the configurable options that change how the game runs.
928
+ * They are key-value pairs in which the key is the game parameter name, and
929
+ * the value is JSON Schema that defines the type of the game parameter, with
930
+ * a required parameter named "default" that is the default value for the
931
+ * parameter.
932
+ */
933
+ interface GameParameters {
934
+ /** The key is the game parameter name */
935
+ [key: string]: DefaultParameter;
936
+ }
937
+ interface DefaultParameter extends JsonSchema {
938
+ /** Default value for the game parameter. */
939
+ default: any;
940
+ }
941
+
942
+ /**
943
+ * Translations is a map of a locale to a map of keys to translations.
944
+ *
945
+ * @example
946
+ * ```
947
+ * const translations: Translations = {
948
+ * "en-US": {
949
+ * "NEXT_BUTTON": "Next"
950
+ * },
951
+ * "es-MX": {
952
+ * "NEXT_BUTTON": "Siguiente"
953
+ * }
954
+ * }
955
+ * ```
956
+ */
957
+ interface Translations {
958
+ [locale: string]: {
959
+ [key: string]: string;
960
+ };
961
+ }
962
+
963
+ /**
964
+ * Options to specify HTML canvas, set game canvas size, and load game assets.
965
+ */
966
+ interface GameOptions {
967
+ /** Human-friendly name of this game */
968
+ name: string;
969
+ /** Short identifier of this game; unique among published games and url-friendly (no spaces, special characters, or slashes)*/
970
+ id: string;
971
+ /** Version of this game */
972
+ version: string;
973
+ /** Uri (repository, webpage, or other location where full information about the game can be found) */
974
+ uri?: string;
975
+ /** Brief description of game */
976
+ shortDescription?: string;
977
+ /** Full description of game */
978
+ longDescription?: string;
979
+ /** Id of the HTML canvas that game will be drawn on. If not provided, the first canvas found will be used */
980
+ canvasId?: string;
981
+ /** Width of game canvas */
982
+ width: number;
983
+ /** Height of game canvas */
984
+ height: number;
985
+ /** Stretch to fill screen? Default is false */
986
+ stretch?: boolean;
987
+ /** Schema of trial data; JSON object where key is variable name, value is data type */
988
+ trialSchema?: TrialSchema;
989
+ /** Default game parameters; JSON object where key is the game parameter, value is default value */
990
+ parameters?: GameParameters;
991
+ /** String array of urls from which to load fonts. The first element will be the default font */
992
+ fontUrls?: Array<string>;
993
+ /** Array of BrowserImage objects to render and load */
994
+ images?: Array<BrowserImage>;
995
+ /** Show FPS in upper left corner? Default is false */
996
+ showFps?: boolean;
997
+ /** Color of the html body, if the game does not fill the screen. Useful for showing scene boundaries. Default is the scene background color */
998
+ bodyBackgroundColor?: RgbaColor;
999
+ /** Maximum number of activity metrics to log. */
1000
+ maximumRecordedActivityMetrics?: number;
1001
+ /** The FPS will be logged in game metrics if the FPS is lower than this value. Default is 59, as defined in Constants.FPS_METRIC_REPORT_THRESHOLD */
1002
+ fpsMetricReportThreshold?: number;
1003
+ /** Adapt execution for unit testing? Default is false */
1004
+ _unitTesting?: boolean;
1005
+ /** Advance through time step-by-step, for development and debugging */
1006
+ timeStepping?: boolean;
1007
+ /** Translations for localization. */
1008
+ translations?: Translations;
1009
+ /** Show logs for WebGl activity? */
1010
+ logWebGl?: boolean;
1011
+ }
1012
+
1013
+ interface GameData extends ActivityKeyValueData {
1014
+ trials: Array<TrialData>;
1015
+ }
1016
+
1017
+ /**
1018
+ * Localization information that is passed to the I18n constructor.
1019
+ */
1020
+ interface LocalizationOptions {
1021
+ /** Locale to use for localization, or "auto" to request from the environment. */
1022
+ locale: string;
1023
+ /** Locale to use if requested locale translation is not availble, or if "auto" locale was requested and environment cannot provide a locale. */
1024
+ fallbackLocale?: string;
1025
+ /** Font color for strings that are missing translation and use the fallback locale or untranslated string. */
1026
+ missingTranslationFontColor?: RgbaColor;
1027
+ /** Translations for localization. */
1028
+ translations?: Translations;
1029
+ /** Additional translations for localization provided through game parameters. These will be merged into existing translations. */
1030
+ additionalTranslations?: Translations;
1031
+ }
1032
+
1033
+ declare class I18n {
1034
+ private _translations;
1035
+ locale: string;
1036
+ fallbackLocale: string;
1037
+ private environmentLocale;
1038
+ options: LocalizationOptions;
1039
+ static makeLocalizationParameters(): GameParameters;
1040
+ constructor(options: LocalizationOptions);
1041
+ t(key: string, useFallback?: boolean): string | undefined;
1042
+ get translations(): Translations;
1043
+ set translations(value: Translations);
1044
+ private getEnvironmentLocale;
1045
+ private mergeAdditionalTranslations;
1046
+ }
1047
+
1048
+ interface TrialData {
1049
+ [key: string]: string | number | boolean | object | undefined | null;
1050
+ }
1051
+ declare class Game implements Activity {
1052
+ readonly type = ActivityType.Game;
1053
+ _canvasKit?: CanvasKit;
1054
+ _session?: Session;
1055
+ uuid: string;
1056
+ name: string;
1057
+ id: string;
1058
+ options: GameOptions;
1059
+ beginTimestamp: number;
1060
+ beginIso8601Timestamp: string;
1061
+ private gameMetrics;
1062
+ private fpsMetricReportThreshold;
1063
+ private maximumRecordedActivityMetrics;
1064
+ private stepCount;
1065
+ private steppingNow;
1066
+ i18n?: I18n;
1067
+ private warmupFunctionQueue;
1068
+ private loaderElementsRemoved;
1069
+ private _dataStore?;
1070
+ additionalParameters?: unknown;
1071
+ /**
1072
+ * The base class for all games. New games should extend this class.
1073
+ *
1074
+ * @param options - {@link GameOptions}
1075
+ */
1076
+ constructor(options: GameOptions);
1077
+ private addLocalizationParametersToGameParameters;
1078
+ init(): Promise<void>;
1079
+ /**
1080
+ * Saves an item to the activity's key-value store.
1081
+ *
1082
+ * @remarks The underlying persistence provider of the key-value store must
1083
+ * be previously set in the activity's `Session` before use:
1084
+ * ```
1085
+ * const db: IDataStore = new LocalDatabase();
1086
+ * session.dataStore = db;
1087
+ * session.init();
1088
+ * ```
1089
+ * @param key - item key
1090
+ * @param value - item value
1091
+ * @param globalStore - if true, treat the item as "global" and not
1092
+ * associated with a specific activity; global items can be accessed
1093
+ * by any activity. Default is false.
1094
+ * @returns key
1095
+ */
1096
+ storeSetItem(key: string, value: string | number | boolean | object | undefined | null, globalStore?: boolean): Promise<string>;
1097
+ /**
1098
+ * Gets an item value from the activity's key-value store.
1099
+ *
1100
+ * @remarks The underlying persistence provider of the key-value store must
1101
+ * be previously set in the activity's `Session` before use:
1102
+ * ```
1103
+ * const db: IDataStore = new LocalDatabase();
1104
+ * session.dataStore = db;
1105
+ * session.init();
1106
+ * ```
1107
+ * @param key - item key
1108
+ * @param globalStore - if true, treat the item as "global" and not
1109
+ * associated with a specific activity; global items can be accessed
1110
+ * by any activity. Default is false.
1111
+ * @returns value of the item
1112
+ */
1113
+ storeGetItem<T extends string | number | boolean | object | undefined | null>(key: string, globalStore?: boolean): Promise<T>;
1114
+ /**
1115
+ * Deletes an item value from the activity's key-value store.
1116
+ *
1117
+ * @remarks The underlying persistence provider of the key-value store must
1118
+ * be previously set in the activity's `Session` before use:
1119
+ * ```
1120
+ * const db: IDataStore = new LocalDatabase();
1121
+ * session.dataStore = db;
1122
+ * session.init();
1123
+ * ```
1124
+ * @param key - item key
1125
+ * @param globalStore - if true, treat the item as "global" and not
1126
+ * associated with a specific activity; global items can be accessed
1127
+ * by any activity. Default is false.
1128
+ */
1129
+ storeDeleteItem(key: string, globalStore?: boolean): Promise<void>;
1130
+ /**
1131
+ * Deletes all items from the activity's key-value store.
1132
+ *
1133
+ * @remarks The underlying persistence provider of the key-value store must
1134
+ * be previously set in the activity's `Session` before use:
1135
+ * ```
1136
+ * const db: IDataStore = new LocalDatabase();
1137
+ * session.dataStore = db;
1138
+ * session.init();
1139
+ * ```
1140
+ */
1141
+ storeClearItems(): Promise<void>;
1142
+ /**
1143
+ * Returns keys of all items in the activity's key-value store.
1144
+ *
1145
+ * @remarks The underlying persistence provider of the key-value store must
1146
+ * be previously set in the activity's `Session` before use:
1147
+ * ```
1148
+ * const db: IDataStore = new LocalDatabase();
1149
+ * session.dataStore = db;
1150
+ * session.init();
1151
+ * ```
1152
+ * @param globalStore - if true, treat the item as "global" and not
1153
+ * associated with a specific activity; global items can be accessed
1154
+ * by any activity. Default is false.
1155
+ */
1156
+ storeItemsKeys(globalStore?: boolean): Promise<string[]>;
1157
+ /**
1158
+ * Determines if a key exists in the activity's key-value store.
1159
+ *
1160
+ * @remarks The underlying persistence provider of the key-value store must
1161
+ * be previously set in the activity's `Session` before use:
1162
+ * ```
1163
+ * const db: IDataStore = new LocalDatabase();
1164
+ * session.dataStore = db;
1165
+ * session.init();
1166
+ * ```
1167
+ * @param key - item key
1168
+ * @param globalStore - if true, treat the item as "global" and not
1169
+ * associated with a specific activity; global items can be accessed
1170
+ * by any activity. Default is false.
1171
+ * @returns true if the key exists, false otherwise
1172
+ */
1173
+ storeItemExists(key: string, globalStore?: boolean): Promise<boolean>;
1174
+ get dataStore(): IDataStore;
1175
+ set dataStore(dataStore: IDataStore);
1176
+ private getLocalizationOptionsFromGameParameters;
1177
+ private isLocalizationRequested;
1178
+ setParameters(additionalParameters: unknown): void;
1179
+ get canvasKit(): CanvasKit;
1180
+ set canvasKit(canvasKit: CanvasKit);
1181
+ get session(): Session;
1182
+ set session(session: Session);
1183
+ /** The scene, or its name as a string, to be presented when the game is started. If this is undefined, the game will start with the first scene that has been added */
1184
+ entryScene?: Scene | string;
1185
+ data: GameData;
1186
+ /** The 0-based index of the current trial */
1187
+ trialIndex: number;
1188
+ private htmlCanvas?;
1189
+ surface?: Surface;
1190
+ private showFps?;
1191
+ private bodyBackgroundColor?;
1192
+ private currentScene?;
1193
+ private priorUpdateTime?;
1194
+ private fpsTextFont?;
1195
+ private fpsTextPaint?;
1196
+ private drawnFrames;
1197
+ private lastFpsUpdate;
1198
+ private nextFpsUpdate;
1199
+ private fpsRate;
1200
+ private animationFramesRequested;
1201
+ private limitFps;
1202
+ private unitTesting;
1203
+ private gameStopRequested;
1204
+ private webGlRendererInfo;
1205
+ canvasCssWidth: number;
1206
+ canvasCssHeight: number;
1207
+ scenes: Scene[];
1208
+ private freeEntitiesScene;
1209
+ private incomingSceneTransitions;
1210
+ private currentSceneSnapshot?;
1211
+ private pendingScreenshot?;
1212
+ /**
1213
+ * Adds an entity as a free entity (an entity that is not part of a scene)
1214
+ * to the game.
1215
+ *
1216
+ * @remarks Once added to the game, a free entity will always be drawn,
1217
+ * and it will not be part of any scene transitions. This is useful if
1218
+ * an entity must persisently be drawn and not move with scene
1219
+ * transitions. The appearance of the free entity must be managed
1220
+ * by the programmer. Note: internally, the free entities are part of a
1221
+ * special scene (named "__freeEntitiesScene"), but this scene is handled
1222
+ * apart from regular scenes in order to achieve the free entity behavior.
1223
+ *
1224
+ * @param entity - entity to add as a free entity
1225
+ */
1226
+ addFreeEntity(entity: Entity): void;
1227
+ /**
1228
+ * Removes a free entity from the game.
1229
+ *
1230
+ * @remarks Throws exception if the entity to remove is not currently added
1231
+ * to the game as a free entity
1232
+ *
1233
+ * @param entity - the free entity to remove or its name as a string
1234
+ */
1235
+ removeFreeEntity(entity: Entity | string): void;
1236
+ /**
1237
+ * Removes all free entities from the game.
1238
+ */
1239
+ removeAllFreeEntities(): void;
1240
+ /**
1241
+ * Returns array of free entities that have been added to the game.
1242
+ *
1243
+ * @returns array of free entities
1244
+ */
1245
+ get freeEntities(): Array<Entity>;
1246
+ /**
1247
+ * Adds a scene to the game.
1248
+ *
1249
+ * @remarks A scene, and its children entities, cannot be presented unless it has been added to the game object.
1250
+ *
1251
+ * @param scene
1252
+ */
1253
+ addScene(scene: Scene): void;
1254
+ /**
1255
+ * Adds multiple scenes to the game.
1256
+ *
1257
+ * @param scenes
1258
+ */
1259
+ addScenes(scenes: Array<Scene>): void;
1260
+ /**
1261
+ * Removes a scene from the game.
1262
+ *
1263
+ * @param scene - the scene to remove or its name as a string
1264
+ */
1265
+ removeScene(scene: Scene | string): void;
1266
+ /**
1267
+ * Specifies the scene that will be presented upon the next frame draw.
1268
+ *
1269
+ * @param scene
1270
+ * @param transition
1271
+ */
1272
+ presentScene(scene: string | Scene, transition?: NoneTransition): void;
1273
+ /**
1274
+ * Gets the value of the game parameter. If parameterName
1275
+ * is not found, then throw exception.
1276
+ *
1277
+ * @param parameterName - the name of the game parameter whose value is requested
1278
+ * @returns
1279
+ */
1280
+ getParameter<T>(parameterName: string): T;
1281
+ /**
1282
+ * Gets the value of the game parameter. If parameterName
1283
+ * is not found, then return fallback value
1284
+ *
1285
+ * @param parameterName - the name of the game parameter whose value is requested
1286
+ * @param fallback - the value to return if parameterName is not found
1287
+ * @returns
1288
+ */
1289
+ getParameterOrFallback<T, U>(parameterName: string, fallbackValue: U): T | U;
1290
+ /**
1291
+ * Returns true if a game parameter exists for the given string.
1292
+ *
1293
+ * @param parameterName - the name of the game parameter whose existence is queried
1294
+ * @returns
1295
+ */
1296
+ hasParameter(parameterName: string): boolean;
1297
+ /**
1298
+ * Starts the game loop.
1299
+ *
1300
+ * @remarks If entryScene is undefined, the game will start with scene
1301
+ * defined in the game object's entryScene property. If that is undefined,
1302
+ * the game will start with the first scene in the game object's scenes.
1303
+ * If there are no scenes in the game object's scenes, it will throw
1304
+ * an error.
1305
+ * Although the method has no awaitable calls, we will likely do
1306
+ * so in the future. Thus this method is async.
1307
+ *
1308
+ * @param entryScene - The scene (Scene object or its string name) to display when the game starts
1309
+ */
1310
+ start(entryScene?: Scene | string): Promise<void>;
1311
+ private addTimeSteppingControlsToDom;
1312
+ private updateTimeSteppingOutput;
1313
+ private advanceStepsHandler;
1314
+ private removeTimeSteppingControlsFromDom;
1315
+ /**
1316
+ * Warms up the Skia-based shaders underlying canvaskit by drawing
1317
+ * primitives.
1318
+ *
1319
+ * @remarks Some canvaskit methods take extra time the first time they are
1320
+ * called because a WebGL shader must be compiled. If the method is part of
1321
+ * an animation, then this may cause frame drops or "jank." To alleviate
1322
+ * this, we can "warm up" the shader associated with the method by calling
1323
+ * it at the beginning of our game. Thus, all warmup operations will be
1324
+ * concentrated at the beginning and will not be noticeable. This warmup
1325
+ * function draws a series of primitives to the canvas. From testing,
1326
+ * the actual WebGl shaders compiled by canvaskit vary depending on the
1327
+ * device hardware. Thus, warmup functions that might call all relevant
1328
+ * WebGL shaders on desktop hardware may not be sufficient for mobile.
1329
+ *
1330
+ * @param canvas - the canvaskit-canvas to draw on
1331
+ * @param positionOffset - an offset to add to the position of each
1332
+ * primitive. Different shaders may be compiled depending on if the position
1333
+ * was fractional or not. This offset allows us to warmup both cases.
1334
+ */
1335
+ private warmupShadersWithPrimitives;
1336
+ /**
1337
+ * Warms up the Skia-based shaders underlying canvaskit by drawing
1338
+ * m2c2kit entities.
1339
+ *
1340
+ * @remarks While warmupShadersWithPrimitives draws a predefined set of
1341
+ * primitives, this function initializes and draws all canvaskit objects
1342
+ * that have been defined as m2c2kit entities. This not only is another
1343
+ * opportunity for shader warmup, it also does the entity initialization.
1344
+ *
1345
+ * @param canvas - the canvaskit-canvas to draw on
1346
+ */
1347
+ private warmupShadersWithScenes;
1348
+ stop(): void;
1349
+ /**
1350
+ * Frees up resources that were allocated to run the game.
1351
+ *
1352
+ * @remarks This will be done automatically by the m2c2kit library;
1353
+ * the end-user must not call this.
1354
+ */
1355
+ dispose(): void;
1356
+ private initData;
1357
+ private propertySchemaDataTypeIsValid;
1358
+ private getDeviceMetadata;
1359
+ /**
1360
+ * Adds data to the game's TrialData object.
1361
+ *
1362
+ * @remarks The variableName must be previously defined in the trialSchema
1363
+ * object passed in during game initialization through
1364
+ * {@link GameInitOptions.trialSchema}. The type of the value must match
1365
+ * what was defined in the trialSchema, otherwise an error is thrown.
1366
+ *
1367
+ * @param variableName - variable to be set
1368
+ * @param value - value of the variable to set
1369
+ */
1370
+ addTrialData(variableName: string, value: any): void;
1371
+ /**
1372
+ * Should be called when the current trial has completed. It will
1373
+ * also increment the trial index.
1374
+ *
1375
+ * @remarks Calling will trigger the onActivityResults callback function,
1376
+ * if one was provided in SessionOptions. This is how the game communicates
1377
+ * trial data to the parent session, which can then save or process the data.
1378
+ * It is the responsibility of the the game programmer to call this at
1379
+ * the appropriate time. It is not triggered automatically.
1380
+ */
1381
+ trialComplete(): void;
1382
+ /**
1383
+ * The m2c2kit engine will automatically include these schema and their
1384
+ * values in the trial data.
1385
+ */
1386
+ private readonly automaticTrialSchema;
1387
+ private makeNewGameDataSchema;
1388
+ private makeGameDataSchema;
1389
+ /**
1390
+ * GameParameters combines default parameters values and
1391
+ * JSON Schema to describe what the parameters are.
1392
+ * The next two functions extract GameParameters's two parts
1393
+ * (the default values and the schema) so they can be returned
1394
+ * separately in the activityData event
1395
+ */
1396
+ private makeGameActivityConfiguration;
1397
+ private makeGameActivityConfigurationSchema;
1398
+ /**
1399
+ * Should be called when current game has ended successfully.
1400
+ *
1401
+ * @remarks This will trigger the onActivityLifecycleChange callback function,
1402
+ * if one was provided in SessionOptions. This is how the game can communicate
1403
+ * its state to the parent session. It is the responsibility of the the game
1404
+ * programmer to call this at the appropriate time. It is not triggered
1405
+ * automatically.
1406
+ */
1407
+ end(): void;
1408
+ /**
1409
+ * Should be called when current game has been canceled by a user action.
1410
+ *
1411
+ * @remarks This will trigger the onActivityLifecycleChange callback function,
1412
+ * if one was provided in SessionOptions. This is how the game can communicate
1413
+ * its state to the parent session. It is the responsibility of the the game
1414
+ * programmer to call this at the appropriate time. It is not triggered
1415
+ * automatically.
1416
+ */
1417
+ cancel(): void;
1418
+ private setupHtmlCanvases;
1419
+ private setupCanvasKitSurface;
1420
+ private interceptWebGlCalls;
1421
+ private setupFpsFont;
1422
+ private setupCanvasDomEventHandlers;
1423
+ private loop;
1424
+ snapshots: Image[];
1425
+ private updateGameTime;
1426
+ private handleIncomingSceneTransitions;
1427
+ /**
1428
+ * Creates a scene that has a screen shot of the current scene.
1429
+ *
1430
+ * @param outgoingSceneImage - an image of the current scene
1431
+ * @returns - the scene with the screen shot
1432
+ */
1433
+ private createOutgoingScene;
1434
+ private update;
1435
+ private draw;
1436
+ private calculateFps;
1437
+ private takeCurrentSceneSnapshot;
1438
+ private handlePendingScreenshot;
1439
+ /**
1440
+ * Takes screenshot of canvas
1441
+ *
1442
+ * @remarks Coordinates should be provided unscaled; that is, the method
1443
+ * will handle any scaling that happened due to device pixel ratios
1444
+ * not equal to 1. This returns a promise because the screenshot request
1445
+ * must be queued and completed once a draw cycle has completed. See
1446
+ * the loop() method.
1447
+ *
1448
+ * @param sx - Upper left coordinate of screenshot
1449
+ * @param sy - Upper right coordinate of screenshot
1450
+ * @param sw - width of area to screenshot
1451
+ * @param sh - hegith of area to screenshot
1452
+ * @returns Promise of Uint8Array of image data
1453
+ */
1454
+ takeScreenshot(sx?: number, sy?: number, sw?: number, sh?: number): Promise<Uint8Array | null>;
1455
+ private animateSceneTransition;
1456
+ private drawFps;
1457
+ /**
1458
+ * Creates an event listener for an entity based on the entity name
1459
+ *
1460
+ * @remarks Typically, event listeners will be created using a method specific to the event, such as onTapDown(). This alternative allows creation with entity name.
1461
+ *
1462
+ * @param type - the type of event to listen for, e.g., "tapdown"
1463
+ * @param entityName - the entity name for which an event will be listened
1464
+ * @param callback
1465
+ * @param replaceExistingCallback
1466
+ */
1467
+ createEventListener(type: EventType, entityName: string, callback: (event: EntityEvent) => void, replaceExistingCallback?: boolean): void;
1468
+ /**
1469
+ * Returns array of all entities that have been added to the game object.
1470
+ */
1471
+ get entities(): Array<Entity>;
1472
+ /**
1473
+ * Receives callback from DOM PointerDown event
1474
+ *
1475
+ * @param domPointerEvent - PointerEvent from the DOM
1476
+ * @returns
1477
+ */
1478
+ private htmlCanvasPointerDownHandler;
1479
+ private htmlCanvasPointerUpHandler;
1480
+ private htmlCanvasPointerMoveHandler;
1481
+ /**
1482
+ * Adjusts dragging behavior when the pointer leaves the canvas
1483
+ *
1484
+ * @remarks This is necessary because the pointerup event is not fired when
1485
+ * the pointer leaves the canvas. On desktop, this means that the user might
1486
+ * lift the pointer outside the canvas, but the entity will still be dragged
1487
+ * when the pointer is moved back into the canvas.
1488
+ *
1489
+ * @param domPointerEvent
1490
+ * @returns
1491
+ */
1492
+ private htmlCanvasPointerLeaveHandler;
1493
+ /**
1494
+ * Determines if/how m2c2kit entities respond to the DOM PointerDown event
1495
+ *
1496
+ * @param entity - entity that might be affected by the DOM PointerDown event
1497
+ * @param m2Event
1498
+ * @param domPointerEvent
1499
+ */
1500
+ private processDomPointerDown;
1501
+ private processDomPointerUp;
1502
+ private processDomPointerMove;
1503
+ private raiseM2PointerDownEvent;
1504
+ private raiseTapDownEvent;
1505
+ private raiseTapLeaveEvent;
1506
+ private raiseM2PointerUpEvent;
1507
+ private raiseTapUpEvent;
1508
+ private raiseTapUpAny;
1509
+ private raiseM2PointerMoveEvent;
1510
+ private raiseM2DragStartEvent;
1511
+ private raiseM2DragEvent;
1512
+ private raiseM2DragEndEvent;
1513
+ private calculatePointWithinEntityFromDomPointerEvent;
1514
+ private raiseEventOnListeningEntities;
1515
+ private sceneCanReceiveUserInteraction;
1516
+ /**
1517
+ *
1518
+ * Checks if the given canvas point is within the entity's bounds.
1519
+ *
1520
+ * @param entity - entity to check bounds for
1521
+ * @param x - x coordinate of the canvas point
1522
+ * @param y - y coordinate of the canvas point
1523
+ * @returns true if x, y point is within the entity's bounds
1524
+ */
1525
+ private IsCanvasPointWithinEntityBounds;
1526
+ private calculateEntityAbsoluteBoundingBox;
1527
+ }
1528
+
1529
+ /**
1530
+ * Describes a drag and drop operation.
1531
+ *
1532
+ * @remarks I would have named it DragEvent, but that would collide with
1533
+ * the existing DOM DragEvent.
1534
+ */
1535
+ interface M2DragEvent extends EntityEvent {
1536
+ /** Position of the entity at the time of the M2DragEvent, relative to the parent entity coordinate system. */
1537
+ position: Point;
1538
+ /** Buttons being pressed when event was fired. Taken from DOM MouseEvent.buttons. */
1539
+ buttons: number;
1540
+ }
1541
+
1542
+ declare function handleInterfaceOptions(entity: Entity, options: EntityOptions): void;
1543
+ declare abstract class Entity implements EntityOptions {
1544
+ type: EntityType;
1545
+ isDrawable: boolean;
1546
+ isShape: boolean;
1547
+ isText: boolean;
1548
+ name: string;
1549
+ position: Point;
1550
+ scale: number;
1551
+ isUserInteractionEnabled: boolean;
1552
+ draggable: boolean;
1553
+ hidden: boolean;
1554
+ layout: Layout;
1555
+ _game?: Game;
1556
+ parent?: Entity;
1557
+ children: Entity[];
1558
+ absolutePosition: Point;
1559
+ size: Size;
1560
+ absoluteScale: number;
1561
+ actions: Action[];
1562
+ queuedAction?: Action;
1563
+ originalActions: Action[];
1564
+ eventListeners: EntityEventListener[];
1565
+ readonly uuid: string;
1566
+ needsInitialization: boolean;
1567
+ userData: any;
1568
+ loopMessages: Set<string>;
1569
+ /** Is the entity in a pressed state? E.g., did the user put the pointer
1570
+ * down on the entity and not yet release it? */
1571
+ pressed: boolean;
1572
+ /** Is the entity in a pressed state AND is the pointer within the entity's
1573
+ * hit area? For example, a user may put the pointer down on the entity, but
1574
+ * then move the pointer, while still down, beyond the entity's hit area. In
1575
+ * this case, pressed = true, but pressedAndWithinHitArea = false. */
1576
+ pressedAndWithinHitArea: boolean;
1577
+ /** When the entity initially enters the pressed state, what is the pointer
1578
+ * offset? (offset from the canvas's origin to the pointer position). We
1579
+ * save this because it will be needed if this press then led to a drag. */
1580
+ pressedInitialPointerOffset: Point;
1581
+ /** What was the previous pointer offset when the entity was in a dragging
1582
+ * state? */
1583
+ draggingLastPointerOffset: Point;
1584
+ /** Is the entity in a dragging state? */
1585
+ dragging: boolean;
1586
+ constructor(options?: EntityOptions);
1587
+ initialize(): void;
1588
+ /**
1589
+ * The game which this entity is a part of.
1590
+ *
1591
+ * @remarks Throws error if entity is not part of the game object.
1592
+ */
1593
+ get game(): Game;
1594
+ /**
1595
+ * Overrides toString() and returns a human-friendly description of the entity.
1596
+ *
1597
+ * @remarks Inspiration from https://stackoverflow.com/a/35361695
1598
+ */
1599
+ toString: () => string;
1600
+ /**
1601
+ * Adds a child to this parent entity. Thows exception if the child's name
1602
+ * is not unique with respect to other children of this parent.
1603
+ *
1604
+ * @param child - The child entity to add
1605
+ */
1606
+ addChild(child: Entity): void;
1607
+ /**
1608
+ * Removes all children from the entity.
1609
+ */
1610
+ removeAllChildren(): void;
1611
+ /**
1612
+ * Removes the specific child from this parent entity. Throws exception if
1613
+ * this parent does not contain the child.
1614
+ *
1615
+ * @param child
1616
+ */
1617
+ removeChild(child: Entity): void;
1618
+ /**
1619
+ * Removes the children from the parent. Throws error if the parent does not
1620
+ * contain all of the children.
1621
+ *
1622
+ * @param children - An array of children to remove from the parent entity
1623
+ */
1624
+ removeChildren(children: Array<Entity>): void;
1625
+ /**
1626
+ * Searches all descendants by name and returns first matching entity.
1627
+ *
1628
+ * @remarks Descendants are children and children of children, recursively.
1629
+ * Throws exception if no descendant with the given name is found.
1630
+ *
1631
+ * @param name - Name of the descendant entity to return
1632
+ * @returns
1633
+ */
1634
+ descendant<T extends Entity>(name: string): T;
1635
+ /**
1636
+ * Returns all descendant entities.
1637
+ *
1638
+ * @remarks Descendants are children and children of children, recursively.
1639
+ */
1640
+ get descendants(): Array<Entity>;
1641
+ /**
1642
+ * Returns all ancestor entities, not including the entity itself.
1643
+ */
1644
+ get ancestors(): Array<Entity>;
1645
+ /**
1646
+ * Determines if this entity or ancestor is part of an active action that
1647
+ * affects it appearance.
1648
+ *
1649
+ * @remarks This is used to determine if the entity should be rendered with
1650
+ * anti-aliasing or not. Anti-aliasing on some devices causes a new shader
1651
+ * to be compiled during the action, which causes jank.
1652
+ *
1653
+ * @returns true if part of active action affecting appearance
1654
+ */
1655
+ involvedInActionAffectingAppearance(): boolean;
1656
+ /**
1657
+ * Determines if the entity is a transitioning Scene or a descendant of a
1658
+ * transitioning Scene.
1659
+ *
1660
+ * @returns true if transitioning
1661
+ */
1662
+ involvedInSceneTransition(): boolean;
1663
+ /**
1664
+ * Executes a callback when the user presses down on the entity.
1665
+ *
1666
+ * @remarks TapDown is a pointer down (mouse click or touches begin) within
1667
+ * the bounds of the entity.
1668
+ *
1669
+ * @param callback - function to execute
1670
+ * @param replaceExistingCallback - should the provided callback replace
1671
+ * any existing callbacks of the same event type on this entity? Usually
1672
+ * there should be only one callback defined, instead of chaining multiple
1673
+ * ones. It is strongly recommended not to change this, unless you have a
1674
+ * special use case. Default is true.
1675
+ */
1676
+ onTapDown(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
1677
+ /**
1678
+ * Executes a callback when the user releases a press, that has been fully
1679
+ * within the entity, from the entity.
1680
+ *
1681
+ * @remarks TapUp is a pointer up (mouse click release or touches end) within
1682
+ * the bounds of the entity and the pointer, while down, has never moved
1683
+ * beyond the bounds of the entity.
1684
+ *
1685
+ * @param callback - function to execute
1686
+ * @param replaceExistingCallback - should the provided callback replace
1687
+ * any existing callbacks of the same event type on this entity? Usually
1688
+ * there should be only one callback defined, instead of chaining multiple
1689
+ * ones. It is strongly recommended not to change this, unless you have a
1690
+ * special use case. Default is true.
1691
+ */
1692
+ onTapUp(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
1693
+ /**
1694
+ * Executes a callback when the user releases a press from the entity within
1695
+ * the bounds of the entity.
1696
+ *
1697
+ * @remarks TapUpAny is a pointer up (mouse click release or touches end)
1698
+ * within the bounds of the entity and the pointer, while down, is allowed to
1699
+ * have been beyond the bounds of the entity during the press before the
1700
+ * release.
1701
+ *
1702
+ * @param callback - function to execute
1703
+ * @param replaceExistingCallback - should the provided callback replace
1704
+ * any existing callbacks of the same event type on this entity? Usually
1705
+ * there should be only one callback defined, instead of chaining multiple
1706
+ * ones. It is strongly recommended not to change this, unless you have a
1707
+ * special use case. Default is true.
1708
+ */
1709
+ onTapUpAny(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
1710
+ /**
1711
+ * Executes a callback when the user moves the pointer (mouse, touches) beyond
1712
+ * the bounds of the entity while the pointer is down.
1713
+ *
1714
+ * @remarks TapLeave occurs when the pointer (mouse, touches) that has
1715
+ * previously pressed the entity moves beyond the bounds of the entity
1716
+ * before the press release.
1717
+ *
1718
+ * @param callback - function to execute
1719
+ * @param replaceExistingCallback - should the provided callback replace
1720
+ * any existing callbacks of the same event type on this entity? Usually
1721
+ * there should be only one callback defined, instead of chaining multiple
1722
+ * ones. It is strongly recommended not to change this, unless you have a
1723
+ * special use case. Default is true.
1724
+ */
1725
+ onTapLeave(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
1726
+ /**
1727
+ * Executes a callback when the pointer first is down on the entity.
1728
+ *
1729
+ * @remarks PointerDown is a pointer down (mouse click or touches begin) within
1730
+ * the bounds of the entity. It occurs under the same conditions as TapDown.
1731
+ *
1732
+ * @param callback - function to execute
1733
+ * @param replaceExistingCallback - should the provided callback replace
1734
+ * any existing callbacks of the same event type on this entity? Usually
1735
+ * there should be only one callback defined, instead of chaining multiple
1736
+ * ones. It is strongly recommended not to change this, unless you have a
1737
+ * special use case. Default is true.
1738
+ */
1739
+ onPointerDown(callback: (m2PointerEvent: M2PointerEvent) => void, replaceExistingCallback?: boolean): void;
1740
+ /**
1741
+ * Executes a callback when the user releases a press from the entity within
1742
+ * the bounds of the entity.
1743
+ *
1744
+ * @remarks PointerUp is a pointer up (mouse click release or touches end)
1745
+ * within the bounds of the entity. It does not require that there was a
1746
+ * previous PointerDown on the entity.
1747
+ *
1748
+ * @param callback - function to execute
1749
+ * @param replaceExistingCallback - should the provided callback replace
1750
+ * any existing callbacks of the same event type on this entity? Usually
1751
+ * there should be only one callback defined, instead of chaining multiple
1752
+ * ones. It is strongly recommended not to change this, unless you have a
1753
+ * special use case. Default is true.
1754
+ */
1755
+ onPointerUp(callback: (m2PointerEvent: M2PointerEvent) => void, replaceExistingCallback?: boolean): void;
1756
+ /**
1757
+ * Executes a callback when the user moves the pointer (mouse or touches)
1758
+ * within the bounds of the entity.
1759
+ *
1760
+ * @param callback - function to execute
1761
+ * @param replaceExistingCallback - should the provided callback replace
1762
+ * any existing callbacks of the same event type on this entity? Usually
1763
+ * there should be only one callback defined, instead of chaining multiple
1764
+ * ones. It is strongly recommended not to change this, unless you have a
1765
+ * special use case. Default is true.
1766
+ */
1767
+ onPointerMove(callback: (m2PointerEvent: M2PointerEvent) => void, replaceExistingCallback?: boolean): void;
1768
+ /**
1769
+ * Executes a callback when the user begins dragging an entity.
1770
+ *
1771
+ * @param callback - function to execute
1772
+ * @param replaceExistingCallback - should the provided callback replace
1773
+ * any existing callbacks of the same event type on this entity? Usually
1774
+ * there should be only one callback defined, instead of chaining multiple
1775
+ * ones. It is strongly recommended not to change this, unless you have a
1776
+ * special use case. Default is true.
1777
+ */
1778
+ onDragStart(callback: (m2DragEvent: M2DragEvent) => void, replaceExistingCallback?: boolean): void;
1779
+ /**
1780
+ * Executes a callback when the user continues dragging an entity.
1781
+ *
1782
+ * @param callback - function to execute
1783
+ * @param replaceExistingCallback - should the provided callback replace
1784
+ * any existing callbacks of the same event type on this entity? Usually
1785
+ * there should be only one callback defined, instead of chaining multiple
1786
+ * ones. It is strongly recommended not to change this, unless you have a
1787
+ * special use case. Default is true.
1788
+ */
1789
+ onDrag(callback: (m2DragEvent: M2DragEvent) => void, replaceExistingCallback?: boolean): void;
1790
+ /**
1791
+ * Executes a callback when the user stop dragging an entity.
1792
+ *
1793
+ * @param callback - function to execute
1794
+ * @param replaceExistingCallback - should the provided callback replace
1795
+ * any existing callbacks of the same event type on this entity? Usually
1796
+ * there should be only one callback defined, instead of chaining multiple
1797
+ * ones. It is strongly recommended not to change this, unless you have a
1798
+ * special use case. Default is true.
1799
+ */
1800
+ onDragEnd(callback: (m2DragEvent: M2DragEvent) => void, replaceExistingCallback?: boolean): void;
1801
+ private addEventListener;
1802
+ private parseLayoutConstraints;
1803
+ private calculateYFromConstraint;
1804
+ private calculateXFromConstraint;
1805
+ update(): void;
1806
+ /**
1807
+ * Draws each child entity that is Drawable and is not hidden, by zPosition
1808
+ * order (highest zPosition on top).
1809
+ *
1810
+ * @param canvas - CanvasKit canvas
1811
+ */
1812
+ drawChildren(canvas: Canvas): void;
1813
+ /**
1814
+ * Runs an action on this entity.
1815
+ *
1816
+ * @remarks If the entity is part of an active scene, the action runs
1817
+ * immediately. Otherwise, the action will run when the entity's scene
1818
+ * becomes active. Calling run() multiple times on an entity will add
1819
+ * to existing actions, not replace them.
1820
+ *
1821
+ * @param action - The action to run
1822
+ * @param key - key (string identifier) used to identify the action.
1823
+ * Only needed if the action will be referred to later
1824
+ */
1825
+ run(action: Action, key?: string): void;
1826
+ /**
1827
+ * Remove an action from this entity. If the action is running, it will be
1828
+ * stopped.
1829
+ *
1830
+ * @param key - key (string identifier) of the action to remove
1831
+ */
1832
+ removeAction(key: string): void;
1833
+ /**
1834
+ * Remove all actions from this entity. If actions are running, they will be
1835
+ * stopped.
1836
+ */
1837
+ removeAllActions(): void;
1838
+ /**
1839
+ * Duplicates an entity using deep copy.
1840
+ *
1841
+ * @remarks This is a deep recursive clone (entity and children).
1842
+ * The uuid property of all duplicated entities will be newly created,
1843
+ * because uuid must be unique.
1844
+ *
1845
+ * @param newName - optional name of the new, duplicated entity. If not
1846
+ * provided, name will be the new uuid
1847
+ */
1848
+ abstract duplicate(newName?: string): Entity;
1849
+ protected getEntityOptions(): EntityOptions;
1850
+ protected getDrawableOptions(): DrawableOptions;
1851
+ protected getTextOptions(): TextOptions;
1852
+ /**
1853
+ * Gets the scene that contains this entity by searching up the ancestor tree recursively. Throws exception if entity is not part of a scene.
1854
+ *
1855
+ * @returns Scene that contains this entity
1856
+ */
1857
+ get canvasKit(): CanvasKit;
1858
+ get parentSceneAsEntity(): Entity;
1859
+ /**
1860
+ * For a given directed acyclic graph, topological ordering of the vertices will be identified using BFS
1861
+ * @param adjList Adjacency List that represent a graph with vertices and edges
1862
+ */
1863
+ private findTopologicalSort;
1864
+ }
1865
+
1866
+ interface MoveActionOptions {
1867
+ /** Destination point. The point is relative to the entity's parent coordinate system */
1868
+ point: Point;
1869
+ /** Duration of move, in milliseconds */
1870
+ duration: number;
1871
+ /** Easing function for movement; default is linear */
1872
+ easing?: EasingFunction;
1873
+ /** Should the action run during screen trnsitions? Default is no */
1874
+ runDuringTransition?: boolean;
1875
+ }
1876
+
1877
+ interface WaitActionOptions {
1878
+ /** Duration of wait, in milliseconds */
1879
+ duration: number;
1880
+ /** Should the action run during screen transitions? Default is no */
1881
+ runDuringTransition?: boolean;
1882
+ }
1883
+
1884
+ interface CustomActionOptions {
1885
+ /** callback - The callback function to be executed */
1886
+ callback: () => void;
1887
+ /** Should the action run during screen transitions? Default is no */
1888
+ runDuringTransition?: boolean;
1889
+ }
1890
+
1891
+ interface ScaleActionOptions {
1892
+ /** The scaling ratio. 1 is no change, greater than 1 is make bigger, less than 1 is make smaller */
1893
+ scale: number;
1894
+ /** Duration of scale, in milliseconds */
1895
+ duration: number;
1896
+ /** Should the action run during screen transitions? Default is no */
1897
+ runDuringTransition?: boolean;
1898
+ }
1899
+
1900
+ interface IActionContainer {
1901
+ children?: Array<Action>;
1902
+ }
1903
+
1904
+ /** The type of action */
1905
+ declare enum ActionType {
1906
+ Sequence = "Sequence",
1907
+ Group = "Group",
1908
+ Wait = "Wait",
1909
+ Custom = "Custom",
1910
+ Move = "Move",
1911
+ Scale = "Scale"
1912
+ }
1913
+
1914
+ /**
1915
+ * The Action class has static methods for creating actions to be executed by
1916
+ * an Entity.
1917
+ */
1918
+ declare abstract class Action {
1919
+ abstract type: ActionType;
1920
+ startOffset: number;
1921
+ endOffset: number;
1922
+ started: boolean;
1923
+ running: boolean;
1924
+ completed: boolean;
1925
+ runStartTime: number;
1926
+ duration: number;
1927
+ runDuringTransition: boolean;
1928
+ parent?: Action;
1929
+ isParent: boolean;
1930
+ isChild: boolean;
1931
+ key?: string;
1932
+ constructor(runDuringTransition?: boolean);
1933
+ /**
1934
+ * Creates an action that will move an entity to a point on the screen.
1935
+ *
1936
+ * @param options - {@link MoveActionOptions}
1937
+ * @returns The move action
1938
+ */
1939
+ static move(options: MoveActionOptions): Action;
1940
+ /**
1941
+ * Creates an action that will wait a given duration before it is considered complete.
1942
+ *
1943
+ * @param options - {@link WaitActionOptions}
1944
+ * @returns The wait action
1945
+ */
1946
+ static wait(options: WaitActionOptions): Action;
1947
+ /**
1948
+ * Creates an action that will execute a callback function.
1949
+ *
1950
+ * @param options - {@link CustomActionOptions}
1951
+ * @returns The custom action
1952
+ */
1953
+ static custom(options: CustomActionOptions): Action;
1954
+ /**
1955
+ * Creates an action that will scale the entity's size.
1956
+ *
1957
+ * @remarks Scaling is relative to any inherited scaling, which is multiplicative. For example, if the entity's parent is scaled to 2.0 and this entity's action scales to 3.0, then the entity will appear 6 times as large as original.
1958
+ *
1959
+ * @param options - {@link ScaleActionOptions}
1960
+ * @returns The scale action
1961
+ */
1962
+ static scale(options: ScaleActionOptions): Action;
1963
+ /**
1964
+ * Creates an array of actions that will be run in order.
1965
+ *
1966
+ * @remarks The next action will not begin until the current one has finished. The sequence will be considered completed when the last action has completed.
1967
+ *
1968
+ * @param actions - One or more actions that form the sequence
1969
+ * @returns
1970
+ */
1971
+ static sequence(actions: Array<Action>): Action;
1972
+ /**
1973
+ * Create an array of actions that will be run simultaneously.
1974
+ *
1975
+ * @remarks All actions within the group will begin to run at the same time. The group will be considered completed when the longest-running action has completed.
1976
+ *
1977
+ * @param actions - One or more actions that form the group
1978
+ * @returns
1979
+ */
1980
+ static group(actions: Array<Action>): Action;
1981
+ initialize(entity: Entity, key?: string): Array<Action>;
1982
+ static cloneAction(action: Action, key?: string): Action;
1983
+ static evaluateAction(action: Action, entity: Entity, now: number, dt: number): void;
1984
+ /**
1985
+ * Calculates the duration of an action, including any children actions
1986
+ * the action may contain.
1987
+ *
1988
+ * @remarks Uses recursion to handle arbitrary level of nesting parent
1989
+ * actions within parent actions
1990
+ *
1991
+ * @param action
1992
+ * @returns the calculated duration
1993
+ */
1994
+ private calculateDuration;
1995
+ /**
1996
+ * Update each action's start and end offsets.
1997
+ *
1998
+ * @remarks Uses recursion to handle arbitrary level of nesting parent
1999
+ * actions within parent actions.
2000
+ *
2001
+ * @param action that needs assigning start and end offsets
2002
+ */
2003
+ private calculateStartEndOffsets;
2004
+ /**
2005
+ * Takes an action hierarchy and flattens to an array of non-nested actions
2006
+ *
2007
+ * @remarks Uses recursion to handle arbitrary level of nesting parent
2008
+ * actions within parent actions
2009
+ *
2010
+ * @param action - the action to flatten
2011
+ * @param actions - the accumulator array of flattened actions. This will be
2012
+ * undefined on the first call, and an array on recursive calls
2013
+ * @returns flattened array of actions
2014
+ */
2015
+ private flattenActions;
2016
+ /**
2017
+ * Parses the action hierarchy and assigns each action its parent and
2018
+ * root action.
2019
+ *
2020
+ * @remarks Uses recursion to handle arbitrary level of nesting parent
2021
+ * actions within parent actions
2022
+ *
2023
+ * @param action
2024
+ * @param rootAction - top-level action passed to the run method
2025
+ * @param key - optional string to identify an action
2026
+ */
2027
+ private assignParents;
2028
+ }
2029
+ declare class SequenceAction extends Action implements IActionContainer {
2030
+ type: ActionType;
2031
+ children: Array<Action>;
2032
+ constructor(actions: Array<Action>);
2033
+ }
2034
+ declare class GroupAction extends Action implements IActionContainer {
2035
+ type: ActionType;
2036
+ children: Action[];
2037
+ constructor(actions: Array<Action>);
2038
+ }
2039
+ declare class CustomAction extends Action {
2040
+ type: ActionType;
2041
+ callback: () => void;
2042
+ constructor(callback: () => void, runDuringTransition?: boolean);
2043
+ }
2044
+ declare class WaitAction extends Action {
2045
+ type: ActionType;
2046
+ constructor(duration: number, runDuringTransition: boolean);
2047
+ }
2048
+ declare class MoveAction extends Action {
2049
+ type: ActionType;
2050
+ point: Point;
2051
+ startPoint: Point;
2052
+ dx: number;
2053
+ dy: number;
2054
+ easing: EasingFunction;
2055
+ constructor(point: Point, duration: number, easing: EasingFunction, runDuringTransition: boolean);
2056
+ }
2057
+ declare class ScaleAction extends Action {
2058
+ type: ActionType;
2059
+ scale: number;
2060
+ delta: number;
2061
+ constructor(scale: number, duration: number, runDuringTransition?: boolean);
2062
+ }
2063
+
2064
+ declare class CanvasKitHelpers {
2065
+ /**
2066
+ * Frees up resources that were allocated by CanvasKit.
2067
+ *
2068
+ * @remarks This frees objects created in WebAssembly by
2069
+ * canvaskit-wasm. JavaScript garbage collection won't
2070
+ * free these wasm objects.
2071
+ */
2072
+ static Dispose(objects: Array<undefined | null | EmbindObject<Font | Paint | ParagraphBuilder | Paragraph | Image | Typeface | FontMgr | Path>>): void;
2073
+ static makePaint(canvasKit: CanvasKit, color: RgbaColor, style: PaintStyle, isAntialiased: boolean): Paint;
2074
+ }
2075
+
2076
+ interface CompositeOptions extends EntityOptions, DrawableOptions {
2077
+ }
2078
+
2079
+ declare abstract class Composite extends Entity implements IDrawable {
2080
+ readonly type = EntityType.Composite;
2081
+ compositeType: string;
2082
+ isDrawable: boolean;
2083
+ anchorPoint: Point;
2084
+ zPosition: number;
2085
+ /**
2086
+ * Base Drawable object for creating custom entities ("composites") composed of primitive entities.
2087
+ *
2088
+ * @param options
2089
+ */
2090
+ constructor(options?: CompositeOptions);
2091
+ initialize(): void;
2092
+ dispose(): void;
2093
+ update(): void;
2094
+ draw(canvas: Canvas): void;
2095
+ abstract warmup(canvas: Canvas): void;
2096
+ }
2097
+
2098
+ /**
2099
+ * Reasonable defaults to use if values are not specified.
2100
+ */
2101
+ declare class Constants {
2102
+ /** Size of the font showing frames per second */
2103
+ static readonly FPS_DISPLAY_TEXT_FONT_SIZE = 12;
2104
+ /** Color of the font showing frames per second */
2105
+ static readonly FPS_DISPLAY_TEXT_COLOR: RgbaColor;
2106
+ /** Frequency, in milliseconds, at which to update frames per second metric shown on the screen */
2107
+ static readonly FPS_DISPLAY_UPDATE_INTERVAL = 1000;
2108
+ /** Maximum number of activity metrics to log. */
2109
+ static readonly MAXIMUM_RECORDED_ACTIVITY_METRICS = 32;
2110
+ /** The frames per second will be logged in game metrics if the FPS is lower than this value */
2111
+ static readonly FPS_METRIC_REPORT_THRESHOLD = 59;
2112
+ /** Scene color, if none is specified. */
2113
+ static readonly DEFAULT_SCENE_BACKGROUND_COLOR: RgbaColor;
2114
+ /** Shape fill color, if none is specified. */
2115
+ static readonly DEFAULT_SHAPE_FILL_COLOR: RgbaColor;
2116
+ /** Color of paths in a shape, if none is specified. */
2117
+ static readonly DEFAULT_PATH_STROKE_COLOR: RgbaColor;
2118
+ /** Line width of paths in a shape, if none is specified. */
2119
+ static readonly DEFAULT_PATH_LINE_WIDTH = 2;
2120
+ /** Color of text in Label and TextLine, if none is specified. */
2121
+ static readonly DEFAULT_FONT_COLOR: RgbaColor;
2122
+ /** Font size in Label and TextLine, if none is specified. */
2123
+ static readonly DEFAULT_FONT_SIZE = 16;
2124
+ static readonly LIMITED_FPS_RATE = 5;
2125
+ static readonly FREE_ENTITIES_SCENE_NAME = "__freeEntitiesScene";
2126
+ static readonly OUTGOING_SCENE_NAME = "__outgoingScene";
2127
+ static readonly OUTGOING_SCENE_SPRITE_NAME = "__outgoingSceneSprite";
2128
+ static readonly OUTGOING_SCENE_IMAGE_NAME = "__outgoingSceneSnapshot";
2129
+ }
2130
+
2131
+ /**
2132
+ * This enum is used interally for processing the layout constraints. We use
2133
+ * an enum to avoid magic strings. NOTE: the casing in ConstraintType must
2134
+ * match the casing in Constraints.ts. Thus, this enum's members are in
2135
+ * lowercase, which is not typical Typescript style.
2136
+ */
2137
+ declare enum ConstraintType {
2138
+ topToTopOf = "topToTopOf",
2139
+ topToBottomOf = "topToBottomOf",
2140
+ bottomToTopOf = "bottomToTopOf",
2141
+ bottomToBottomOf = "bottomToBottomOf",
2142
+ startToStartOf = "startToStartOf",
2143
+ startToEndOf = "startToEndOf",
2144
+ endToEndOf = "endToEndOf",
2145
+ endToStartOf = "endToStartOf"
2146
+ }
2147
+
2148
+ declare enum Dimensions {
2149
+ MatchConstraint = 0
2150
+ }
2151
+
2152
+ /**
2153
+ * Utility class for comparing equality of m2c2kit objects.
2154
+ */
2155
+ declare class Equals {
2156
+ /**
2157
+ * Compares two RgbaColor objects and returns true if they are equal.
2158
+ *
2159
+ * @remarks If either of the colors is undefined, the comparison will
2160
+ * return false. RgbaColor is an array of 4 numbers, and thus is a
2161
+ * reference type. We need this method to compare two RgbaColor objects
2162
+ * for value equality.
2163
+ *
2164
+ * @param color1
2165
+ * @param color2
2166
+ * @returns
2167
+ */
2168
+ static rgbaColor(color1?: RgbaColor, color2?: RgbaColor): boolean;
2169
+ }
2170
+
2171
+ interface FontData {
2172
+ gameUuid: string;
2173
+ fontUrl: string;
2174
+ fontArrayBuffer: ArrayBuffer;
2175
+ }
2176
+
2177
+ interface IText {
2178
+ text?: string;
2179
+ fontName?: string;
2180
+ fontColor?: RgbaColor;
2181
+ fontSize?: number;
2182
+ }
2183
+
2184
+ declare enum LabelHorizontalAlignmentMode {
2185
+ Center = 0,
2186
+ Left = 1,
2187
+ Right = 2
2188
+ }
2189
+
2190
+ interface LabelOptions extends EntityOptions, DrawableOptions, TextOptions {
2191
+ /** Horizontal alignment of label text. see {@link LabelHorizontalAlignmentMode}. Default is LabelHorizontalAlignmentMode.center */
2192
+ horizontalAlignmentMode?: LabelHorizontalAlignmentMode;
2193
+ /** Maximum width of label text before wrapping occurs. Default is the canvas width */
2194
+ preferredMaxLayoutWidth?: number;
2195
+ /** Background color of label text. Default is no background color */
2196
+ backgroundColor?: RgbaColor;
2197
+ }
2198
+
2199
+ declare class Label extends Entity implements IDrawable, IText, LabelOptions {
2200
+ readonly type = EntityType.Label;
2201
+ isDrawable: boolean;
2202
+ isText: boolean;
2203
+ anchorPoint: {
2204
+ x: number;
2205
+ y: number;
2206
+ };
2207
+ zPosition: number;
2208
+ private _text;
2209
+ private _fontName;
2210
+ private _fontColor;
2211
+ private _fontSize;
2212
+ private _horizontalAlignmentMode;
2213
+ private _preferredMaxLayoutWidth;
2214
+ private _backgroundColor?;
2215
+ private paragraph?;
2216
+ private paraStyle?;
2217
+ private builder?;
2218
+ private _translatedText;
2219
+ /**
2220
+ * Single or multi-line text formatted and rendered on the screen.
2221
+ *
2222
+ * @remarks Label (in contrast to TextLine) has enhanced text support for line wrapping, centering/alignment, and background colors.
2223
+ *
2224
+ * @param options - {@link LabelOptions}
2225
+ */
2226
+ constructor(options?: LabelOptions);
2227
+ initialize(): void;
2228
+ dispose(): void;
2229
+ get text(): string;
2230
+ set text(text: string);
2231
+ get translatedText(): string;
2232
+ get fontName(): string | undefined;
2233
+ set fontName(fontName: string | undefined);
2234
+ get fontColor(): RgbaColor;
2235
+ set fontColor(fontColor: RgbaColor);
2236
+ get fontSize(): number;
2237
+ set fontSize(fontSize: number);
2238
+ get horizontalAlignmentMode(): LabelHorizontalAlignmentMode;
2239
+ set horizontalAlignmentMode(horizontalAlignmentMode: LabelHorizontalAlignmentMode);
2240
+ get preferredMaxLayoutWidth(): number | undefined;
2241
+ set preferredMaxLayoutWidth(preferredMaxLayoutWidth: number | undefined);
2242
+ get backgroundColor(): RgbaColor | undefined;
2243
+ set backgroundColor(backgroundColor: RgbaColor | undefined);
2244
+ /**
2245
+ * Duplicates an entity using deep copy.
2246
+ *
2247
+ * @remarks This is a deep recursive clone (entity and children).
2248
+ * The uuid property of all duplicated entities will be newly created,
2249
+ * because uuid must be unique.
2250
+ *
2251
+ * @param newName - optional name of the new, duplicated entity. If not
2252
+ * provided, name will be the new uuid
2253
+ */
2254
+ duplicate(newName?: string): Label;
2255
+ update(): void;
2256
+ draw(canvas: Canvas): void;
2257
+ warmup(canvas: Canvas): void;
2258
+ }
2259
+
2260
+ /**
2261
+ * This class is used internally for processing layout constraints that
2262
+ * have been defined according to the Contraints interface.
2263
+ *
2264
+ * Imagine we have two entities, A and B. B's position is set
2265
+ * using its position property. A's position is set using the layout
2266
+ * constraint "bottomToTopOf B." A is the focal entity in this example.
2267
+ * What this means is that A's y coordinate will be computed such that
2268
+ * the bottom of A is the top of B. If A and B are squares, then A sits
2269
+ * on top of B with no gap.
2270
+ */
2271
+ declare class LayoutConstraint {
2272
+ type: ConstraintType;
2273
+ alterEntity: Entity;
2274
+ verticalConstraint: boolean;
2275
+ focalEntityMinimum: boolean;
2276
+ alterEntityMinimum: boolean;
2277
+ verticalTypes: ConstraintType[];
2278
+ focalEntityMinimumTypes: ConstraintType[];
2279
+ alterEntityMinimumTypes: ConstraintType[];
2280
+ constructor(type: ConstraintType, alterEntity: Entity);
2281
+ }
2282
+
2283
+ /**
2284
+ * A set of lines and/or shapes to draw.
2285
+ */
2286
+ interface M2Path {
2287
+ /** The subpath that compose up the path */
2288
+ subpaths: Array<Array<Point>>;
2289
+ /** The size of the path. This is neeeded to properly position the shape that is drawn by the path */
2290
+ size: Size;
2291
+ }
2292
+
2293
+ /**
2294
+ * Lines and/or shapes, and methods for creating them.
2295
+ */
2296
+ declare class MutablePath implements M2Path {
2297
+ size: Size;
2298
+ _subpaths: Point[][];
2299
+ get subpaths(): Array<Array<Point>>;
2300
+ private currentPath;
2301
+ /**
2302
+ * Starts a new subpath at a given point.
2303
+ *
2304
+ * @param point - location at which to start the new subpath
2305
+ */
2306
+ move(point: Point): void;
2307
+ /**
2308
+ * Adds a straight line to the current subpath.
2309
+ *
2310
+ * @remarks The line is added from the last point in the current subpath to
2311
+ * the given point.
2312
+ *
2313
+ * @param point - location where the line will end
2314
+ */
2315
+ addLine(point: Point): void;
2316
+ clear(): void;
2317
+ duplicate(newName?: string | undefined): Entity;
2318
+ }
2319
+
2320
+ declare class RandomDraws {
2321
+ /**
2322
+ * Draws a single random integer from a uniform distribution of integers in
2323
+ * the specified range.
2324
+ *
2325
+ * @param minimumInclusive - Lower bound of range
2326
+ * @param maximumInclusive - Upper bound of range
2327
+ * @returns A sampled integer
2328
+ */
2329
+ static SingleFromRange(minimumInclusive: number, maximumInclusive: number): number;
2330
+ /**
2331
+ * Draws random integers, without replacement, from a uniform distribution
2332
+ * of integers in the specified range.
2333
+ *
2334
+ * @param n - Number of draws
2335
+ * @param minimumInclusive - Lower bound of range
2336
+ * @param maximumInclusive - Upper bound of range
2337
+ * @returns An array of integers
2338
+ */
2339
+ static FromRangeWithoutReplacement(n: number, minimumInclusive: number, maximumInclusive: number): Array<number>;
2340
+ /**
2341
+ * Draw random grid cell locations, without replacement, from a uniform
2342
+ * distribution of all grid cells. Grid cell locations are zero-based,
2343
+ * i.e., upper-left is (0,0).
2344
+ *
2345
+ * @param n - Number of draws
2346
+ * @param rows - Number of rows in grid; must be at least 1
2347
+ * @param columns - Number of columns in grid; must be at least 1
2348
+ * @param predicate - Optional lambda function that takes a grid row number
2349
+ * and grid column number pair and returns a boolean to indicate if the pair
2350
+ * should be allowed. For example, if one wanted to constrain the random
2351
+ * grid location to be along the diagonal, the predicate would be:
2352
+ * (row, column) => row === column
2353
+ * @returns Array of grid cells. Each cell is object in form of:
2354
+ * \{ row: number, column: number \}. Grid cell locations are zero-based
2355
+ */
2356
+ static FromGridWithoutReplacement(n: number, rows: number, columns: number, predicate?: (row: number, column: number) => boolean): Array<{
2357
+ row: number;
2358
+ column: number;
2359
+ }>;
2360
+ }
2361
+
2362
+ interface RectOptions {
2363
+ /** Position of rectangle */
2364
+ origin?: Point;
2365
+ /** Size of rectangle */
2366
+ size?: Size;
2367
+ /** X coordinate of rectangle position; this can be used instead of setting the origin property */
2368
+ x?: number;
2369
+ /** Y coordinate of rectangle position; this can be used instead of setting the origin property */
2370
+ y?: number;
2371
+ /** Width of rectangle; this can be used instead of setting the size property */
2372
+ width?: number;
2373
+ /** Height of rectangle; this can be used instead of setting the size property */
2374
+ height?: number;
2375
+ }
2376
+
2377
+ declare enum ShapeType {
2378
+ Undefined = "Undefined",
2379
+ Rectangle = "Rectangle",
2380
+ Circle = "Circle",
2381
+ Path = "Path"
2382
+ }
2383
+
2384
+ /**
2385
+ * A path created from an SVG string path.
2386
+ */
2387
+ interface SvgStringPath {
2388
+ /** SVG string from which to create te path */
2389
+ svgString?: string;
2390
+ /** If provided, scale the SVG path to this height, and scale the width to keep the original SVG proportions */
2391
+ height?: number;
2392
+ /** If provided, scale the SVG path to this width, and scale the height to keep the original SVG proportions */
2393
+ width?: number;
2394
+ }
2395
+
2396
+ interface ShapeOptions extends EntityOptions, DrawableOptions {
2397
+ shapeType?: ShapeType;
2398
+ /** If provided, shape will be a circle with given radius */
2399
+ circleOfRadius?: number;
2400
+ /** If provided, shape will be a rectangle as specified in {@link Rect} */
2401
+ rect?: RectOptions;
2402
+ /** Radius of rectangle's corners */
2403
+ cornerRadius?: number;
2404
+ /** Color with which to fill shape. Default is Constants.DEFAULT_SHAPE_FILL_COLOR (WebColors.Red) */
2405
+ fillColor?: RgbaColor;
2406
+ /** Color with which to outline shape. Default is no color for rectangle and circle, red for path. */
2407
+ strokeColor?: RgbaColor;
2408
+ /** Width of outline. Default is undefined for rectangle and cricle, 2 for path. */
2409
+ lineWidth?: number;
2410
+ /** A path from which to create the shape */
2411
+ path?: M2Path | SvgStringPath;
2412
+ /** Size of container "viewbox" for path shapes. Leave undefined for circle and rectangle shapes. */
2413
+ size?: Size;
2414
+ /** Should the shape be drawn with antialiasing. Default is yes. */
2415
+ isAntialiased?: boolean;
2416
+ }
2417
+
2418
+ declare class Shape extends Entity implements IDrawable, ShapeOptions {
2419
+ readonly type = EntityType.Shape;
2420
+ isDrawable: boolean;
2421
+ isShape: boolean;
2422
+ anchorPoint: {
2423
+ x: number;
2424
+ y: number;
2425
+ };
2426
+ zPosition: number;
2427
+ shapeType: ShapeType;
2428
+ circleOfRadius?: number;
2429
+ rect?: RectOptions;
2430
+ path?: M2Path | SvgStringPath;
2431
+ ckPath: Path | null;
2432
+ ckPathWidth?: number;
2433
+ ckPathHeight?: number;
2434
+ pathSvgString?: string;
2435
+ cornerRadius: number;
2436
+ private _fillColor;
2437
+ private _strokeColor?;
2438
+ lineWidth?: number;
2439
+ private _isAntialiased;
2440
+ private _fillColorPaintAntialiased?;
2441
+ private _strokeColorPaintAntialiased?;
2442
+ private _fillColorPaintNotAntialiased?;
2443
+ private _strokeColorPaintNotAntialiased?;
2444
+ private svgPathRequestedWidth?;
2445
+ private svgPathRequestedHeight?;
2446
+ private svgPathScaleForResizing;
2447
+ private svgPathWidth;
2448
+ private svgPathHeight;
2449
+ private svgPreviousAbsoluteScale;
2450
+ private svgPreviousAbsoluteX;
2451
+ private svgPreviousAbsoluteY;
2452
+ private pathIsSvgStringPath;
2453
+ /**
2454
+ * Rectangular, circular, or path-based shape
2455
+ *
2456
+ * @param options - {@link ShapeOptions}
2457
+ */
2458
+ constructor(options?: ShapeOptions);
2459
+ initialize(): void;
2460
+ dispose(): void;
2461
+ /**
2462
+ * Duplicates an entity using deep copy.
2463
+ *
2464
+ * @remarks This is a deep recursive clone (entity and children).
2465
+ * The uuid property of all duplicated entities will be newly created,
2466
+ * because uuid must be unique.
2467
+ *
2468
+ * @param newName - optional name of the new, duplicated entity. If not
2469
+ * provided, name will be the new uuid
2470
+ */
2471
+ duplicate(newName?: string): Shape;
2472
+ update(): void;
2473
+ draw(canvas: Canvas): void;
2474
+ private drawPathFromM2Path;
2475
+ private drawPathFromSvgString;
2476
+ private calculateSvgPathY;
2477
+ private calculateSvgPathX;
2478
+ private saveSvgPathDrawParameters;
2479
+ private calculateTransformationMatrix;
2480
+ private pathNeedsTransform;
2481
+ private drawCircle;
2482
+ private drawRectangle;
2483
+ private drawCircleWithCanvasKit;
2484
+ private drawRectangleWithCanvasKit;
2485
+ private calculateCKRoundedRectangle;
2486
+ private getFillPaint;
2487
+ private getStrokePaint;
2488
+ warmup(canvas: Canvas): void;
2489
+ private warmupFilledCircle;
2490
+ private warmupStrokedCircle;
2491
+ private warmupFilledRectangle;
2492
+ private warmupStrokedRectangle;
2493
+ get fillColor(): RgbaColor;
2494
+ set fillColor(fillColor: RgbaColor);
2495
+ get strokeColor(): RgbaColor | undefined;
2496
+ set strokeColor(strokeColor: RgbaColor | undefined);
2497
+ get isAntialiased(): boolean;
2498
+ set isAntialiased(isAntialiased: boolean);
2499
+ get fillColorPaintAntialiased(): Paint;
2500
+ set fillColorPaintAntialiased(value: Paint);
2501
+ get strokeColorPaintAntialiased(): Paint;
2502
+ set strokeColorPaintAntialiased(value: Paint);
2503
+ get fillColorPaintNotAntialiased(): Paint;
2504
+ set fillColorPaintNotAntialiased(value: Paint);
2505
+ get strokeColorPaintNotAntialiased(): Paint;
2506
+ set strokeColorPaintNotAntialiased(value: Paint);
2507
+ }
2508
+
2509
+ interface SpriteOptions extends EntityOptions, DrawableOptions {
2510
+ /** Name of image to use for sprite. Must have been previously loaded */
2511
+ imageName?: string;
2512
+ }
2513
+
2514
+ declare class Sprite extends Entity implements IDrawable, SpriteOptions {
2515
+ readonly type = EntityType.Sprite;
2516
+ isDrawable: boolean;
2517
+ anchorPoint: {
2518
+ x: number;
2519
+ y: number;
2520
+ };
2521
+ zPosition: number;
2522
+ private _imageName;
2523
+ private loadedImage?;
2524
+ /**
2525
+ * Visual image displayed on the screen.
2526
+ *
2527
+ * @remarks Images that will be used to create the sprite must be loaded during the Game.init() method prior to their use.
2528
+ *
2529
+ * @param options - {@link SpriteOptions}
2530
+ */
2531
+ constructor(options?: SpriteOptions);
2532
+ initialize(): void;
2533
+ dispose(): void;
2534
+ set imageName(imageName: string);
2535
+ get imageName(): string;
2536
+ /**
2537
+ * Duplicates an entity using deep copy.
2538
+ *
2539
+ * @remarks This is a deep recursive clone (entity and children).
2540
+ * The uuid property of all duplicated entities will be newly created,
2541
+ * because uuid must be unique.
2542
+ *
2543
+ * @param newName - optional name of the new, duplicated entity. If not
2544
+ * provided, name will be the new uuid
2545
+ */
2546
+ duplicate(newName?: string): Sprite;
2547
+ update(): void;
2548
+ draw(canvas: Canvas): void;
2549
+ warmup(canvas: Canvas): void;
2550
+ }
2551
+
2552
+ interface StoryOptions {
2553
+ sceneNamePrefix?: string;
2554
+ }
2555
+
2556
+ declare abstract class Story {
2557
+ static Create(options: StoryOptions): Array<Scene>;
2558
+ }
2559
+
2560
+ interface TextLineOptions extends EntityOptions, DrawableOptions, TextOptions {
2561
+ width?: number;
2562
+ }
2563
+
2564
+ declare class TextLine extends Entity implements IDrawable, IText, TextLineOptions {
2565
+ readonly type = EntityType.TextLine;
2566
+ isDrawable: boolean;
2567
+ isText: boolean;
2568
+ zPosition: number;
2569
+ anchorPoint: {
2570
+ x: number;
2571
+ y: number;
2572
+ };
2573
+ private _text;
2574
+ private _fontName;
2575
+ private _fontColor;
2576
+ private _fontSize;
2577
+ private paint?;
2578
+ private font?;
2579
+ private typeface;
2580
+ private _translatedText;
2581
+ private missingTranslationPaint?;
2582
+ /**
2583
+ * Single-line text rendered on the screen.
2584
+ *
2585
+ * @remarks TextLine has no paragraph formatting options; Label will be preferred in most use cases.
2586
+ *
2587
+ * @param options - {@link TextLineOptions}
2588
+ */
2589
+ constructor(options?: TextLineOptions);
2590
+ get text(): string;
2591
+ set text(text: string);
2592
+ get translatedText(): string;
2593
+ get fontName(): string | undefined;
2594
+ set fontName(fontName: string | undefined);
2595
+ get fontColor(): RgbaColor;
2596
+ set fontColor(fontColor: RgbaColor);
2597
+ get fontSize(): number;
2598
+ set fontSize(fontSize: number);
2599
+ update(): void;
2600
+ initialize(): void;
2601
+ dispose(): void;
2602
+ /**
2603
+ * Duplicates an entity using deep copy.
2604
+ *
2605
+ * @remarks This is a deep recursive clone (entity and children).
2606
+ * The uuid property of all duplicated entities will be newly created,
2607
+ * because uuid must be unique.
2608
+ *
2609
+ * @param newName - optional name of the new, duplicated entity. If not
2610
+ * provided, name will be the new uuid
2611
+ */
2612
+ duplicate(newName?: string): TextLine;
2613
+ draw(canvas: Canvas): void;
2614
+ warmup(canvas: Canvas): void;
2615
+ }
2616
+
2617
+ declare class Timer {
2618
+ private startTime;
2619
+ private stopTime;
2620
+ private stopped;
2621
+ /**
2622
+ * cumulativeElapsed is a cumulative total of elapsed time while the timer
2623
+ * was in previous started (running) states, NOT INCLUDING the possibily
2624
+ * active run's duration
2625
+ */
2626
+ private cumulativeElapsed;
2627
+ private name;
2628
+ private static _timers;
2629
+ constructor(name: string);
2630
+ /**
2631
+ * Aliases performance.now()
2632
+ *
2633
+ * @remarks The m2c2kit Timer class is designed to measure elapsed durations
2634
+ * after a designated start point for a uniquely named timer. However, if a
2635
+ * timestamp based on the
2636
+ * [time origin](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
2637
+ * is needed, this method can be used.
2638
+ *
2639
+ * @returns a [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp)
2640
+ */
2641
+ static now(): number;
2642
+ /**
2643
+ * Starts a millisecond-resolution timer based on
2644
+ * [performance.now()](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now).
2645
+ *
2646
+ * @remarks The method throws an error if a timer with the given
2647
+ * name is already in a started state.
2648
+ *
2649
+ * @param name - The name of the timer to be started
2650
+ */
2651
+ static start(name: string): void;
2652
+ /**
2653
+ * Stops a timer.
2654
+ *
2655
+ * @remarks The method throws an error if a timer with the given
2656
+ * name is already in a stopped state, or if a timer with the
2657
+ * given name has not been started.
2658
+ *
2659
+ * @param name - The name of the timer to be stopped
2660
+ */
2661
+ static stop(name: string): void;
2662
+ /**
2663
+ * Restarts a timer.
2664
+ *
2665
+ * @remarks The timer elapsed duration is set to 0 and it starts anew.
2666
+ * The method throws an error if a timer with the given
2667
+ * name does not exist (if there is not a started or stopped timer
2668
+ * with the given name).
2669
+ *
2670
+ * @param name - The name of the timer to be restarted
2671
+ */
2672
+ static restart(name: string): void;
2673
+ /**
2674
+ * Returns the total time elapsed, in milliseconds, of the timer.
2675
+ *
2676
+ * @remarks The total time elapsed will include all durations from multiple
2677
+ * starts and stops of the timer, if applicable. A timer's elapsed duration
2678
+ * can be read while it is in started or stopped state. The method throws
2679
+ * an error if a timer with the given name does not exist.
2680
+ *
2681
+ * @param name - The name of the timer whose elapsed duration is requested
2682
+ */
2683
+ static elapsed(name: string): number;
2684
+ /**
2685
+ * Removes a timer.
2686
+ *
2687
+ * @remarks After removal, no additional methods can be used with a timer
2688
+ * of the given name, other than to start a new timer with the given name,
2689
+ * whose duration will begin at 0 again. The method throws an error if
2690
+ * a timer with the given name does not exist.
2691
+ *
2692
+ * @param name - The name of the timer to be removed
2693
+ */
2694
+ static remove(name: string): void;
2695
+ /**
2696
+ * Remove all timers.
2697
+ *
2698
+ * @remarks This method will {@link remove} any timers in a started or
2699
+ * stopped state. This method is idempotent; method is safe to call even
2700
+ * if there are no timers to remove; no errors are thrown if there are
2701
+ * not any timers that can be removed.
2702
+ */
2703
+ static removeAll(): void;
2704
+ /**
2705
+ * Checks if a timer of the given name exists.
2706
+ *
2707
+ * @remarks The method checks if there is a timer with the given name.
2708
+ *
2709
+ * @param name - The name of the timer to check for existence
2710
+ * @returns boolean
2711
+ */
2712
+ static exists(name: string): boolean;
2713
+ }
2714
+
2715
+ declare class Uuid {
2716
+ static generate(): string;
2717
+ }
2718
+
2719
+ declare class WebColors {
2720
+ static Transparent: RgbaColor;
2721
+ static MediumVioletRed: RgbaColor;
2722
+ static DeepPink: RgbaColor;
2723
+ static PaleVioletRed: RgbaColor;
2724
+ static HotPink: RgbaColor;
2725
+ static LightPink: RgbaColor;
2726
+ static Pink: RgbaColor;
2727
+ static DarkRed: RgbaColor;
2728
+ static Red: RgbaColor;
2729
+ static Firebrick: RgbaColor;
2730
+ static Crimson: RgbaColor;
2731
+ static IndianRed: RgbaColor;
2732
+ static LightCoral: RgbaColor;
2733
+ static Salmon: RgbaColor;
2734
+ static DarkSalmon: RgbaColor;
2735
+ static LightSalmon: RgbaColor;
2736
+ static OrangeRed: RgbaColor;
2737
+ static Tomato: RgbaColor;
2738
+ static DarkOrange: RgbaColor;
2739
+ static Coral: RgbaColor;
2740
+ static Orange: RgbaColor;
2741
+ static DarkKhaki: RgbaColor;
2742
+ static Gold: RgbaColor;
2743
+ static Khaki: RgbaColor;
2744
+ static PeachPuff: RgbaColor;
2745
+ static Yellow: RgbaColor;
2746
+ static PaleGoldenrod: RgbaColor;
2747
+ static Moccasin: RgbaColor;
2748
+ static PapayaWhip: RgbaColor;
2749
+ static LightGoldenrodYellow: RgbaColor;
2750
+ static LemonChiffon: RgbaColor;
2751
+ static LightYellow: RgbaColor;
2752
+ static Maroon: RgbaColor;
2753
+ static Brown: RgbaColor;
2754
+ static SaddleBrown: RgbaColor;
2755
+ static Sienna: RgbaColor;
2756
+ static Chocolate: RgbaColor;
2757
+ static DarkGoldenrod: RgbaColor;
2758
+ static Peru: RgbaColor;
2759
+ static RosyBrown: RgbaColor;
2760
+ static Goldenrod: RgbaColor;
2761
+ static SandyBrown: RgbaColor;
2762
+ static Tan: RgbaColor;
2763
+ static Burlywood: RgbaColor;
2764
+ static Wheat: RgbaColor;
2765
+ static NavajoWhite: RgbaColor;
2766
+ static Bisque: RgbaColor;
2767
+ static BlanchedAlmond: RgbaColor;
2768
+ static Cornsilk: RgbaColor;
2769
+ static DarkGreen: RgbaColor;
2770
+ static Green: RgbaColor;
2771
+ static DarkOliveGreen: RgbaColor;
2772
+ static ForestGreen: RgbaColor;
2773
+ static SeaGreen: RgbaColor;
2774
+ static Olive: RgbaColor;
2775
+ static OliveDrab: RgbaColor;
2776
+ static MediumSeaGreen: RgbaColor;
2777
+ static LimeGreen: RgbaColor;
2778
+ static Lime: RgbaColor;
2779
+ static SpringGreen: RgbaColor;
2780
+ static MediumSpringGreen: RgbaColor;
2781
+ static DarkSeaGreen: RgbaColor;
2782
+ static MediumAquamarine: RgbaColor;
2783
+ static YellowGreen: RgbaColor;
2784
+ static LawnGreen: RgbaColor;
2785
+ static Chartreuse: RgbaColor;
2786
+ static LightGreen: RgbaColor;
2787
+ static GreenYellow: RgbaColor;
2788
+ static PaleGreen: RgbaColor;
2789
+ static Teal: RgbaColor;
2790
+ static DarkCyan: RgbaColor;
2791
+ static LightSeaGreen: RgbaColor;
2792
+ static CadetBlue: RgbaColor;
2793
+ static DarkTurquoise: RgbaColor;
2794
+ static MediumTurquoise: RgbaColor;
2795
+ static Turquoise: RgbaColor;
2796
+ static Aqua: RgbaColor;
2797
+ static Cyan: RgbaColor;
2798
+ static Aquamarine: RgbaColor;
2799
+ static PaleTurquoise: RgbaColor;
2800
+ static LightCyan: RgbaColor;
2801
+ static Navy: RgbaColor;
2802
+ static DarkBlue: RgbaColor;
2803
+ static MediumBlue: RgbaColor;
2804
+ static Blue: RgbaColor;
2805
+ static MidnightBlue: RgbaColor;
2806
+ static RoyalBlue: RgbaColor;
2807
+ static SteelBlue: RgbaColor;
2808
+ static DodgerBlue: RgbaColor;
2809
+ static DeepSkyBlue: RgbaColor;
2810
+ static CornflowerBlue: RgbaColor;
2811
+ static SkyBlue: RgbaColor;
2812
+ static LightSkyBlue: RgbaColor;
2813
+ static LightSteelBlue: RgbaColor;
2814
+ static LightBlue: RgbaColor;
2815
+ static PowderBlue: RgbaColor;
2816
+ static Indigo: RgbaColor;
2817
+ static Purple: RgbaColor;
2818
+ static DarkMagenta: RgbaColor;
2819
+ static DarkViolet: RgbaColor;
2820
+ static DarkSlateBlue: RgbaColor;
2821
+ static BlueViolet: RgbaColor;
2822
+ static DarkOrchid: RgbaColor;
2823
+ static Fuchsia: RgbaColor;
2824
+ static Magenta: RgbaColor;
2825
+ static SlateBlue: RgbaColor;
2826
+ static MediumSlateBlue: RgbaColor;
2827
+ static MediumOrchid: RgbaColor;
2828
+ static MediumPurple: RgbaColor;
2829
+ static Orchid: RgbaColor;
2830
+ static Violet: RgbaColor;
2831
+ static Plum: RgbaColor;
2832
+ static Thistle: RgbaColor;
2833
+ static Lavender: RgbaColor;
2834
+ static MistyRose: RgbaColor;
2835
+ static AntiqueWhite: RgbaColor;
2836
+ static Linen: RgbaColor;
2837
+ static Beige: RgbaColor;
2838
+ static WhiteSmoke: RgbaColor;
2839
+ static LavenderBlush: RgbaColor;
2840
+ static OldLace: RgbaColor;
2841
+ static AliceBlue: RgbaColor;
2842
+ static Seashell: RgbaColor;
2843
+ static GhostWhite: RgbaColor;
2844
+ static Honeydew: RgbaColor;
2845
+ static FloralWhite: RgbaColor;
2846
+ static Azure: RgbaColor;
2847
+ static MintCream: RgbaColor;
2848
+ static Snow: RgbaColor;
2849
+ static Ivory: RgbaColor;
2850
+ static White: RgbaColor;
2851
+ static Black: RgbaColor;
2852
+ static DarkSlateGray: RgbaColor;
2853
+ static DimGray: RgbaColor;
2854
+ static SlateGray: RgbaColor;
2855
+ static Gray: RgbaColor;
2856
+ static LightSlateGray: RgbaColor;
2857
+ static DarkGray: RgbaColor;
2858
+ static Silver: RgbaColor;
2859
+ static LightGray: RgbaColor;
2860
+ static Gainsboro: RgbaColor;
2861
+ static RebeccaPurple: RgbaColor;
2862
+ }
2863
+
2864
+ declare class WebGlInfo {
2865
+ /**
2866
+ * Returns graphics driver vendor and renderer information.
2867
+ *
2868
+ * @remarks Information is from parameters UNMASKED_VENDOR_WEBGL and
2869
+ * UNMASKED_RENDERER_WEBGL when asking for WEBGL_debug_renderer_info
2870
+ * from the WebGLRenderingContext.
2871
+ *
2872
+ * @returns string
2873
+ */
2874
+ static getRendererString(): string;
2875
+ /**
2876
+ * Removes the temporary canvas that was created to get WebGL information.
2877
+ */
2878
+ static dispose(): void;
2879
+ }
2880
+
2881
+ export { Action, Activity, ActivityKeyValueData, ActivityLifecycleEvent, ActivityResultsEvent, ActivityType, BrowserImage, CanvasKitHelpers, Composite, CompositeOptions, Constants, ConstraintType, Constraints, CustomAction, CustomActionOptions, DefaultParameter, Dimensions, DrawableOptions, EasingFunction, Easings, Entity, EntityEvent, EntityEventListener, EntityOptions, EntityType, Equals, EventBase, EventType, FontData, FontManager, Game, GameData, GameOptions, GameParameters, GlobalVariables, GoToActivityOptions, GroupAction, I18n, IDataStore, IDrawable, IText, ImageManager, Label, LabelHorizontalAlignmentMode, LabelOptions, Layout, LayoutConstraint, LoadedImage, M2DragEvent, M2Path, MoveAction, MoveActionOptions, MutablePath, NoneTransition, Point, RandomDraws, RectOptions, RgbaColor, ScaleAction, ScaleActionOptions, Scene, SceneOptions, SceneTransition, SequenceAction, Session, SessionDictionaryValues, SessionLifecycleEvent, SessionOptions, Shape, ShapeOptions, ShapeType, Size, SlideTransition, SlideTransitionOptions, Sprite, SpriteOptions, Story, StoryOptions, TextLine, TextLineOptions, TextOptions, Timer, Transition, TransitionDirection, TransitionType, Translations, TrialData, TrialSchema, Uuid, WaitAction, WaitActionOptions, WebColors, WebGlInfo, handleInterfaceOptions };