Newer
Older
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
protected_dirs: ["assets", "style", "views", "standard"],
default_meta_keys: ["title", "description", "image", "open_graph", "json_ld"],
},
};
images_url: `/assets/images`,
data_url: `/assets/data`,
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const MtlAnimation = require("./model/animation");
const MentaloEngine = require("./mentalo-engine");
const MtlScene = require("./model/scene");
const MtlGame = require("./model/game");
const MtlSoundTrack = require("./model/sound-track");
const SCENE_TYPES = require("./model/scene-types");
const MtlChoice = require("./model/choice");
const MtlGameObject = require("./model/game-object");
const FrameRateController = require("./lib/frame-rate-controller");
const font_tools = require("./lib/font-tools");
const color_tools = require("./lib/color-tools");
const shape_tools = require("./lib/shape-tools");
module.exports = {
MentaloEngine,
MtlAnimation,
MtlScene,
MtlGame,
MtlSoundTrack,
SCENE_TYPES,
MtlChoice,
MtlGameObject,
FrameRateController,
font_tools,
color_tools,
shape_tools,
};
},{"./lib/color-tools":5,"./lib/font-tools":6,"./lib/frame-rate-controller":7,"./lib/shape-tools":8,"./mentalo-engine":9,"./model/animation":10,"./model/choice":11,"./model/game":13,"./model/game-object":12,"./model/scene":17,"./model/scene-types":16,"./model/sound-track":18}],5:[function(require,module,exports){
"use strict";
/**
* Helpers to work with color values
*/
/**
* Get a RGB color value in String from either "rgb(x,x,x)" or #xxxxxx
* @param {String} color A RGB color value as String in the form: #ffffff or rgb(x,x,x)
* @returns {Array<Uint8>} An array of 3 values from 0 to 256 for [RED, GREEN, BLUE]
*/
function color_str_to_rgb_array(color) {
color = color.toLowerCase(0);
if (color.includes("rgb")) {
return color.replaceAll(/[a-z\(\)w]/g, "")
.split(",")
.slice(0, 3)
.map(n => parseInt(n));
} else {
return color.replace("#", "")
.match(/.{0,2}/g)
.slice(0, 3)
.map(hex => parseInt(hex, 16));
}
}
/**
* @param {String} color A color value (#xxxxxx or rbg(x,x,x))
* @returns The average between each tone of the given color.
*/
function get_average_rgb_color_tone(color) {
return color_str_to_rgb_array(color).reduce((tot, n) => tot + n / 3, 0);
}
/**
* Gets an array of 3 8bits integers for red green and blue and and return a color value as an hexadecimal string #xxxxxx
* @param {Array<Uint8>} rgb
* @returns {String} The hexacdecimal rgb value of the color including the hash character: #xxxxxx
*/
function rgb_array_to_hex(rgb) {
return `#${rgb.slice(0, 3).map(n => {
const hex = n.toString(16);
return hex.length < 2 ? '0' + hex : hex;
}).join('')}`;
}
/**
* Gets an array of 4 8bits integers for red green blue and transparency channel and return a color value as an hexadecimal string #xxxxxx
* @param {Array<Uint8>} rgb
* @returns {String} The hexacdecimal rgba value of the color including the hash character: #xxxxxxxx
*/
function rgba_array_to_hex(rgba) {
rgba = rgba.length === 4 ? rgba : rgba.concat([255])
return `#${rgba.slice(0, 4).map(n => {
const hex = n.toString(16);
return hex.length < 2 ? '0' + hex : hex;
}).join('')}`;
}
/**
* Gets a background color as argument and return a calculated optimal foreground color.
* For example if the background is dark the function will return a lighten version of the background.
* @param {String} base_color A RGB color value in hexadecimal form: #ffffff
* @returns
*/
function get_optimal_visible_foreground_color(base_color) {
// create a 2D 1px canvas context
const tmp_canvas = document.createElement("canvas");
tmp_canvas.width = 1;
tmp_canvas.height = 1;
const ctx = tmp_canvas.getContext("2d");
// fill it with the given color
ctx.fillStyle = base_color;
ctx.fillRect(0, 0, 1, 1);
// Get either a semi-transparent black or semi-transparent white regarding the base color is above or below an avg of 127
const superpo_color = get_average_rgb_color_tone(base_color) > 127 ? "#0000003f" : "#ffffff3f";
// Fill the pixel with the semi-transparent black or white on top of the base color
ctx.fillStyle = superpo_color;
ctx.fillRect(0, 0, 1, 1);
// Return the flatten result of the superposition
return rgb_array_to_hex(Array.from(ctx.getImageData(0, 0, 1, 1).data));
}
/**
* @param {Array<Uint8; 4>} col1 A RGBA color value as an array of 4 0 to 256 integers
* @param {Array<Uint8; 4>} col2 A RGBA color value as an array of 4 0 to 256 integers
* @returns {Boolean} true if the 2 colors are equals
*/
function same_rgba(col1, col2) {
return col1[0] === col2[0]
&& col1[1] === col2[1]
&& col1[2] === col2[2]
&& col1[3] === col2[3];
}
module.exports = {
get_average_rgb_color_tone,
get_optimal_visible_foreground_color,
color_str_to_rgb_array,
rgb_array_to_hex,
rgba_array_to_hex,
same_rgba,
};
},{}],6:[function(require,module,exports){
"use strict";
/**
* Helpers to works with default web fonts
*/
const FONT_FAMILIES = [
{
category: "Sans serif", values: [
{ value: "sans-serif", text: "sans-serif" },
{ text: "Arial", value: "Arial, sans-serif" },
{ text: "Helvetica", value: "Helvetica, sans-serif" },
{ text: "Verdana", value: "Verdana, sans-serif" },
{ text: "Trebuchet MS", value: "Trebuchet MS, sans-serif" },
{ text: "Noto Sans", value: "Noto Sans, sans-serif" },
{ text: "Gill Sans", value: "Gill Sans, sans-serif" },
{ text: "Avantgarde", value: "Avantgarde, TeX Gyre Adventor, URW Gothic L, sans-serif" },
{ text: "Optima", value: "Optima, sans-serif" },
{ text: "Arial Narrow", value: "Arial Narrow, sans-serif" }
],
},
{
category: "Serif", values: [
{ text: "serif", value: "serif" },
{ text: "Times", value: "Times, Times New Roman, serif" },
{ text: "Didot", value: "Didot, serif" },
{ text: "Georgia", value: "Georgia, serif" },
{ text: "Palatino", value: "Palatino, URW Palladio L, serif" },
{ text: "Bookman", value: "Bookman, URW Bookman L, serif" },
{ text: "New Century Schoolbook", value: "New Century Schoolbook, TeX Gyre Schola, serif" },
{ text: "American Typewriter", value: "American Typewriter, serif" }
],
},
{
category: "Monospace", values: [
{ text: "monospace", value: "monospace" },
{ text: "Andale Mono", value: "Andale Mono, monospace" },
{ text: "Courrier New", value: "Courier New, monospace" },
{ text: "Courrier", value: "Courier, monospace" },
{ text: "FreeMono", value: "FreeMono, monospace" },
{ text: "OCR A Std", value: "OCR A Std, monospace" },
{ text: "DejaVu Sans Mono", value: "DejaVu Sans Mono, monospace" },
],
},
{
category: "Cursive", values: [
{ text: "cursive", value: "cursive" },
{ text: "Comic Sans MS", value: "Comic Sans MS, Comic Sans, cursive" },
{ text: "Apple Chancery", value: "Apple Chancery, cursive" },
{ text: "Bradley Hand", value: "Bradley Hand, cursive" },
{ text: "Brush Script MT", value: "Brush Script MT, Brush Script Std, cursive" },
{ text: "Snell Roundhand", value: "Snell Roundhand, cursive" },
{ text: "URW Chancery L", value: "URW Chancery L, cursive" },
],
}
];
const TEXT_ALIGN_OPTIONS = [
{ value: "left", text: "Left" }, // TODO trad or icon
{ value: "right", text: "Right" },
{ value: "center", text: "Center" },
];
const FONT_STYLE_OPTIONS = [
{ value: "normal", text: "Normal" },
{ value: "italic", text: "Italic" }, // TODO trad or icon
];
const FONT_WEIGHT_OPTIONS = [
{ value: "1", text: "Thin" },
{ value: "normal", text: "Normal" },
{ value: "900", text: "Bold" },
];
/**
* Gets an object description of a font and returns it formatted as a string that can be given to a 2D drawing context.
* Example : ctx.font = get_canvas_font({font_family:"monospace", font_size: 32})
* @param {Object} font_data An object description of the font settings, with font_size, font_family, font_style, font_weight.s
* @returns {String}
*/
function get_canvas_font(font_data = {}) {
const { font_size = 20, font_family = "sans-serif", font_style = "normal", font_weight = "normal" } = font_data;
const font_variant = "normal";
return `${font_style} ${font_variant} ${font_weight} ${font_size.toFixed()}px ${font_family}`;
}
/**
* @returns {Object} A map of all defined constants for font families, text align options, font styles and font weights.
*/
function get_font_options() {
return {
font_families: FONT_FAMILIES,
text_align_options: TEXT_ALIGN_OPTIONS,
font_style_options: FONT_STYLE_OPTIONS,
font_weight_options: FONT_WEIGHT_OPTIONS,
};
}
/**
* An approximation of the average width of a character for a 2D drawing context with a given font configuration.
* @param {CanvasRenderingContext2D} ctx
* @returns
*/
function get_canvas_char_size(ctx) {
const str = `Lorem ipsum dolor Sit amet, Consectetur adipiscing elit`;
const width = ctx.measureText(str).width / str.length;
const height = ctx.measureText("M").width * 1.1;
const text_line_height = height * 1.2;
return {
width,
height,
text_line_height,
}
}
module.exports = {
get_canvas_font,
get_font_options,
get_canvas_char_size,
FONT_FAMILIES,
TEXT_ALIGN_OPTIONS,
FONT_STYLE_OPTIONS,
FONT_WEIGHT_OPTIONS
};
},{}],7:[function(require,module,exports){
"use strict";
/**
* A little helper class to control the rendering frame rate
*/
class FrameRateController {
/**
* @param {Integer} fps The wanted frame rate in frame per second
*/
constructor(fps) {
this.tframe = performance.now();
this.interval = 1000 / fps; // convert in milliseconds
this.initial = true;
}
/**
* @returns {Boolean} true if the defined interval is elapsed.
*/
nextFrameReady() {
if (this.initial) {
this.initial = false;
return true;
}
const now = performance.now();
const elapsed = now - this.tframe;
const ready = elapsed > this.interval;
if (ready) {
this.tframe = now - (elapsed % this.interval);
}
return ready;
}
}
module.exports = FrameRateController;
},{}],8:[function(require,module,exports){
"use strict";
/**
* Draws a rectangle on a canvas 2D context with support of corner rounding and border options.
* @param {CanvasRenderingContext2D} ctx
* @param {Integer} x
* @param {Integer} y
* @param {Integer} width
* @param {Integer} height
* @param {Object} options
*/
function draw_rect(ctx, x, y, width, height, options = {
rounded_corners_radius: 0,
border: { width: 0, color: "rgba(0,0,0,0)" },
fill_color: "black",
}) {
const { rounded_corners_radius = 0, border = { width: 0, color: "rgba(0,0,0,0)" }, fill_color = "black", fill_image } = options;
const smallest_axis = Math.min(width, height);
const radius = rounded_corners_radius > smallest_axis / 2 ? smallest_axis / 2 : rounded_corners_radius;
ctx.save();
ctx.beginPath();
ctx.arc(x + radius, y + radius, radius, Math.PI, 3 * Math.PI / 2);
ctx.lineTo(x + width - radius, y);
ctx.arc(x + width - radius, y + radius, radius, 3 * Math.PI / 2, 0);
ctx.lineTo(x + width, y + height - radius);
ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI / 2);
ctx.lineTo(x + radius, y + height);
ctx.arc(x + radius, y + height - radius, radius, Math.PI / 2, Math.PI);
ctx.closePath();
ctx.clip();
if (fill_image) {
ctx.drawImage(
fill_image.src,
0, 0,
fill_image.src.width, fill_image.src.height,
fill_image.dx, fill_image.dy,
fill_image.dw, fill_image.dh,
)
} else {
ctx.fillStyle = fill_color;
ctx.fillRect(x, y, width, height);
}
if (border.width > 0) {
ctx.strokeStyle = border.color;
ctx.lineWidth = border.width;
ctx.stroke();
}
ctx.restore();
}
module.exports = {
draw_rect,
}
},{}],9:[function(require,module,exports){
"use strict";
const MtlGame = require("./model/game");
const SCENE_TYPES = require("./model/scene-types");
const MtlRender = require("./render/render");
const { supported_locales, get_translated } = require("./translation");
/**
* The encapsulating class of all the components of the Mentalo game engine.
* This is the class that should be used from outside to run a game.
*/
class MentaloEngine {
/**
* Initialize A MtlGame instance, populates it with the gama_data given as param.
* Initializes the DOM element to contain the rendering of the engine.
* Defines the listeners for Escape key and initialize a MtlRender instance.
* @param {Object} params
* Parameter params.game_data is required and should be the result of the exportation format of the Mentalo editor app.
*/
constructor(params) {
this.game = new MtlGame();
this.game.load_data(params.game_data);
this.game.on_load_resources(() => this.loading = false);
this.use_locale = params.use_locale && supported_locales.includes(params.use_locale)
? params.use_locale
: "en";
/**
* Allow to exit game by typing Escape or q
* @param {Event} e
*/
this.escape_listener = e => {
const k = e.key.toLowerCase();
(k === "escape" || k === "q") && this.quit();
};
window.addEventListener("keydown", this.escape_listener);
this.on_quit_game = function () {
if (this.used_default_container) {
this.container.remove();
}
window.removeEventListener("keydown", this.escape_listener);
params.on_quit_game && params.on_quit_game();
};
this.used_default_container = false;
this.container = params.container || (() => {
const el = document.createElement("div");
el.style.display = "flex";
el.style.justifyContent = "center";
el.style.alignItems = "center";
el.style.position = "absolute";
el.style.top = 0;
el.style.bottom = 0;
el.style.left = 0;
el.style.right = 0;
el.style.zIndex = 1000;
el.style.overflow = "hidden";
document.body.appendChild(el);
this.used_default_container = true
return el;
})();
this.render = new MtlRender({
container: this.container,
fullscreen: params.fullscreen,
frame_rate: params.frame_rate,
get_game_settings: this.get_game_settings.bind(this),
get_game_scenes: this.get_game_scenes.bind(this),
get_scene: this.get_scene.bind(this),
get_inventory: this.get_inventory.bind(this),
on_game_object_click: this.on_game_object_click.bind(this),
on_drop_inventory_object: this.on_drop_inventory_object.bind(this),
on_choice_click: this.on_choice_click.bind(this),
});
this.loading = true;
this.will_quit = false;
}
/**
* Returns a fragment of the game instance ui_options, which are the styling settings of the game interface.
* Can be the settings for text_boxes, choices_panel, inventory, etc.
* @param {String} key The key of the wanted interface settings.
* @returns {Object} The fragment of this.game.game_ui_options for the given key.
*/
get_game_settings(key) {
return this.game.game_ui_options[key];
}
/**
* @returns {Array<MtlScene>} Returns an array of the scenes of the game.
*/
get_game_scenes() {
return this.game.scenes;
}
/**
* @returns {MtlScene} The scene that is currently displayed
*/
get_scene() {
return this.game.get_scene();
}
/**
* Returns the game objects currently saved in the inventory.
* @returns {Set<MtlGameObject>}
*/
get_inventory() {
return this.game.state.inventory;
}
/**
* Sets the flag this.will_quit to true.
* This flag will be parsed in the rendering loop and the engine will then effectively exit the game calling __exit().
*/
quit() {
this.will_quit = true;
}
/**
* Clean the render instance, stops the rendering loop and calls the on_quit_game callback.
* This is called when the rendering loop reads the this.will_quit flag as true.
*/
__quit() {
window.cancelAnimationFrame(window.mentalo_engine_animation_id);
this.render.exit_fullscreen();
this.render.clear_event_listeners();
this.game.get_soundtrack().stop();
this.on_quit_game();
}
/**
* Initialize the rendering loop and the MtlRender instance.
* Also checks that the first loaded scene has an image to load.
* If it doesn't the game will exit immediately in order to avoid having a black screen.
* ( If the first scene doesn't have an image to load, the game.on_load_resource callback will
* never be called and the engine will remain in loading state. )
*/
init() {
window.requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame;
window.cancelAnimationFrame = window.cancelAnimationFrame
|| window.mozCancelAnimationFrame;
if (window.mentalo_engine_animation_id) {
window.cancelAnimationFrame(window.mentalo_engine_animation_id);
}
this.render.init();
if (this.game.get_scene().animation.empty) {
alert(get_translated("First scene has an empty image, game cannot be loaded", this.use_locale));
this.quit();
}
}
/**
* Clear the event listeners and rendering element related to the current scene from the MtlRender instance,
* And sets the game current scene state to a new index.
* @param {Integer} index
*/
go_to_scene(index) {
this.render.reset_user_error_popup();
this.render.clear_event_listeners();
this.game.get_soundtrack().stop();
this.game.go_to_scene(index);
this.render.clear_children();
this.render.reset_text_box_visibility();
}
/**
* Event listener for doubleclick on a game object.
* Adds the object to inventory.
* @param {MtlGameObject} obj
*/
on_game_object_click(obj) {
this.game.inventory_has_empty_slot() && this.game.add_object_to_inventory(obj);
}
/**
* All callback called from the inventory render component when an object image is clicked in the inventory.
* Removes the object from inventory.
* @param {MtlGameObject} obj
*/
on_drop_inventory_object(obj) {
this.game.remove_object_from_inventory(obj);
}
/**
* Callback called from the choices_panel render component.
* Handles the click on a choice.
* @param {MtlChoice} choice
* @returns
*/
on_choice_click(choice) {
const { destination_scene_index, use_objects } = choice;
if (destination_scene_index === -1) { // -1 is default index when the choice destination scene is not set.
this.render.set_user_error_popup({
text: get_translated("Destination scene has not been set.", this.use_locale),
});
return;
}
if (destination_scene_index === -2) { // -2 is the index used to indicate that destination scene is just the end of program.
this.quit()
return;
}
// Handle the case where the clicked choice requires some objects to be presents in the inventory.
if (use_objects.value) {
const inventory = this.get_inventory();
const objs = [];
for (const it of use_objects.items) {
const ob = Array.from(inventory).find(o => o.name === it.name);
if (ob) {
objs.push(ob);
} else {
this.render.set_user_error_popup({
text: use_objects.missing_object_message,
});
return;
}
}
objs.forEach(o => use_objects.items
.find(it => o.name === it.name)
.consume_object && this.game.consume_game_object(o));
}
this.go_to_scene(destination_scene_index);
}
/**
* Callback called when a scene of type "Cinematic" reaches end.
*/
on_cinematic_end() {
const scene = this.game.get_scene();
if (scene.end_cinematic_options.quit) {
this.quit();
} else if (scene.end_cinematic_options.destination_scene_index === -1) {
this.render.set_user_error_popup({
text: get_translated("Next scene has not been set.", this.use_locale),
on_close: this.quit.bind(this),
});
} else {
this.go_to_scene(scene.end_cinematic_options.destination_scene_index);
}
}
/**
* The rendering loop.
* Handles the different states of the engine (quit, loading or runnning normally)
* @returns The id of the registered window.requestAnimationFrame
*/
run_game() {
if (this.will_quit) {
this.__quit();
return;
} else if (this.loading) {
this.render.draw_loading();
} else {
if (this.get_scene()._type === SCENE_TYPES.CINEMATIC) {
this.game.update_cinematic_timeout();
if (this.game.is_cinematic_ended()) {
this.on_cinematic_end();
}
}
const sound_track = this.game.get_soundtrack();
if (sound_track.loaded && !sound_track.is_playing()) {
sound_track.play();
}
this.render.draw_game();
}
window.mentalo_engine_animation_id = requestAnimationFrame(this.run_game.bind(this));
}
}
module.exports = MentaloEngine;
},{"./model/game":13,"./model/scene-types":16,"./render/render":19,"./translation":20}],10:[function(require,module,exports){
"use strict";
const Loadable = require("./loadable");
/**
* The data type used for a MtlScene animation
*/
class MtlAnimation extends Loadable {
/**
* Initialize an empty instance of Image HtmlElement,
* and registers the onload callback to update the instance with the loaded image actual dimensions.
*/
constructor() {
super(new Image(), "image", "load");
this.image.onload = () => this.update_dimensions();
this.name = "";
this.dimensions = {
width: 0,
height: 0,
};
this.frame_nb = 1;
this.frame = 0;
this.speed = 1;
this.play_once = false;
this.initialized = false;
this.finished = false;
}
/**
* Copies the dimensions of the loaded image at the root level of the instance.
* Deletes the canvas dimensions precalculations created by the SceneAnimation component
*/
update_dimensions() {
this.dimensions = {
width: this.image.width / this.frame_nb,
height: this.image.height,
};
if (this.canvas_precalc) {
delete this.canvas_precalc;
}
}
/**
* Populates the instance with loaded litteral data.
* @param {Object} data
*/
init(data) {
this.empty = data.src === "";
this.name = data.name;
this.image.src = data.src;
this.frame_nb = data.frame_nb;
this.frame = 0;
this.speed = data.speed;
this.play_once = data.play_once;
this.initialized = true;
}
/**
* Increments the framcount argument if the animation next frame is ready to be rendered.
* @param {Integer} framecount
*/
update_frame(framecount) {
this.finished = this.play_once && this.frame === this.frame_nb - 1;
if (this.frame_nb > 1 && framecount % this.speed === 0 && !this.finished) {
this.frame = this.frame + 1 <= this.frame_nb - 1 ? this.frame + 1 : 0;
}
}
/**
* Reset the frame state.
*/
reset_frame() {
this.finished = false;
this.frame = 0;
}
}
module.exports = MtlAnimation;
},{"./loadable":15}],11:[function(require,module,exports){
"use strict";
/**
* The data type used for the choices of a MtlScene
*/
class MtlChoice {
/**
* Initializes the instance with given data or default empty data.
* @param {Object} data
*/
constructor(data = {
text: "",
destination_scene_index: -1,
use_objects: {
value: false,
items: [],
missing_object_message: "",
}
}) {
this.load_data(data);
}
/**
* Populates the instance with litteral description data
* @param {Object} data
*/
load_data(data) {
this.text = data.text;
this.destination_scene_index = data.destination_scene_index;
this.use_objects = data.use_objects;
}
}
module.exports = MtlChoice;
},{}],12:[function(require,module,exports){
"use strict";
const Loadable = require("./loadable");
/**
* The data type used for the game_objects field of a MtlScene
*/
class MtlGameObject extends Loadable {
/**
* Initializes the instance with an empty image and zero position.
*/
constructor() {
super(new Image(), "image", "load");
this.name = "";
this.position = { x: 0, y: 0 };
this.state = {};
}
/**
* Populates the instance with a litteral description data object
* @param {Object} data
*/
load_data(data) {
this.image.src = data.image;
this.name = data.name;
this.position = data.position;
}
/**
* @returns {Object<Integer, Integer} A {width, height} object for the dimensions of the image.
*/
get_dimensions() {
return {
width: this.image.width,
height: this.image.height,
}
}
/**
* Returns the bounding box coordinates of the object image as a {top, right, bottom, left} object.
* @returns {Object<Int, Int, Int, Int>}
*/
get_bounds() {
const dims = this.get_dimensions();
return {
top: this.position.y,
right: this.position.x + dims.width,
bottom: this.position.y + dims.height,
left: this.position.x,
}
}
}
module.exports = MtlGameObject;
},{"./loadable":15}],13:[function(require,module,exports){
"use strict";
const MtlScene = require("./scene");
const SCENE_TYPES = require("./scene-types");
/**
* The data type to encapsulate a loaded game.
*/
class MtlGame {
/**
* Initialize the instance with default data.
*/
constructor() {
this.name = "";
this.scenes = [new MtlScene()];
// Game interface styling preferences
this.game_ui_options = {
// The overall look of the innterface
general: {
background_color: "#000000",
animation_canvas_dimensions: {
width: 600,
ratio: "4:3",
height: function () {
const split_ratio = this.ratio.split(":").map(n => parseInt(n));
const factor = split_ratio[1] / split_ratio[0];
return Number((this.width * factor).toFixed());
},
},
},
// The text box displayed on top of a scene image if a message is defined
text_boxes: {
background_color: "#222222",
font_size: 20,
font_style: "normal",
font_weight: "normal",
font_family: "Arial, sans-serif",
font_color: "#ffffff",
text_align: "left",
padding: 20,
margin: 20,
border_width: 0,
rounded_corners_radius: 0,
},
// The panel containing the choices buttons below the scene image.
choices_panel: {
background_color: "#222222",
font_size: 20,
font_family: "sans",
font_color: "#ffffff",
font_style: "normal",
text_align: "left",
font_weight: "normal",
container_padding: 2,// unit em (font size related)
choice_padding: 1.2,// idem
active_choice_background_color: "rgba(255,255,255,.4)",
active_choice_border_width: 0,
active_choice_rounded_corners_radius: 0,
},
// the inventory grid drawn at the right of the scene image
inventory: {
background_color: "#222222",
columns: 1,
rows: 4,
gap: 10,
padding: 20,
slot_rounded_corner_radius: 0,
slot_border_width: 2,
},
};
this.starting_scene_index = 0;
// The state of the running game
this.state = {
scene: this.starting_scene_index,
inventory: new Set(),
cinematic_timeout: {
inc: 0,
last_update_time: -1,
timeout: false,
},
};
// This state will be incremented for each when it finishes to load its image and sound resources.
// The loaded_scenes value must be equal to the scenes number for the game to consider that all resources are loaded.
this.load_state = {
loaded_scenes: 0,
};
}
/**
* Returns the scene that is currently displayed
* @returns {MtlScene}
*/
get_scene() {
return this.scenes[this.state.scene];
}
/**
* @returns {MtlSoundTrack} the soundtrack that is set for the current scene
*/
get_soundtrack() {
return this.get_scene().sound_track;
}
/**
* Updates the state with a new scene index.
* @param {Integer} index The index of the wanted scene
*/
go_to_scene(index) {
const current_scene = this.get_scene();
current_scene.animation.reset_frame();
if (current_scene._type == SCENE_TYPES.CINEMATIC) {
this.state.cinematic_timeout = {
inc: 0,
last_update_time: -1,
timeout: false,
};
}
this.state.scene = index;
}
/**
* This is called if the current scene is of type Cinematic.
* UIncrements the cinematic_timeout counter and update the
* cinematic_timeout.timeout state to true if the cinematic
* has been running as much or more time than what is defined in scene.cinematic_duration.
*/
update_cinematic_timeout() {
if (this.state.cinematic_timeout.timeout) return;
const t = new Date().getTime();
if (this.state.cinematic_timeout.last_update_time === -1) {
this.state.cinematic_timeout.last_update_time = t;
}
this.state.cinematic_timeout.inc = t - this.state.cinematic_timeout.last_update_time;
this.state.cinematic_timeout.timeout = this.get_scene().cinematic_duration * 1000 <= this.state.cinematic_timeout.inc;
}
/**
* Returns a state wether the running cinematic is ended or not
* @returns {Boolean}
*/
is_cinematic_ended() {
const scene = this.get_scene();
if (scene.cinematic_duration === 0) return scene.animation.finished;
return this.state.cinematic_timeout.timeout;
}
/**
* Takes a game object as parameter and references it in the inventory state.
* @param {MtlGameObject} obj
*/
add_object_to_inventory(obj) {
this.state.inventory.add(obj);
}
/**
* @returns {Boolean} true if inventory has an empty slot.