@m2c2kit/core 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,67 +1,6 @@
1
- import { FontMgr, Typeface, Image, CanvasKit, Canvas } from 'canvaskit-wasm';
2
-
3
- interface FontData {
4
- fontUrl: string;
5
- fontArrayBuffer: ArrayBuffer;
6
- }
7
-
8
- declare class FontManager {
9
- _fontMgr?: FontMgr;
10
- private _typefaces;
11
- _getTypeface(name: string): Typeface;
12
- FetchFontsAsArrayBuffers(fontUrls: Array<string>): Promise<FontData>[];
13
- LoadFonts(fonts: Array<ArrayBuffer>): void;
14
- }
15
-
16
- declare class LoadedImage {
17
- name: string;
18
- image: Image;
19
- width: number;
20
- height: number;
21
- constructor(name: string, image: Image, width: number, height: number);
22
- }
23
-
24
- declare class RenderedDataUrlImage {
25
- name: string;
26
- dataUrlImage: string;
27
- width: number;
28
- height: number;
29
- constructor(name: string, dataUrlImage: string, width: number, height: number);
30
- }
31
-
32
- /**
33
- * SVG image to be rendered and loaded from a URL or HTML svg tag in string form.
34
- */
35
- interface SvgImage {
36
- /** Name that will be used to refer to the SVG image. Must be unique among all images */
37
- name: string;
38
- /** Width to scale SVG image to */
39
- width: number;
40
- /** Height to scale SVG image to */
41
- height: number;
42
- /** The HTML SVG tag, in string form, that will be rendered and loaded. Must begin with &#60;svg> and end with &#60;/svg> */
43
- svgString?: string;
44
- /** URL of SVG asset to render and load */
45
- url?: string;
46
- }
47
-
48
- declare class ImageManager {
49
- private scratchCanvas?;
50
- private ctx?;
51
- private scale?;
52
- _renderedDataUrlImages: Record<string, RenderedDataUrlImage>;
53
- _loadedImages: Record<string, LoadedImage>;
54
- initialize(scratchCanvas: HTMLCanvasElement): void;
55
- renderSvgImage(svgImage: SvgImage): Promise<RenderedDataUrlImage>;
56
- LoadRenderedSvgImages(urls: RenderedDataUrlImage[]): void;
57
- private convertRenderedDataUrlImage;
58
- private dataURLtoArrayBuffer;
59
- }
1
+ import { Canvas, CanvasKit, Image, FontMgr, Typeface } from 'canvaskit-wasm';
60
2
 
