@m2c2kit/core 0.1.10 → 0.3.6

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