61
3
  declare class GlobalVariables {
62
- canvasKit: CanvasKit;
63
- fontManager: FontManager;
64
- imageManager: ImageManager;
65
4
  now: number;
66
5
  deltaTime: number;
67
6
  canvasScale: number;
@@ -72,41 +11,55 @@ declare class GlobalVariables {
72
11
 
73
12
  declare global {
74
13
  var Globals: GlobalVariables;
14
+ }
15
+ //# sourceMappingURL=Globals.d.ts.map
16
+
17
+ interface EntityEvent {
18
+ target: Entity;
19
+ }
20
+
21
+ interface EntityEventListener {
22
+ eventType: string;
23
+ entityName: string;
24
+ callback: (event: EntityEvent) => void;
75
25
  }
76
26
 
77
27
  /**
78
28
  * Position in two-dimensional space.
79
29
  */
80
30
  declare class Point {
31
+ /** Horizonal coordinate */
81
32
  x: number;
33
+ /** Vertical coordinate */
82
34
  y: number;
83
35
  constructor(x?: number, y?: number);
84
36
  }
85
37
 
86
- declare class TapListener {
87
- entityName?: string;
88
- codeCallback?: (tapevent: TapEvent) => void;
89
- }
90
- /**
91
- * Object passed to the tap event handler when the entity is tapped.
92
- */
93
- interface TapEvent {
94
- /** The entity that was tapped */
95
- tappedEntity: Entity;
38
+ interface TapEvent extends EntityEvent {
96
39
  /** Point that was tapped on entity, relative to the entity coordinate system */
97
40
  point: Point;
98
41
  }
99
42
 
100
43
  interface Constraints {
44
+ /** 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 */
101
45
  topToTopOf?: Entity | string;
46
+ /** Constrain the top (vertical axis) of this entity to the bottom of the specified entity. This entity will appear immediately below the specified entity */
102
47
  topToBottomOf?: Entity | string;
48
+ /** 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 */
103
49
  bottomToTopOf?: Entity | string;
50
+ /** 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 */
104
51
  bottomToBottomOf?: Entity | string;
52
+ /** 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 */
105
53
  startToStartOf?: Entity | string;
54
+ /** 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 */
106
55
  startToEndOf?: Entity | string;
56
+ /** 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 */
107
57
  endToEndOf?: Entity | string;
58
+ /** 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 */
108
59
  endToStartOf?: Entity | string;
60
+ /** 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) */
109
61
  horizontalBias?: number;
62
+ /** 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 */
110
63
  verticalBias?: number;
111
64
  [key: string]: Entity | string | number | undefined;
112
65
  }
@@ -136,11 +89,17 @@ declare class Size {
136
89
  }
137
90
 
138
91
  interface EntityOptions {
92
+ /** Name of the entity. Only needed if the entity will be referred to by name in a later function */
139
93
  name?: string;
94
+ /** Position of the entity within its parent coordinate system. Default is (0, 0) */
140
95
  position?: Point;
96
+ /** Scale of the entity. Default is 1.0 */
141
97
  scale?: number;
98
+ /** Does the entity respond to user events, such as taps? Default is false */
142
99
  isUserInteractionEnabled?: boolean;
100
+ /** Is the entity, and its children, hidden? (not displayed). Default is false */
143
101
  hidden?: boolean;
102
+ /** FOR INTERNAL USE ONLY */
144
103
  layout?: Layout;
145
104
  }
146
105
 
@@ -155,7 +114,7 @@ declare enum EntityType {
155
114
  }
156
115
 
157
116
  declare function handleInterfaceOptions(entity: Entity, options: EntityOptions): void;
158
- declare abstract class Entity {
117
+ declare abstract class Entity implements EntityOptions {
159
118
  type: EntityType;
160
119
  isDrawable: boolean;
161
120
  isShape: boolean;
@@ -174,7 +133,7 @@ declare abstract class Entity {
174
133
  actions: Action[];
175
134
  queuedAction?: Action;
176
135
  originalActions: Action[];
177
- tapListeners: TapListener[];
136
+ eventListeners: EntityEventListener[];
178
137
  uuid: string;
179
138
  needsInitialization: boolean;
180
139
  userData: any;
@@ -214,7 +173,13 @@ declare abstract class Entity {
214
173
  * Returns all descendant entities. Descendants are children and children of children, recursively.
215
174
  */
216
175
  get descendants(): Array<Entity>;
217
- onTap(codeCallback: (tapEvent: TapEvent) => void, replaceExistingCodeCallback?: boolean): void;
176
+ /**
177
+ * 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.
178
+ *
179
+ * @param callback - function to execute
180
+ * @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.
181
+ */
182
+ onTapDown(callback: (tapEvent: TapEvent) => void, replaceExistingCallback?: boolean): void;
218
183
  private parseLayoutConstraints;
219
184
  private calculateYFromConstraint;
220
185
  private calculateXFromConstraint;
@@ -252,8 +217,8 @@ declare abstract class Entity {
252
217
  *
253
218
  * @returns Scene that contains this entity
254
219
  */
220
+ get canvasKit(): CanvasKit;
255
221
  get parentSceneAsEntity(): Entity;
256
- private generateUUID;
257
222
  /**
258
223
  * For a given directed acyclic graph, topological ordering of the vertices will be identified using BFS
259
224
  * @param adjList Adjacency List that represent a graph with vertices and edges
@@ -389,8 +354,8 @@ declare class GroupAction extends Action implements IActionContainer {
389
354
  }
390
355
  declare class CustomAction extends Action {
391
356
  type: ActionType;
392
- codeCallback: () => void;
393
- constructor(codeCallback: () => void, runDuringTransition?: boolean);
357
+ callback: () => void;
358
+ constructor(callback: () => void, runDuringTransition?: boolean);
394
359
  }
395
360
  declare class WaitAction extends Action {
396
361
  type: ActionType;
@@ -410,80 +375,155 @@ declare class ScaleAction extends Action {
410
375
  constructor(scale: number, duration: number, runDuringTransition?: boolean);
411
376
  }
412
377
 
413
- interface IDrawable {
414
- draw(canvas: Canvas): void;
415
- anchorPoint: Point;
416
- zPosition: number;
378
+ declare class LoadedImage {
379
+ name: string;
380
+ image: Image;
381
+ width: number;
382
+ height: number;
383
+ constructor(name: string, image: Image, width: number, height: number);
417
384
  }
418
385
 
419
- interface DrawableOptions {
420
- anchorPoint?: Point;
421
- zPosition?: number;
386
+ /**
387
+ * Image that can be rendered by a browser and loaded from a URL or HTML svg tag in string form.
388
+ */
389
+ interface BrowserImage {
390
+ /** Name that will be used to refer to the SVG image. Must be unique among all images */
391
+ name: string;
392
+ /** Width to scale SVG image to */
393
+ width: number;
394
+ /** Height to scale SVG image to */
395
+ height: number;
396
+ /** The HTML SVG tag, in string form, that will be rendered and loaded. Must begin with &#60;svg> and end with &#60;/svg> */
397
+ svgString?: string;
398
+ /** URL of SVG asset to render and load */
399
+ url?: string;
422
400
  }
423
401
 
424
- interface CompositeOptions extends EntityOptions, DrawableOptions {
402
+ interface GameImages {
403
+ uuid: string;
404
+ images: Array<BrowserImage>;
425
405
  }
426
406
 
427
- declare abstract class Composite extends Entity implements IDrawable {
428
- readonly type = EntityType.composite;
429
- compositeType: string;
430
- isDrawable: boolean;
431
- anchorPoint: Point;
432
- zPosition: number;
407
+ declare class ImageManager {
408
+ canvasKit?: CanvasKit;
409
+ private renderedImages;
410
+ private loadedImages;
411
+ private _scratchCanvas?;
412
+ private ctx?;
413
+ private scale?;
414
+ getLoadedImage(gameUuid: string, imageName: string): LoadedImage;
433
415
  /**
434
- * Base Drawable object for creating custom entities ("composites") composed of primitive entities.
416
+ * Adds a CanvasKit image to the images available to a given game.
417
+ * Typically, this won't be called directly because images will be
418
+ * automatically rendered and loaded in the Activity async init.
419
+ * The only time this function is called in-game is to add
420
+ * screenshot images needed for transitions
435
421
  *
436
- * @param options
422
+ * @param loadedImage
423
+ * @param gameUuid
437
424
  */
438
- constructor(options?: CompositeOptions);
439
- initialize(): void;
440
- update(): void;
441
- draw(canvas: Canvas): void;
425
+ addLoadedImage(loadedImage: LoadedImage, gameUuid: string): void;
426
+ renderImages(allGamesImages: Array<GameImages>): Promise<void[]>;
427
+ loadAllGamesRenderedImages(): void;
428
+ private renderBrowserImage;
429
+ private convertRenderedDataUrlImageToCanvasKitImage;
430
+ /**
431
+ * scratchCanvas is an extra, non-visible canvas in the DOM we use so the native browser can render images
432
+ */
433
+ private get scratchCanvas();
434
+ private dataURLtoArrayBuffer;
442
435
  }
443
436
 
444
- /**
445
- * Color in red (0-255), green (0-255), blue (0-255), alpha (0-1) format. Must be numeric array of length 4.
446
- */
447
- declare type RgbaColor = [number, number, number, number];
437
+ interface GameFontUrls {
438
+ uuid: string;
439
+ fontUrls: Array<string>;
440
+ }
448
441
 
449
- /**
450
- * Reasonable defaults to use if values are not specified.
451
- */
452
- declare class Constants {
453
- static readonly FPS_DISPLAY_TEXT_FONT_SIZE = 12;
454
- static readonly FPS_DISPLAY_TEXT_COLOR: RgbaColor;
455
- static readonly FPS_DISPLAY_UPDATE_INTERVAL = 500;
456
- static readonly DEFAULT_SCENE_BACKGROUND_COLOR: RgbaColor;
457
- static readonly DEFAULT_SHAPE_FILL_COLOR: RgbaColor;
458
- static readonly DEFAULT_FONT_COLOR: RgbaColor;
459
- static readonly DEFAULT_FONT_SIZE = 16;
460
- static readonly LIMITED_FPS_RATE = 5;
442
+ declare class FontManager {
443
+ canvasKit?: CanvasKit;
444
+ fontMgr?: FontMgr;
445
+ private gameTypefaces;
446
+ private allGamesFontData?;
447
+ /**
448
+ * Gets a typeface that was previously loaded for the specified game.
449
+ *
450
+ * @param gameUuid
451
+ * @param fontFamily
452
+ * @returns the requested Typeface
453
+ */
454
+ getTypeface(gameUuid: string, fontFamily: string): Typeface;
455
+ /**
456
+ * Fetches all fonts for all games.
457
+ *
458
+ * @param allGamesFontUrls
459
+ * @returns
460
+ */
461
+ fetchFonts(allGamesFontUrls: Array<GameFontUrls>): Promise<void>;
462
+ /**
463
+ * Takes the fonts, which have been previously fetched and converted into
464
+ * Array Buffers using FontManager.fetchFonts(), and makes them available
465
+ * to our engine
466
+ */
467
+ loadAllGamesFontData(): void;
468
+ /**
469
+ * For the specified game, fetches all fonts in the array of urls and
470
+ * stores fonts as array buffers.
471
+ *
472
+ * @param gameUuid
473
+ * @param fontUrls - array of font urls
474
+ * @returns
475
+ */
476
+ private fetchGameFontsAsArrayBuffers;
477
+ /**
478
+ * For the specified game, loads all fonts from array buffers and makes
479
+ * fonts available within canvaskit as a Typeface
480
+ *
481
+ * @param gameUuid
482
+ * @param fonts - array of fonts in array buffer form
483
+ */
484
+ private loadGameFonts;
485
+ }
486
+
487
+ interface GameEvent {
488
+ gameUuid: string;
489
+ gameName: string;
490
+ }
491
+
492
+ interface GameLifecycleEvent extends GameEvent {
493
+ ended: boolean;
494
+ }
495
+
496
+ interface GameParameters {
497
+ [key: string]: DefaultParameter;
498
+ }
499
+ interface DefaultParameter {
500
+ value: any;
501
+ type?: "number" | "string" | "boolean" | "object";
502
+ description?: string;
503
+ }
504
+
505
+ interface IDrawable {
506
+ draw(canvas: Canvas): void;
507
+ anchorPoint: Point;
508
+ zPosition: number;
461
509
  }
462
510
 
463
511
  /**
464
- * This enum is used interally for processing the layout constraints. We use
465
- * an enum to avoid magic strings.
512
+ * Color in red (0-255), green (0-255), blue (0-255), alpha (0-1) format. Must be numeric array of length 4.
466
513
  */
467
- declare enum ConstraintType {
468
- topToTopOf = "topToTopOf",
469
- topToBottomOf = "topToBottomOf",
470
- bottomToTopOf = "bottomToTopOf",
471
- bottomToBottomOf = "bottomToBottomOf",
472
- startToStartOf = "startToStartOf",
473
- startToEndOf = "startToEndOf",
474
- endToEndOf = "endToEndOf",
475
- endToStartOf = "endToStartOf"
476
- }
514
+ declare type RgbaColor = [number, number, number, number];
477
515
 
478
- declare enum Dimensions {
479
- MATCH_CONSTRAINT = 0
516
+ interface DrawableOptions {
517
+ anchorPoint?: Point;
518
+ zPosition?: number;
480
519
  }
481
520
 
482
521
  interface SceneOptions extends EntityOptions, DrawableOptions {
522
+ /** Background color of the scene. Default is Constants.DEFAULT_SCENE_BACKGROUND_COLOR (WebColors.WhiteSmoke) */
483
523
  backgroundColor?: RgbaColor;
484
524
  }
485
525
 
486
- declare class Scene extends Entity implements IDrawable {
526
+ declare class Scene extends Entity implements IDrawable, SceneOptions {
487
527
  readonly type = EntityType.scene;
488
528
  isDrawable: boolean;
489
529
  anchorPoint: Point;
@@ -499,8 +539,7 @@ declare class Scene extends Entity implements IDrawable {
499
539
  *
500
540
  * @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.
501
541
  *
502
- * @param options
503
- * @see {@link SceneOptions}
542
+ * @param options - {@link SceneOptions}
504
543
  */
505
544
  constructor(options?: SceneOptions);
506
545
  initialize(): void;
@@ -509,19 +548,26 @@ declare class Scene extends Entity implements IDrawable {
509
548
  get backgroundColor(): RgbaColor;
510
549
  set backgroundColor(backgroundColor: RgbaColor);
511
550
  /**
512
- * Code that will be called every time the screen is shown.
551
+ * Code that will be called every time the screen is first presented.
513
552
  *
514
- * @remarks Use this callback to "reset" entities to their initial state. For example, if a screen 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 screen may have been displayed. In addition, if entities should vary in each iteration, that should be done here.
553
+ * @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.
515
554
  *
516
- * @param codeCallback
555
+ * @param callback
517
556
  */
518
- setup(codeCallback: (scene: Scene) => void): void;
557
+ setup(callback: (scene: Scene) => void): void;
519
558
  draw(canvas: Canvas): void;
520
559
  }
521
560
 
522
561
  declare abstract class Transition {
523
562
  abstract type: TransitionType;
524
563
  duration: number;
564
+ /**
565
+ * Creates a scene transition in which the outgoing scene slides out and the incoming scene slides in, as if the incoming scene pushes it.
566
+ *
567
+ * @param direction - TransitionDirection in which the push action goes
568
+ * @param duration - Duration, in millis, of the transition
569
+ * @returns
570
+ */
525
571
  static push(direction: TransitionDirection, duration: number): PushTransition;
526
572
  }
527
573
  declare class PushTransition extends Transition {
@@ -544,10 +590,28 @@ declare class SceneTransition {
544
590
  constructor(scene: Scene, transition?: Transition | undefined);
545
591
  }
546
592
 
593
+ interface TrialSchema {
594
+ [key: string]: PropertySchema;
595
+ }
596
+ interface PropertySchema {
597
+ type: "number" | "string" | "boolean" | "object";
598
+ description?: string;
599
+ }
600
+
547
601
  /**
548
602
  * Options to specify HTML canvas, set game canvas size, and load game assets.
549
603
  */
550
- interface GameInitOptions {
604
+ interface GameOptions {
605
+ /** Human-friendly name of this game */
606
+ name: string;
607
+ /** Version of this game */
608
+ version?: string;
609
+ /** Uri (repository, webpage, or other location where full information about the game can be found) */
610
+ uri?: string;
611
+ /** Brief description of game */
612
+ shortDescription?: string;
613
+ /** Full description of game */
614
+ longDescription?: string;
551
615
  /** Id of the HTML canvas that game will be drawn on. If not provided, the first canvas found will be used */
552
616
  canvasId?: string;
553
617
  /** Width of game canvas */
@@ -557,13 +621,13 @@ interface GameInitOptions {
557
621
  /** Stretch to fill screen? Default is false */
558
622
  stretch?: boolean;
559
623
  /** Schema of trial data; JSON object where key is variable name, value is data type */
560
- trialSchema?: object;
624
+ trialSchema?: TrialSchema;
561
625
  /** Default game parameters; JSON object where key is the game parameter, value is default value */
562
- defaultParameters?: object;
626
+ parameters?: GameParameters;
563
627
  /** String array of urls from which to load fonts. The first element will be the default font */
564
628
  fontUrls?: Array<string>;
565
- /** Array of SvgImage objects to render and load */
566
- svgImages?: SvgImage[];
629
+ /** Array of BrowserImage objects to render and load */
630
+ images?: Array<BrowserImage>;
567
631
  /** Show FPS in upper left corner? Default is false */
568
632
  showFps?: boolean;
569
633
  /** Color of the html body, if the game does not fill the screen. Useful for showing scene boundaries. Default is the scene background color */
@@ -578,25 +642,20 @@ interface TrialData {
578
642
  interface Metadata {
579
643
  userAgent?: string;
580
644
  }
581
- interface GameData {
582
- trials: Array<TrialData>;
583
- metadata: Metadata;
584
- }
585
- interface LifecycleCallbacks {
586
- trialComplete: (trialNumber: number, data: GameData, trialSchema: object) => void;
587
- allTrialsComplete: (data: GameData, trialSchema: object) => void;
588
- }
589
- declare class Game {
645
+ declare class Game implements Activity {
646
+ _canvasKit?: CanvasKit;
647
+ _session?: Session;
648
+ uuid: string;
649
+ options: GameOptions;
650
+ constructor(options: GameOptions, specifiedParameters?: any);
651
+ get canvasKit(): CanvasKit;
652
+ set canvasKit(canvasKit: CanvasKit);
653
+ get session(): Session;
654
+ set session(session: Session);
590
655
  entryScene?: Scene | string;
591
- parameters: any;
592
- private defaultParameters;
593
656
  data: GameData;
594
- trialNumber: number;
595
- trialSchema: {};
596
- lifecycle: LifecycleCallbacks;
597
- private trialSchemaMap;
657
+ trialIndex: number;
598
658
  private htmlCanvas?;
599
- private scratchHtmlCanvas?;
600
659
  private surface?;
601
660
  private showFps?;
602
661
  private bodyBackgroundColor?;
@@ -611,40 +670,25 @@ declare class Game {
611
670
  private animationFramesRequested;
612
671
  private limitFps;
613
672
  private unitTesting;
673
+ private gameStopRequested;
614
674
  canvasCssWidth: number;
615
675
  canvasCssHeight: number;
616
676
  private scenes;
617
677
  private incomingSceneTransitions;
618
678
  private currentSceneSnapshot?;
619
- /**
620
- * Asynchronously initializes the game engine and load assets
621
- *
622
- * @param gameInitOptions
623
- * @returns Promise<void>
624
- */
625
- init(gameInitOptions: GameInitOptions): Promise<void>;
626
- /**
627
- * Provide a callback function to be invoked when a trial has completed.
628
- * It is the responsibility of the the game programmer to call this
629
- * at the appropriate time. It is not triggered automatically.
630
- * @param codeCallback
631
- */
632
- onTrialComplete(codeCallback: (trialNumber: number, data: GameData, trialSchema: object) => void): void;
633
- /**
634
- * Provide a callback function to be invoked when all trials are complete.
635
- * It is the responsibility of the the game programmer to call this
636
- * at the appropriate time. It is not triggered automatically.
637
- * @param codeCallback
638
- */
639
- onAllTrialsComplete(codeCallback: (data: GameData) => void): void;
640
679
  /**
641
680
  * Adds a scene to the game.
642
681
  *
643
- * @remarks A scene, and its children entities, cannot be preseneted unless it has been added to the game object.
682
+ * @remarks A scene, and its children entities, cannot be presented unless it has been added to the game object.
644
683
  *
645
684
  * @param scene
646
685
  */
647
686
  addScene(scene: Scene): void;
687
+ /**
688
+ * Adds multiple scenes to the game.
689
+ *
690
+ * @param scenes
691
+ */
648
692
  addScenes(scenes: Array<Scene>): void;
649
693
  /**
650
694
  * Specifies the scene that will be presented upon the next frame draw.
@@ -654,10 +698,8 @@ declare class Game {
654
698
  */
655
699
  presentScene(scene: string | Scene, transition?: Transition): void;
656
700
  /**
657
- * Gets the value of the specified game parameter. If the value was not
658
- * provided in the parameters property above, then return the value in
659
- * defaultParameters. If the parameterName is still not found, then
660
- * throw exception.
701
+ * Gets the value of the game parameter. If parameterName
702
+ * is not found, then throw exception.
661
703
  * @param parameterName - the name of the game parameter whose value is requested
662
704
  * @returns
663
705
  */
@@ -668,13 +710,37 @@ declare class Game {
668
710
  * @param entryScene - The scene (Scene object or its string name) to display when the game starts
669
711
  */
670
712
  start(entryScene?: Scene | string): void;
671
- initData(trialSchema: object): void;
713
+ stop(): void;
714
+ initData(): void;
715
+ /**
716
+ * Adds data to the game's TrialData object.
717
+ *
718
+ * @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.
719
+ *
720
+ * @param variableName - variable to be set
721
+ * @param value - value of the variable to set
722
+ */
672
723
  addTrialData(variableName: string, value: any): void;
673
- private loadCanvasKit;
724
+ /**
725
+ * Should be called when the current trial has completed. It will
726
+ * also increment the trial index.
727
+ * Calling this will trigger the onTrialComplete callback function,
728
+ * if one was provided in SessionOptions. This is how the game communicates
729
+ * trial data to the parent session, which can then save or process the data.
730
+ * It is the responsibility of the the game programmer to call this at
731
+ * the appropriate time. It is not triggered automatically.
732
+ */
733
+ trialComplete(): void;
734
+ /**
735
+ * Should be called when the current game has ended. This will trigger
736
+ * the onGameEnd callback function, if one was provided in SessionOptions.
737
+ * This is how the game communicates its ended or "finished" state to the
738
+ * parent session.
739
+ * It is the responsibility of the the game programmer to call this at
740
+ * the appropriate time. It is not triggered automatically.
741
+ */
742
+ end(): void;
674
743
  private setupHtmlCanvases;
675
- private fetchFonts;
676
- private renderSvgImages;
677
- private loadFonts;
678
744
  private setupCanvasKitSurface;
679
745
  private setupFpsFont;
680
746
  private setupEventHandlers;
@@ -687,27 +753,174 @@ declare class Game {
687
753
  private animateSceneTransition;
688
754
  private drawFps;
689
755
  /**
690
- * Creates a tap listener for an entity based on the entity name
756
+ * Creates an event listener for an entity based on the entity name
691
757
  *
692
- * @remarks Typically, tap listeners will be created using the onTap() method of each entity. This alternative allows creation with entity name.
758
+ * @remarks Typically, event listeners will be created using a method specific to the event, such as onTapDown(). This alternative allows creation with entity name.
693
759
  *
694
- * @param entityName
695
- * @param codeCallback
696
- * @param replaceExistingCodeCallback
760
+ * @param eventType - the type of event to listen for, e.g., "tapdown"
761
+ * @param entityName - the entity name for which an event will be listened
762
+ * @param callback
763
+ * @param replaceExistingCallback
697
764
  */
698
- createTapListener(entityName: string, codeCallback: (tapEvent: TapEvent) => void, replaceExistingCodeCallback?: boolean): void;
765
+ createEventListener(eventType: string, entityName: string, callback: (event: EntityEvent) => void, replaceExistingCallback?: boolean): void;
699
766
  /**
700
767
  * Returns array of all entities that have been added to the game object.
701
768
  */
702
769
  get entities(): Array<Entity>;
703
770
  private htmlCanvasMouseDownHandler;
704
771
  private htmlCanvasTouchStartHandler;
772
+ private sceneCanReceiveUserInteraction;
705
773
  private processTaps;
706
774
  private handleEntityTapped;
707
775
  private tapIsWithinEntityBounds;
708
776
  private calculateEntityAbsoluteBoundingBox;
709
777
  }
710
778
 
779
+ interface GameData {
780
+ trials: Array<TrialData>;
781
+ metadata: Metadata;
782
+ }
783
+
784
+ interface GameTrialEvent extends GameEvent {
785
+ trialIndex: number;
786
+ trialSchema: TrialSchema;
787
+ gameData: GameData;
788
+ gameParameters: GameParameters;
789
+ }
790
+
791
+ interface GameCallbacks {
792
+ /** Callback executed when the current game has ended. */
793
+ onGameEnd?: (event: GameLifecycleEvent) => void;
794
+ /** Callback executed when a game trial has completed. */
795
+ onGameTrialComplete?: (event: GameTrialEvent) => void;
796
+ }
797
+
798
+ interface SessionOptions {
799
+ /** The activities that compose this session */
800
+ activities: Array<Activity>;
801
+ /** Callbacks executed when trials are completed and when game ends */
802
+ gameCallbacks?: GameCallbacks;
803
+ }
804
+
805
+ declare class Session {
806
+ options: SessionOptions;
807
+ fontManager: FontManager;
808
+ imageManager: ImageManager;
809
+ currentActivity?: Activity;
810
+ uuid: string;
811
+ private canvasKit?;
812
+ /**
813
+ * A Session contains one or more activities; currently, the only
814
+ * class that implements Activity is Game, but Survey is planned.
815
+ * The session manages the start and stop of activities, and
816
+ * advancement to next activity
817
+ *
818
+ * @param options
819
+ */
820
+ constructor(options: SessionOptions);
821
+ /**
822
+ * Asynchronously initializes the m2c2kit engine and loads assets
823
+ */
824
+ init(): Promise<void>;
825
+ /**
826
+ * Starts the session and starts the first activity.
827
+ */
828
+ start(): void;
829
+ /**
830
+ * Stops the current activity and advances to next activity in the session.
831
+ * If there is no activity after the current activity, throws error
832
+ */
833
+ advanceToNextActivity(): void;
834
+ /**
835
+ * Gets the next activity after the current one, or undefined if
836
+ * this is the last activity.
837
+ */
838
+ get nextActivity(): Activity | undefined;
839
+ private logStartingActivity;
840
+ /**
841
+ * Gets asynchronous assets, including initialization of canvaskit wasm,
842
+ * fetching of fonts from specified urls, and rendering and fetching
843
+ * of images
844
+ * @returns
845
+ */
846
+ private getAsynchronousAssets;
847
+ private loadCanvasKit;
848
+ private loadAssets;
849
+ private assignCanvasKit;
850
+ private getFontsConfigurationFromGames;
851
+ private getImagesConfigurationFromGames;
852
+ }
853
+
854
+ interface Activity {
855
+ /** Starts the activity */
856
+ start(): void;
857
+ /** Stops the activity */
858
+ stop(): void;
859
+ /** The activity's parent session */
860
+ session: Session;
861
+ /** The activity's unique identifier. NOTE: This is newly generated each session. The uuid for an activity will vary across sessions. */
862
+ uuid: string;
863
+ }
864
+
865
+ interface CompositeOptions extends EntityOptions, DrawableOptions {
866
+ }
867
+
868
+ declare abstract class Composite extends Entity implements IDrawable {
869
+ readonly type = EntityType.composite;
870
+ compositeType: string;
871
+ isDrawable: boolean;
872
+ anchorPoint: Point;
873
+ zPosition: number;
874
+ /**
875
+ * Base Drawable object for creating custom entities ("composites") composed of primitive entities.
876
+ *
877
+ * @param options
878
+ */
879
+ constructor(options?: CompositeOptions);
880
+ initialize(): void;
881
+ update(): void;
882
+ draw(canvas: Canvas): void;
883
+ }
884
+
885
+ /**
886
+ * Reasonable defaults to use if values are not specified.
887
+ */
888
+ declare class Constants {
889
+ static readonly FPS_DISPLAY_TEXT_FONT_SIZE = 12;
890
+ static readonly FPS_DISPLAY_TEXT_COLOR: RgbaColor;
891
+ static readonly FPS_DISPLAY_UPDATE_INTERVAL = 500;
892
+ static readonly DEFAULT_SCENE_BACKGROUND_COLOR: RgbaColor;
893
+ static readonly DEFAULT_SHAPE_FILL_COLOR: RgbaColor;
894
+ static readonly DEFAULT_FONT_COLOR: RgbaColor;
895
+ static readonly DEFAULT_FONT_SIZE = 16;
896
+ static readonly LIMITED_FPS_RATE = 5;
897
+ }
898
+
899
+ /**
900
+ * This enum is used interally for processing the layout constraints. We use
901
+ * an enum to avoid magic strings.
902
+ */
903
+ declare enum ConstraintType {
904
+ topToTopOf = "topToTopOf",
905
+ topToBottomOf = "topToBottomOf",
906
+ bottomToTopOf = "bottomToTopOf",
907
+ bottomToBottomOf = "bottomToBottomOf",
908
+ startToStartOf = "startToStartOf",
909
+ startToEndOf = "startToEndOf",
910
+ endToEndOf = "endToEndOf",
911
+ endToStartOf = "endToStartOf"
912
+ }
913
+
914
+ declare enum Dimensions {
915
+ MATCH_CONSTRAINT = 0
916
+ }
917
+
918
+ interface FontData {
919
+ gameUuid: string;
920
+ fontUrl: string;
921
+ fontArrayBuffer: ArrayBuffer;
922
+ }
923
+
711
924
  interface IText {
712
925
  text?: string;
713
926
  fontName?: string;
@@ -716,9 +929,13 @@ interface IText {
716
929
  }
717
930
 
718
931
  interface TextOptions {
932
+ /** Text to be displayed */
719
933
  text?: string;
934
+ /** Name of font to use for text. Must have been previously loaded */
720
935
  fontName?: string;
936
+ /** Color of text. Default is Constants.DEFAULT_FONT_COLOR (WebColors.Black) */
721
937
  fontColor?: RgbaColor;
938
+ /** Size of text. Default is Constants.DEFAULT_FONT_SIZE (16) */
722
939
  fontSize?: number;
723
940
  }
724
941
 
@@ -729,12 +946,15 @@ declare enum LabelHorizontalAlignmentMode {
729
946
  }
730
947
 
731
948
  interface LabelOptions extends EntityOptions, DrawableOptions, TextOptions {
949
+ /** Horizontal alignment of label text. see {@link LabelHorizontalAlignmentMode}. Default is LabelHorizontalAlignmentMode.center */
732
950
  horizontalAlignmentMode?: LabelHorizontalAlignmentMode;
951
+ /** Maximum width of label text before wrapping occurs. Default is the canvas width */
733
952
  preferredMaxLayoutWidth?: number;
953
+ /** Background color of label text. Default is no background color */
734
954
  backgroundColor?: RgbaColor;
735
955
  }
736
956
 
737
- declare class Label extends Entity implements IDrawable, IText {
957
+ declare class Label extends Entity implements IDrawable, IText, LabelOptions {
738
958
  readonly type = EntityType.label;
739
959
  isDrawable: boolean;
740
960
  isText: boolean;
@@ -752,9 +972,9 @@ declare class Label extends Entity implements IDrawable, IText {
752
972
  /**
753
973
  * Single or multi-line text formatted and rendered on the screen.
754
974
  *
755
- * @remarks Label (in contrast to TextLine) has enhanced text support for line wrapping, centering/alignment, and background colors.
975
+ * @remarks Label (in contrast to TextLine) has enhanced text support for line wrapping, centering/alignment, and background colors.
756
976
  *
757
- * @param options
977
+ * @param options - {@link LabelOptions}
758
978
  */
759
979
  constructor(options?: LabelOptions);
760
980
  initialize(): void;
@@ -825,11 +1045,17 @@ declare class RandomDraws {
825
1045
  }
826
1046
 
827
1047
  interface RectOptions {
1048
+ /** Position of rectangle */
828
1049
  origin?: Point;
1050
+ /** Size of rectangle */
829
1051
  size?: Size;
1052
+ /** X coordinate of rectangle position; this can be used instead of setting the origin property */
830
1053
  x?: number;
1054
+ /** Y coordinate of rectangle position; this can be used instead of setting the origin property */
831
1055
  y?: number;
1056
+ /** Width of rectangle; this can be used instead of setting the size property */
832
1057
  width?: number;
1058
+ /** Height of rectangle; this can be used instead of setting the size property */
833
1059
  height?: number;
834
1060
  }
835
1061
 
@@ -844,11 +1070,17 @@ declare class Rect implements RectOptions {
844
1070
  }
845
1071
 
846
1072
  interface ShapeOptions extends EntityOptions, DrawableOptions {
1073
+ /** If provided, shape will be a circle with given radius */
847
1074
  circleOfRadius?: number;
1075
+ /** If provided, shape will be a rectangle as specified in {@link Rect} */
848
1076
  rect?: Rect;
1077
+ /** Radius of rectangle's corners */
849
1078
  cornerRadius?: number;
1079
+ /** Color with which to fill shape. Default is Constants.DEFAULT_SHAPE_FILL_COLOR (WebColors.Red) */
850
1080
  fillColor?: RgbaColor;
1081
+ /** Color with which to outline shape. Default is no color */
851
1082
  strokeColor?: RgbaColor;
1083
+ /** Width of outline. Default is undefined */
852
1084
  lineWidth?: number;
853
1085
  }
854
1086
 
@@ -858,7 +1090,7 @@ declare enum ShapeType {
858
1090
  circle = "Circle"
859
1091
  }
860
1092
 
861
- declare class Shape extends Entity implements IDrawable {
1093
+ declare class Shape extends Entity implements IDrawable, ShapeOptions {
862
1094
  readonly type = EntityType.shape;
863
1095
  isDrawable: boolean;
864
1096
  isShape: boolean;
@@ -874,9 +1106,9 @@ declare class Shape extends Entity implements IDrawable {
874
1106
  private fillColorPaint?;
875
1107
  private strokeColorPaint?;
876
1108
  /**
877
- * Rectangular shape
1109
+ * Rectangular or circular shape
878
1110
  *
879
- * @param options
1111
+ * @param options - {@link ShapeOptions}
880
1112
  */
881
1113
  constructor(options?: ShapeOptions);
882
1114
  initialize(): void;
@@ -889,10 +1121,11 @@ declare class Shape extends Entity implements IDrawable {
889
1121
  }
890
1122
 
891
1123
  interface SpriteOptions extends EntityOptions, DrawableOptions {
1124
+ /** Name of image to use for sprite. Must have been previously loaded */
892
1125
  imageName?: string;
893
1126
  }
894
1127
 
895
- declare class Sprite extends Entity implements IDrawable {
1128
+ declare class Sprite extends Entity implements IDrawable, SpriteOptions {
896
1129
  readonly type = EntityType.sprite;
897
1130
  isDrawable: boolean;
898
1131
  anchorPoint: Point;
@@ -904,7 +1137,7 @@ declare class Sprite extends Entity implements IDrawable {
904
1137
  *
905
1138
  * @remarks Sprites must be loaded during the Game.init() method prior to their use.
906
1139
  *
907
- * @param options
1140
+ * @param options - {@link SpriteOptions}
908
1141
  */
909
1142
  constructor(options?: SpriteOptions);
910
1143
  initialize(): void;
@@ -926,7 +1159,7 @@ interface TextLineOptions extends EntityOptions, DrawableOptions, TextOptions {
926
1159
  width?: number;
927
1160
  }
928
1161
 
929
- declare class TextLine extends Entity implements IDrawable, IText {
1162
+ declare class TextLine extends Entity implements IDrawable, IText, TextLineOptions {
930
1163
  readonly type = EntityType.textline;
931
1164
  isDrawable: boolean;
932
1165
  isText: boolean;
@@ -943,7 +1176,7 @@ declare class TextLine extends Entity implements IDrawable, IText {
943
1176
  *
944
1177
  * @remarks TextLine has no paragraph formatting options; Label will be preferred in most use cases.
945
1178
  *
946
- * @param options
1179
+ * @param options - {@link TextLineOptions}
947
1180
  */
948
1181
  constructor(options?: TextLineOptions);
949
1182
  get text(): string;
@@ -977,6 +1210,10 @@ declare class Timer {
977
1210
  static RemoveAll(): void;
978
1211
  }
979
1212
 
1213
+ declare class Uuid {
1214
+ static generate(): string;
1215
+ }
1216
+
980
1217
  declare class WebColors {
981
1218
  static Transparent: RgbaColor;
982
1219
  static MediumVioletRed: RgbaColor;
@@ -1122,4 +1359,4 @@ declare class WebColors {
1122
1359
  static RebeccaPurple: RgbaColor;
1123
1360
  }
1124
1361
 
1125
- export { Action, Composite, CompositeOptions, Constants, ConstraintType, Constraints, CustomAction, CustomActionOptions, Dimensions, DrawableOptions, Entity, EntityOptions, EntityType, FontData, FontManager, Game, GameInitOptions, GlobalVariables, GroupAction, IDrawable, IText, ImageManager, Label, LabelHorizontalAlignmentMode, LabelOptions, Layout, LayoutConstraint, LoadedImage, MoveAction, MoveActionOptions, Point, PushTransition, RandomDraws, Rect, RectOptions, RgbaColor, ScaleAction, ScaleActionOptions, Scene, SceneOptions, SceneTransition, SequenceAction, Shape, ShapeOptions, ShapeType, Size, Sprite, SpriteOptions, Story, StoryOptions, SvgImage, TapEvent, TapListener, TextLine, TextLineOptions, TextOptions, Timer, Transition, TransitionDirection, TransitionType, WaitAction, WaitActionOptions, WebColors, handleInterfaceOptions };
1362
+ export { Action, Activity, BrowserImage, Composite, CompositeOptions, Constants, ConstraintType, Constraints, CustomAction, CustomActionOptions, DefaultParameter, Dimensions, DrawableOptions, Entity, EntityEventListener, EntityOptions, EntityType, FontData, FontManager, Game, GameCallbacks, GameData, GameLifecycleEvent, GameOptions, GameParameters, GameTrialEvent, GlobalVariables, GroupAction, IDrawable, IText, ImageManager, Label, LabelHorizontalAlignmentMode, LabelOptions, Layout, LayoutConstraint, LoadedImage, Metadata, MoveAction, MoveActionOptions, Point, PropertySchema, PushTransition, RandomDraws, Rect, RectOptions, RgbaColor, ScaleAction, ScaleActionOptions, Scene, SceneOptions, SceneTransition, SequenceAction, Session, SessionOptions, Shape, ShapeOptions, ShapeType, Size, Sprite, SpriteOptions, Story, StoryOptions, TextLine, TextLineOptions, TextOptions, Timer, Transition, TransitionDirection, TransitionType, TrialData, TrialSchema, Uuid, WaitAction, WaitActionOptions, WebColors, handleInterfaceOptions };