UNPKG

151 kBJavaScriptView Raw
1'use strict';
2
3var pixi_js = require('pixi.js');
4var deepDiff = require('deep-diff');
5var sha1 = require('crypto-js/sha1');
6var devtools = require('@pixi/devtools');
7
8function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10var sha1__default = /*#__PURE__*/_interopDefault(sha1);
11
12var __defProp = Object.defineProperty;
13var __defProps = Object.defineProperties;
14var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
16var __getOwnPropSymbols = Object.getOwnPropertySymbols;
17var __hasOwnProp = Object.prototype.hasOwnProperty;
18var __propIsEnum = Object.prototype.propertyIsEnumerable;
19var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
20var __spreadValues = (a, b) => {
21 for (var prop in b || (b = {}))
22 if (__hasOwnProp.call(b, prop))
23 __defNormalProp(a, prop, b[prop]);
24 if (__getOwnPropSymbols)
25 for (var prop of __getOwnPropSymbols(b)) {
26 if (__propIsEnum.call(b, prop))
27 __defNormalProp(a, prop, b[prop]);
28 }
29 return a;
30};
31var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
32var __decorateClass = (decorators, target, key, kind) => {
33 var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
34 for (var i = decorators.length - 1, decorator; i >= 0; i--)
35 if (decorator = decorators[i])
36 result = (kind ? decorator(target, key, result) : decorator(result)) || result;
37 if (kind && result) __defProp(target, key, result);
38 return result;
39};
40var __async = (__this, __arguments, generator) => {
41 return new Promise((resolve, reject) => {
42 var fulfilled = (value) => {
43 try {
44 step(generator.next(value));
45 } catch (e) {
46 reject(e);
47 }
48 };
49 var rejected = (value) => {
50 try {
51 step(generator.throw(value));
52 } catch (e) {
53 reject(e);
54 }
55 };
56 var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
57 step((generator = generator.apply(__this, __arguments)).next());
58 });
59};
60
61// src/classes/CanvasEvent.ts
62var CanvasEvent = class {
63 constructor() {
64 /**
65 * Get the id of the event. This variable is used in the system to get the event by id, {@link getEventInstanceById}
66 */
67 this.id = "event_id_not_set";
68 this.id = this.constructor.prototype.id;
69 }
70 fn(_event, _element) {
71 throw new Error("[Pixi'VN] The method CanvasEvent.fn() must be overridden");
72 }
73};
74function getStepSha1(step) {
75 let sha1String = sha1__default.default(step.toString().toLocaleLowerCase());
76 return sha1String.toString();
77}
78function checkIfStepsIsEqual(step1, step2) {
79 return step1 === step2;
80}
81
82// src/classes/LabelAbstract.ts
83var LabelAbstract = class {
84 /**
85 * @param id is the id of the label
86 * @param props is the properties of the label
87 */
88 constructor(id, props) {
89 this._id = id;
90 this._onStepStart = props == null ? void 0 : props.onStepStart;
91 this._onLoadStep = props == null ? void 0 : props.onLoadStep;
92 this._onStepEnd = props == null ? void 0 : props.onStepEnd;
93 this._choiseIndex = props == null ? void 0 : props.choiseIndex;
94 }
95 /**
96 * Get the id of the label. This variable is used in the system to get the label by id, {@link getLabelById}
97 */
98 get id() {
99 return this._id;
100 }
101 /**
102 * Get the corresponding steps number
103 * @param externalSteps
104 * @returns Numer of corresponding steps, for example, if externalSteps is [ABC, DEF, GHI] and the steps of the label is [ABC, GHT], the result will be 1
105 */
106 getCorrespondingStepsNumber(externalSteps) {
107 if (externalSteps.length === 0) {
108 return 0;
109 }
110 let res = 0;
111 externalSteps.forEach((step, index) => {
112 if (checkIfStepsIsEqual(step, this.steps[index])) {
113 res = index;
114 }
115 });
116 return res;
117 }
118 /**
119 * Is a function that will be executed in {@link Label#onStepStart} and when the user goes back to it or when the user laods a save file.
120 * @returns Promise<void> or void
121 */
122 get onStepStart() {
123 return (stepIndex, label) => __async(this, null, function* () {
124 if (this._onLoadStep) {
125 yield this._onLoadStep(stepIndex, label);
126 }
127 if (this._onStepStart) {
128 return yield this._onStepStart(stepIndex, label);
129 }
130 });
131 }
132 /**
133 * Get the function that will be executed a old step is reloaded. A step is reloaded when the user goes back to it or when the user laods a save file.
134 * @returns Promise<void> or void
135 */
136 get onLoadStep() {
137 return this._onLoadStep;
138 }
139 /**
140 * Is a function that will be executed when the step ends.
141 * @returns Promise<void> or void
142 */
143 get onStepEnd() {
144 return this._onStepEnd;
145 }
146 get choiseIndex() {
147 return this._choiseIndex;
148 }
149};
150
151// src/classes/Label.ts
152var Label = class extends LabelAbstract {
153 /**
154 * @param id is the id of the label
155 * @param steps is the list of steps that the label will perform
156 * @param props is the properties of the label
157 */
158 constructor(id, steps, props) {
159 super(id, props);
160 this._steps = steps;
161 }
162 /**
163 * Get the steps of the label.
164 */
165 get steps() {
166 if (typeof this._steps === "function") {
167 return this._steps();
168 }
169 return this._steps;
170 }
171};
172
173// src/classes/CloseLabel.ts
174var CLOSE_LABEL_ID = "__close-label-id__";
175function newCloseLabel(choiseIndex) {
176 return new Label(CLOSE_LABEL_ID, [], {
177 choiseIndex
178 });
179}
180
181// src/decorators/LabelDecorator.ts
182var registeredLabels = {};
183function newLabel(id, steps, props) {
184 if (registeredLabels[id]) {
185 console.info(`[Pixi'VN] Label ${id} already exists, it will be overwritten`);
186 }
187 let label = new Label(id, steps, props);
188 registeredLabels[id] = label;
189 return label;
190}
191function getLabelById(id) {
192 let label = registeredLabels[id];
193 if (!label) {
194 console.error(`[Pixi'VN] Label ${id} not found`);
195 return;
196 }
197 return label;
198}
199function saveLabel(label) {
200 registeredLabels[label.id] = label;
201}
202var CanvasBase = class extends pixi_js.Container {
203 constructor() {
204 super(...arguments);
205 /**
206 * Get the id of the canvas element. This variable is used in the system to get the canvas element by id, {@link getCanvasElementInstanceById}
207 */
208 this.pixivnId = "canvas_element_id_not_set";
209 }
210 /**
211 * This method return the memory of the canvas element.
212 */
213 get memory() {
214 throw new Error("[Pixi'VN] The method CanvasBase.memory must be overridden");
215 }
216 /**
217 * This method set the memory of the canvas element.
218 */
219 set memory(_value) {
220 throw new Error("[Pixi'VN] The method CanvasBase.memory must be overridden");
221 }
222};
223
224// src/functions/CanvasUtility.ts
225function getTextureMemory(texture) {
226 let sourceTexture = texture.source;
227 let textureMemory = {
228 image: sourceTexture.label
229 };
230 return textureMemory;
231}
232function exportCanvasElement(element) {
233 return element.memory;
234}
235function importCanvasElement(memory) {
236 let element = getCanvasElementInstanceById(memory.pixivnId);
237 if (element) {
238 element.memory = memory;
239 } else {
240 throw new Error("[Pixi'VN] The element " + memory.pixivnId + " could not be created");
241 }
242 return element;
243}
244
245// src/classes/canvas/CanvasContainer.ts
246var CANVAS_CONTAINER_ID = "CanvasContainer";
247var CanvasContainer = class extends pixi_js.Container {
248 constructor(options) {
249 super(options);
250 this.pixivnId = CANVAS_CONTAINER_ID;
251 this.pixivnId = this.constructor.prototype.pixivnId || CANVAS_CONTAINER_ID;
252 }
253 get memory() {
254 let memory = getMemoryContainer(this);
255 this.children.forEach((child) => {
256 memory.elements.push(exportCanvasElement(child));
257 });
258 return memory;
259 }
260 set memory(value) {
261 setMemoryContainer(this, value);
262 value.elements.forEach((child) => {
263 this.addChild(importCanvasElement(child));
264 });
265 }
266};
267function getMemoryContainer(element) {
268 let className = "CanvasContainer";
269 if (element.hasOwnProperty("pixivnId")) {
270 className = element.pixivnId;
271 }
272 return {
273 pixivnId: className,
274 elements: [],
275 width: element.width,
276 height: element.height,
277 isRenderGroup: element.isRenderGroup,
278 blendMode: element.blendMode,
279 tint: element.tint,
280 alpha: element.alpha,
281 angle: element.angle,
282 renderable: element.renderable,
283 rotation: element.rotation,
284 scale: { x: element.scale.x, y: element.scale.y },
285 pivot: { x: element.pivot.x, y: element.pivot.y },
286 position: { x: element.position.x, y: element.position.y },
287 skew: { x: element.skew.x, y: element.skew.y },
288 visible: element.visible,
289 x: element.x,
290 y: element.y,
291 boundsArea: element.boundsArea,
292 cursor: element.cursor,
293 eventMode: element.eventMode,
294 interactive: element.interactive,
295 interactiveChildren: element.interactiveChildren,
296 hitArea: element.hitArea
297 };
298}
299function setMemoryContainer(element, memory) {
300 memory.isRenderGroup && (element.isRenderGroup = memory.isRenderGroup);
301 memory.blendMode && (element.blendMode = memory.blendMode);
302 memory.tint && (element.tint = memory.tint);
303 memory.alpha && (element.alpha = memory.alpha);
304 memory.angle && (element.angle = memory.angle);
305 memory.renderable && (element.renderable = memory.renderable);
306 memory.rotation && (element.rotation = memory.rotation);
307 if (memory.scale) {
308 if (typeof memory.scale === "number") {
309 element.scale.set(memory.scale, memory.scale);
310 } else {
311 element.scale.set(memory.scale.x, memory.scale.y);
312 }
313 }
314 if (memory.pivot) {
315 if (typeof memory.pivot === "number") {
316 element.pivot.set(memory.pivot, memory.pivot);
317 } else {
318 element.pivot.set(memory.pivot.x, memory.pivot.y);
319 }
320 }
321 memory.position && element.position.set(memory.position.x, memory.position.y);
322 memory.skew && element.skew.set(memory.skew.x, memory.skew.y);
323 memory.visible && (element.visible = memory.visible);
324 memory.x && (element.x = memory.x);
325 memory.y && (element.y = memory.y);
326 memory.boundsArea && (element.boundsArea = memory.boundsArea);
327 memory.cursor && (element.cursor = memory.cursor);
328 memory.eventMode && (element.eventMode = memory.eventMode);
329 memory.interactive && (element.interactive = memory.interactive);
330 memory.interactiveChildren && (element.interactiveChildren = memory.interactiveChildren);
331 memory.hitArea && (element.hitArea = memory.hitArea);
332 memory.width && (element.width = memory.width);
333 memory.height && (element.height = memory.height);
334}
335function getTexture(imageUrl) {
336 return __async(this, null, function* () {
337 if (pixi_js.Assets.cache.has(imageUrl)) {
338 return pixi_js.Assets.get(imageUrl);
339 }
340 return pixi_js.Assets.load(imageUrl).then((texture) => {
341 if (!texture) {
342 console.error("[Pixi'VN] Texture not found", imageUrl);
343 return;
344 }
345 if (!(texture instanceof pixi_js.Texture)) {
346 console.error("[Pixi'VN] File not is a image", imageUrl);
347 return;
348 }
349 return texture;
350 }).catch((e) => {
351 console.error("[Pixi'VN] Error loading image", e);
352 return;
353 });
354 });
355}
356function getFillGradientFillPattern(prop, propName) {
357 if (!(prop instanceof Object)) {
358 return prop;
359 }
360 console.warn(`[Pixi'VN] CanvasText.style.${propName} is a FillGradient or FillPattern, this is not supported yet.`, prop);
361 return void 0;
362}
363function getTextStyle(style) {
364 return {
365 align: style.align,
366 breakWords: style.breakWords,
367 dropShadow: style.dropShadow,
368 fill: getFillGradientFillPattern(style.stroke, "fill"),
369 fontFamily: style.fontFamily,
370 fontSize: style.fontSize,
371 fontStyle: style.fontStyle,
372 fontVariant: style.fontVariant,
373 fontWeight: style.fontWeight,
374 leading: style.leading,
375 letterSpacing: style.letterSpacing,
376 lineHeight: style.lineHeight,
377 padding: style.padding,
378 stroke: getFillGradientFillPattern(style.stroke, "stroke"),
379 textBaseline: style.textBaseline,
380 trim: style.trim,
381 whiteSpace: style.whiteSpace,
382 wordWrap: style.wordWrap,
383 wordWrapWidth: style.wordWrapWidth
384 };
385}
386
387// src/decorators/EventDecorator.ts
388var registeredEvents = {};
389function eventDecorator(name) {
390 return function(target) {
391 if (!name) {
392 name = target.name;
393 }
394 if (registeredEvents[name]) {
395 console.info(`[Pixi'VN] Event ${name} already exists, it will be overwritten`);
396 }
397 target.prototype.id = name;
398 registeredEvents[name] = target;
399 };
400}
401function getEventTypeById(eventId) {
402 try {
403 let eventType = registeredEvents[eventId];
404 if (!eventType) {
405 console.error(`[Pixi'VN] Event ${eventId} not found`);
406 return;
407 }
408 new eventType();
409 return eventType;
410 } catch (e) {
411 console.error(`[Pixi'VN] Error while getting Event ${eventId}`, e);
412 return;
413 }
414}
415function getEventInstanceById(eventId) {
416 try {
417 let eventType = registeredEvents[eventId];
418 if (!eventType) {
419 console.error(`[Pixi'VN] Event ${eventId} not found`);
420 return;
421 }
422 let event = new eventType();
423 return event;
424 } catch (e) {
425 console.error(`[Pixi'VN] Error while getting Event ${eventId}`, e);
426 return;
427 }
428}
429
430// src/classes/canvas/CanvasSprite.ts
431var CANVAS_SPRITE_ID = "CanvasSprite";
432var CanvasSprite = class _CanvasSprite extends pixi_js.Sprite {
433 constructor(options) {
434 super(options);
435 this.pixivnId = CANVAS_SPRITE_ID;
436 this._onEvents = {};
437 this.pixivnId = this.constructor.prototype.pixivnId || CANVAS_SPRITE_ID;
438 }
439 get memory() {
440 return getMemorySprite(this);
441 }
442 set memory(value) {
443 setMemorySprite(this, value);
444 }
445 get onEvents() {
446 return this._onEvents;
447 }
448 /**
449 * is same function as on(), but it keeps in memory the children.
450 * @param event The event type, e.g., 'click', 'mousedown', 'mouseup', 'pointerdown', etc.
451 * @param eventClass The class that extends CanvasEvent.
452 * @returns
453 * @example
454 * ```typescript
455 * \@eventDecorator()
456 * export class EventTest extends CanvasEvent<CanvasSprite> {
457 * override fn(event: CanvasEventNamesType, sprite: CanvasSprite): void {
458 * if (event === 'pointerdown') {
459 * sprite.scale.x *= 1.25;
460 * sprite.scale.y *= 1.25;
461 * }
462 * }
463 * }
464 * ```
465 *
466 * ```typescript
467 * let sprite = addImage("alien", 'https://pixijs.com/assets/eggHead.png')
468 * await sprite.load()
469 *
470 * sprite.eventMode = 'static';
471 * sprite.cursor = 'pointer';
472 * sprite.onEvent('pointerdown', EventTest);
473 *
474 * GameWindowManager.addCanvasElement("bunny", sprite);
475 * ```
476 */
477 onEvent(event, eventClass) {
478 let id = eventClass.prototype.id;
479 let instance = getEventInstanceById(id);
480 this._onEvents[event] = id;
481 if (instance) {
482 super.on(event, () => {
483 instance.fn(event, this);
484 });
485 }
486 return this;
487 }
488 /**
489 * on() does not keep in memory the event class, use onEvent() instead
490 * @deprecated
491 * @private
492 * @param event
493 * @param fn
494 * @param context
495 */
496 on(event, fn, context) {
497 return super.on(event, fn, context);
498 }
499 static from(source, skipCache) {
500 let sprite = pixi_js.Sprite.from(source, skipCache);
501 let mySprite = new _CanvasSprite();
502 mySprite.texture = sprite.texture;
503 return mySprite;
504 }
505};
506function getMemorySprite(element) {
507 let temp = getMemoryContainer(element);
508 return __spreadProps(__spreadValues({}, temp), {
509 pixivnId: element.pixivnId,
510 textureImage: getTextureMemory(element.texture),
511 anchor: { x: element.anchor.x, y: element.anchor.y },
512 roundPixels: element.roundPixels,
513 onEvents: element.onEvents
514 });
515}
516function setMemorySprite(element, memory) {
517 setMemoryContainer(element, memory);
518 getTexture(memory.textureImage.image).then((texture) => {
519 if (texture) {
520 element.texture = texture;
521 }
522 });
523 if (memory.anchor) {
524 if (typeof memory.anchor === "number") {
525 element.anchor.set(memory.anchor, memory.anchor);
526 } else {
527 element.anchor.set(memory.anchor.x, memory.anchor.y);
528 }
529 }
530 memory.roundPixels && (element.roundPixels = memory.roundPixels);
531 for (let event in memory.onEvents) {
532 let id = memory.onEvents[event];
533 let instance = getEventTypeById(id);
534 if (instance) {
535 element.onEvent(event, instance);
536 }
537 }
538}
539
540// src/classes/canvas/CanvasImage.ts
541var CANVAS_IMAGE_ID = "CanvasImage";
542var CanvasImage = class _CanvasImage extends CanvasSprite {
543 constructor(options, imageLink) {
544 super(options);
545 this.pixivnId = CANVAS_IMAGE_ID;
546 this.imageLink = "";
547 if (imageLink) {
548 this.imageLink = imageLink;
549 }
550 }
551 get memory() {
552 return __spreadProps(__spreadValues({}, getMemorySprite(this)), {
553 pixivnId: this.pixivnId,
554 imageLink: this.imageLink
555 });
556 }
557 set memory(memory) {
558 setMemorySprite(this, memory);
559 this.imageLink = memory.imageLink;
560 }
561 static from(source, skipCache) {
562 let sprite = pixi_js.Sprite.from(source, skipCache);
563 let mySprite = new _CanvasImage();
564 mySprite.texture = sprite.texture;
565 return mySprite;
566 }
567 /**
568 * Load the image from the link and set the texture of the sprite.
569 * @param image The link of the image. If it is not set, it will use the imageLink property.
570 * @returns A promise that resolves when the image is loaded.
571 */
572 load(image) {
573 return __async(this, null, function* () {
574 if (!image) {
575 image = this.imageLink;
576 }
577 return getTexture(this.imageLink).then((texture) => {
578 if (texture) {
579 this.texture = texture;
580 }
581 }).catch((e) => {
582 console.error("[Pixi'VN] Error into CanvasImage.load()", e);
583 });
584 });
585 }
586};
587var CANVAS_TEXT_ID = "CanvasText";
588var CanvasText = class extends pixi_js.Text {
589 constructor(options) {
590 super(options);
591 this.pixivnId = CANVAS_TEXT_ID;
592 this._onEvents = {};
593 this.pixivnId = this.constructor.prototype.pixivnId || CANVAS_TEXT_ID;
594 }
595 get memory() {
596 return getMemoryText(this);
597 }
598 set memory(value) {
599 setMemoryText(this, value);
600 }
601 get onEvents() {
602 return this._onEvents;
603 }
604 /**
605 * is same function as on(), but it keeps in memory the children.
606 * @param event The event type, e.g., 'click', 'mousedown', 'mouseup', 'pointerdown', etc.
607 * @param eventClass The class that extends CanvasEvent.
608 * @returns
609 * @example
610 * ```typescript
611 * \@eventDecorator()
612 * export class EventTest extends CanvasEvent<CanvasText> {
613 * override fn(event: CanvasEventNamesType, text: CanvasText): void {
614 * if (event === 'pointerdown') {
615 * text.scale.x *= 1.25;
616 * text.scale.y *= 1.25;
617 * }
618 * }
619 * }
620 * ```
621 *
622 * ```typescript
623 * const text = new CanvasText();
624 * text.text = "Hello World"
625 *
626 * text.eventMode = 'static';
627 * text.cursor = 'pointer';
628 * text.onEvent('pointerdown', EventTest);
629 *
630 * GameWindowManager.addCanvasElement("text", text);
631 * ```
632 */
633 onEvent(event, eventClass) {
634 let id = eventClass.prototype.id;
635 let instance = getEventInstanceById(id);
636 this._onEvents[event] = id;
637 if (instance) {
638 super.on(event, () => {
639 instance.fn(event, this);
640 });
641 }
642 return this;
643 }
644 /**
645 * on() does not keep in memory the event class, use onEvent() instead
646 * @deprecated
647 * @private
648 * @param event
649 * @param fn
650 * @param context
651 */
652 on(event, fn, context) {
653 return super.on(event, fn, context);
654 }
655};
656function getMemoryText(element) {
657 let temp = getMemoryContainer(element);
658 return __spreadProps(__spreadValues({}, temp), {
659 pixivnId: element.pixivnId,
660 anchor: { x: element.anchor.x, y: element.anchor.y },
661 text: element.text,
662 resolution: element.resolution,
663 style: getTextStyle(element.style),
664 roundPixels: element.roundPixels,
665 onEvents: element.onEvents
666 });
667}
668function setMemoryText(element, memory) {
669 setMemoryContainer(element, memory);
670 if (memory.anchor) {
671 if (typeof memory.anchor === "number") {
672 element.anchor.set(memory.anchor, memory.anchor);
673 } else {
674 element.anchor.set(memory.anchor.x, memory.anchor.y);
675 }
676 }
677 memory.text && (element.text = memory.text);
678 memory.resolution && (element.resolution = memory.resolution);
679 memory.style && (element.style = memory.style);
680 memory.roundPixels && (element.roundPixels = memory.roundPixels);
681 for (let event in memory.onEvents) {
682 let id = memory.onEvents[event];
683 let instance = getEventTypeById(id);
684 if (instance) {
685 element.onEvent(event, instance);
686 }
687 }
688}
689
690// src/decorators/CanvasElementDecorator.ts
691var registeredCanvasElement = {};
692function canvasElementDecorator(name) {
693 return function(target) {
694 if (!name) {
695 name = target.name;
696 }
697 if (registeredCanvasElement[name]) {
698 console.warn(`[Pixi'VN] CanvasElement ${name} already registered`);
699 }
700 target.prototype.pixivnId = name;
701 registeredCanvasElement[name] = target;
702 };
703}
704function getCanvasElementInstanceById(canvasId) {
705 try {
706 let eventType = registeredCanvasElement[canvasId];
707 if (!eventType) {
708 if (canvasId === CANVAS_CONTAINER_ID) {
709 eventType = CanvasContainer;
710 } else if (canvasId === CANVAS_IMAGE_ID) {
711 eventType = CanvasImage;
712 } else if (canvasId === CANVAS_SPRITE_ID) {
713 eventType = CanvasSprite;
714 } else if (canvasId === CANVAS_TEXT_ID) {
715 eventType = CanvasText;
716 }
717 }
718 if (!eventType) {
719 console.error(`[Pixi'VN] CanvasElement ${canvasId} not found`);
720 return;
721 }
722 let canvasElement = new eventType();
723 return canvasElement;
724 } catch (e) {
725 console.error(`[Pixi'VN] Error while getting CanvasElement ${canvasId}`, e);
726 return;
727 }
728}
729
730// src/decorators/CharacterDecorator.ts
731var registeredCharacters = {};
732function saveCharacter(character) {
733 if (Array.isArray(character)) {
734 character.forEach((c) => saveCharacter(c));
735 return;
736 }
737 if (registeredCharacters[character.id]) {
738 console.info(`[Pixi'VN] Character id ${character.id} already exists, it will be overwritten`);
739 }
740 registeredCharacters[character.id] = character;
741}
742function getCharacterById(id) {
743 try {
744 let character = registeredCharacters[id];
745 if (!character) {
746 console.error(`[Pixi'VN] Character ${id} not found`);
747 return;
748 }
749 return character;
750 } catch (e) {
751 console.error(`[Pixi'VN] Error while getting Character ${id}`, e);
752 return;
753 }
754}
755function getAllCharacters() {
756 return Object.values(registeredCharacters);
757}
758
759// src/decorators/TickerDecorator.ts
760var registeredTickers = {};
761function tickerDecorator(name) {
762 return function(target) {
763 if (!name) {
764 name = target.name;
765 }
766 if (registeredTickers[name]) {
767 console.info(`[Pixi'VN] Ticker ${name} already exists, it will be overwritten`);
768 }
769 target.prototype.id = name;
770 registeredTickers[name] = target;
771 };
772}
773function geTickerInstanceById(tickerId, args, duration, priority) {
774 try {
775 let ticker = registeredTickers[tickerId];
776 if (!ticker) {
777 console.error(`[Pixi'VN] Ticker ${tickerId} not found`);
778 return;
779 }
780 return new ticker(args, duration, priority);
781 } catch (e) {
782 console.error(`[Pixi'VN] Error while getting Ticker ${tickerId}`, e);
783 return;
784 }
785}
786
787// src/types/CloseType.ts
788var Close = "close";
789
790// src/classes/ChoiceMenuOption.ts
791var ChoiceMenuOption = class {
792 /**
793 * @param text Text to be displayed in the menu
794 * @param label Label to be opened when the option is selected or the id of the label
795 * @param props Properties to be passed to the label and olther parameters that you can use when get all the choice menu options. It be converted to a JSON string, so it cannot contain functions or classes.
796 * @param type Type of the label to be opened. @default "call"
797 */
798 constructor(text, label, props, type = "call") {
799 /**
800 * Properties to be passed to the label and olther parameters that you can use when get all the choice menu options.
801 * @example
802 * ```tsx
803 * setChoiceMenuOptions([
804 * new ChoiceMenuOption("Hello", helloLabel, { disabled: true }),
805 * ])
806 * return <List>
807 * {getChoiceMenuOptions()?.map((item, index) => {
808 * return (
809 * <ChoiceButton
810 * disabled={item.props.disabled}
811 * onClick={() => {
812 * afterSelectChoice(item)
813 * }}
814 * >
815 * {item.text}
816 * </ChoiceButton>
817 * )
818 * })}
819 * </List>
820 * ```
821 */
822 this.props = {};
823 this.text = text;
824 this._label = label;
825 this.type = type;
826 if (props) {
827 this.props = props;
828 }
829 }
830 /**
831 * Label to be opened when the option is selected
832 */
833 get label() {
834 let label = this._label;
835 if (typeof label === "string") {
836 let res = getLabelById(label);
837 if (res) {
838 label = res;
839 } else {
840 console.error(`Label ${label} not found, so it will be closed`);
841 label = newCloseLabel();
842 }
843 }
844 return label;
845 }
846};
847var ChoiceMenuOptionClose = class {
848 /**
849 * @param text Text to be displayed in the menu
850 * @param closeCurrentLabel If true, the current label will be closed. @default false
851 */
852 constructor(text, closeCurrentLabel = false) {
853 /**
854 * Label to be opened when the option is selected
855 */
856 this.label = newCloseLabel();
857 /**
858 * Type of the label to be opened
859 */
860 this.type = Close;
861 /**
862 * Properties to be passed to the label and olther parameters that you can use when get all the choice menu options.
863 * @example
864 * ```tsx
865 * setChoiceMenuOptions([
866 * new ChoiceMenuOption("Hello", helloLabel, { disabled: true }),
867 * ])
868 * return <List>
869 * {getChoiceMenuOptions()?.map((item, index) => {
870 * return (
871 * <ChoiceButton
872 * disabled={item.props.disabled}
873 * onClick={() => {
874 * afterSelectChoice(item)
875 * }}
876 * >
877 * {item.text}
878 * </ChoiceButton>
879 * )
880 * })}
881 * </List>
882 * ```
883 */
884 this.props = {};
885 this.text = text;
886 this.closeCurrentLabel = closeCurrentLabel;
887 }
888};
889
890// src/functions/FlagsUtility.ts
891function setFlag(name, value) {
892 let flags = GameStorageManager.getVariable(GameStorageManager.keysSystem.FLAGS_CATEGORY_KEY) || [];
893 if (value) {
894 if (!flags.includes(name)) {
895 flags.push(name);
896 }
897 } else {
898 let index = flags.indexOf(name);
899 if (index > -1) {
900 flags.splice(index, 1);
901 }
902 }
903 GameStorageManager.setVariable(GameStorageManager.keysSystem.FLAGS_CATEGORY_KEY, flags);
904}
905function getFlag(name) {
906 let flags = GameStorageManager.getVariable(GameStorageManager.keysSystem.FLAGS_CATEGORY_KEY) || [];
907 return flags.includes(name);
908}
909
910// src/functions/DialogueUtility.ts
911function setDialogue(props) {
912 let text = "";
913 let character = void 0;
914 let dialogue;
915 if (typeof props === "string") {
916 text = props;
917 dialogue = new DialogueBaseModel(text, character);
918 } else if (Array.isArray(props)) {
919 text = props.join();
920 dialogue = new DialogueBaseModel(text, character);
921 } else if (!(props instanceof DialogueBaseModel)) {
922 if (Array.isArray(props.text)) {
923 text = props.text.join();
924 } else {
925 text = props.text;
926 }
927 if (props.character) {
928 if (typeof props.character === "string") {
929 character = props.character;
930 } else {
931 character = props.character.id;
932 }
933 }
934 dialogue = new DialogueBaseModel(text, character);
935 } else {
936 dialogue = props;
937 }
938 if (getFlag(GameStorageManager.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY)) {
939 let glueDialogue = getDialogue();
940 if (glueDialogue) {
941 dialogue.text = `${glueDialogue.text}${dialogue.text}`;
942 }
943 setFlag(GameStorageManager.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY, false);
944 }
945 GameStorageManager.setVariable(GameStorageManager.keysSystem.CURRENT_DIALOGUE_MEMORY_KEY, dialogue);
946 GameStorageManager.setVariable(GameStorageManager.keysSystem.LAST_DIALOGUE_ADDED_IN_STEP_MEMORY_KEY, GameStepManager.lastStepIndex);
947}
948function getDialogue() {
949 return GameStorageManager.getVariable(GameStorageManager.keysSystem.CURRENT_DIALOGUE_MEMORY_KEY);
950}
951function clearDialogue() {
952 GameStorageManager.setVariable(GameStorageManager.keysSystem.CURRENT_DIALOGUE_MEMORY_KEY, void 0);
953}
954function setChoiceMenuOptions(options) {
955 let value = options.map((option) => {
956 if (option instanceof ChoiceMenuOptionClose) {
957 return {
958 text: option.text,
959 type: Close,
960 closeCurrentLabel: option.closeCurrentLabel
961 };
962 }
963 return __spreadProps(__spreadValues({}, option), {
964 label: option.label.id
965 });
966 });
967 GameStorageManager.setVariable(GameStorageManager.keysSystem.CURRENT_MENU_OPTIONS_MEMORY_KEY, value);
968 GameStorageManager.setVariable(GameStorageManager.keysSystem.LAST_MENU_OPTIONS_ADDED_IN_STEP_MEMORY_KEY, GameStepManager.lastStepIndex);
969}
970function getChoiceMenuOptions() {
971 let d = GameStorageManager.getVariable(GameStorageManager.keysSystem.CURRENT_MENU_OPTIONS_MEMORY_KEY);
972 if (d) {
973 let options = [];
974 d.forEach((option, index) => {
975 if (option.type === Close) {
976 let itemLabel = newCloseLabel(index);
977 let choice = new ChoiceMenuOptionClose(option.text, option.closeCurrentLabel);
978 choice.label = itemLabel;
979 options.push(choice);
980 return;
981 }
982 let label = getLabelById(option.label);
983 if (label) {
984 let itemLabel = new Label(label.id, label.steps, {
985 onStepStart: label.onStepStart,
986 choiseIndex: index
987 });
988 options.push(new ChoiceMenuOption(option.text, itemLabel, option.props, option.type));
989 }
990 });
991 return options;
992 }
993 return void 0;
994}
995function clearChoiceMenuOptions() {
996 GameStorageManager.setVariable(GameStorageManager.keysSystem.CURRENT_MENU_OPTIONS_MEMORY_KEY, void 0);
997}
998function getDialogueHistory() {
999 let list = [];
1000 GameStepManager.stepsHistory.forEach((step) => {
1001 let dialoge = step.dialoge;
1002 let requiredChoices = step.choices;
1003 if (list.length > 0 && list[list.length - 1].choices && !list[list.length - 1].playerMadeChoice && step.currentLabel) {
1004 let oldChoices = list[list.length - 1].choices;
1005 if (oldChoices) {
1006 let choiceMade = false;
1007 if (step.choiceIndexMade !== void 0 && oldChoices.length > step.choiceIndexMade) {
1008 oldChoices[step.choiceIndexMade].isResponse = true;
1009 choiceMade = true;
1010 }
1011 list[list.length - 1].playerMadeChoice = choiceMade;
1012 list[list.length - 1].choices = oldChoices;
1013 }
1014 }
1015 if (dialoge || requiredChoices) {
1016 let choices = requiredChoices == null ? void 0 : requiredChoices.map((choice) => {
1017 return {
1018 text: choice.text,
1019 type: choice.type,
1020 isResponse: false
1021 };
1022 });
1023 list.push({
1024 dialoge,
1025 playerMadeChoice: false,
1026 choices,
1027 stepIndex: step.index
1028 });
1029 }
1030 });
1031 return list;
1032}
1033
1034// src/functions/GameUtility.ts
1035function clearAllGameDatas() {
1036 GameStorageManager.clear();
1037 GameWindowManager.clear();
1038 GameStepManager.clear();
1039}
1040
1041// src/classes/ticker/TickerBase.ts
1042var TickerBase = class {
1043 /**
1044 * @param args The arguments that you want to pass to the ticker.
1045 * @param duration The duration of the ticker in seconds. If is undefined, the step will end only when the animation is finished (if the animation doesn't have a goal to reach then it won't finish). @default undefined
1046 * @param priority The priority of the ticker. @default UPDATE_PRIORITY.NORMAL
1047 */
1048 constructor(args, duration, priority) {
1049 /**
1050 * Get the id of the ticker. This variable is used in the system to get the ticker by id, {@link geTickerInstanceById}
1051 */
1052 this.id = "ticker_id_not_set";
1053 this.args = args;
1054 this.duration = duration;
1055 this.priority = priority;
1056 this.id = this.constructor.prototype.id;
1057 }
1058 /**
1059 * The method that will be called every frame.
1060 * This method should be overridden and you can use GameWindowManager.addCanvasElement() to get the canvas element of the canvas, and edit them.
1061 * @param _ticker The ticker that is calling this method
1062 * @param _args The arguments that you passed when you added the ticker
1063 * @param _tags The tags of the canvas elements that are connected to this ticker
1064 * @param _tickerId The id of the ticker. You can use this to get the ticker from the {@link GameWindowManager.currentTickers}
1065 */
1066 fn(_ticker, _args, _tags, _tickerId) {
1067 throw new Error("[Pixi'VN] The method TickerBase.fn() must be overridden");
1068 }
1069};
1070
1071// src/classes/ticker/FadeAlphaTicker.ts
1072exports.FadeAlphaTicker = class FadeAlphaTicker extends TickerBase {
1073 fn(ticker, args, tags, tickerId) {
1074 let type = args.type === void 0 ? "hide" : args.type;
1075 let duration = args.duration === void 0 ? 1 : args.duration;
1076 let speed = 1 / (duration * 60);
1077 let limit = args.limit === void 0 ? type === "hide" ? 0 : 1 : args.limit;
1078 let tagToRemoveAfter2 = args.tagToRemoveAfter || [];
1079 if (typeof tagToRemoveAfter2 === "string") {
1080 tagToRemoveAfter2 = [tagToRemoveAfter2];
1081 }
1082 if (type === "hide" && limit < 0) {
1083 limit = 0;
1084 }
1085 if (type === "show" && limit > 1) {
1086 limit = 1;
1087 }
1088 tags.filter((tag) => {
1089 var _a;
1090 let element = GameWindowManager.getCanvasElement(tag);
1091 if (args.startOnlyIfHaveTexture) {
1092 if (element && element instanceof pixi_js.Sprite && ((_a = element.texture) == null ? void 0 : _a.label) == "EMPTY") {
1093 return false;
1094 }
1095 }
1096 return true;
1097 }).forEach((tag) => {
1098 let element = GameWindowManager.getCanvasElement(tag);
1099 if (element && element instanceof pixi_js.Container) {
1100 if (type === "show" && element.alpha < limit) {
1101 element.alpha += speed * ticker.deltaTime;
1102 } else if (type === "hide" && element.alpha > limit) {
1103 element.alpha -= speed * ticker.deltaTime;
1104 }
1105 if (type === "show" && element.alpha >= limit) {
1106 element.alpha = limit;
1107 GameWindowManager.onEndOfTicker(tag, this, tagToRemoveAfter2, tickerId);
1108 } else if (type === "hide" && element.alpha <= limit) {
1109 element.alpha = limit;
1110 GameWindowManager.onEndOfTicker(tag, this, tagToRemoveAfter2, tickerId);
1111 }
1112 }
1113 });
1114 }
1115};
1116exports.FadeAlphaTicker = __decorateClass([
1117 tickerDecorator()
1118], exports.FadeAlphaTicker);
1119
1120// src/functions/TickerUtility.ts
1121function updateTickerProgression(args, propertyName, progression, valueConvert) {
1122 let limit = valueConvert && progression.limit ? valueConvert(progression.limit) : progression.limit;
1123 if (args[propertyName] === void 0 || !progression || args[propertyName] === limit) {
1124 return;
1125 }
1126 if (typeof args[propertyName] === "number") {
1127 if (progression.type === "linear") {
1128 args[propertyName] = getLinearProgression(args[propertyName], progression);
1129 } else if (progression.type === "exponential") {
1130 args[propertyName] = getExponentialProgression(args[propertyName], progression);
1131 }
1132 } else if (args[propertyName] !== void 0 && typeof args[propertyName] === "object" && args[propertyName].haveOwnProperty("x") && args[propertyName].haveOwnProperty("y") && typeof args[propertyName].x === "number" && typeof args[propertyName].y === "number") {
1133 if (progression.type === "linear") {
1134 args[propertyName].x = getLinearProgression(args[propertyName].x, progression);
1135 args[propertyName].y = getLinearProgression(args[propertyName].y, progression);
1136 } else if (progression.type === "exponential") {
1137 args[propertyName].x = getExponentialProgression(args[propertyName].x, progression);
1138 args[propertyName].y = getExponentialProgression(args[propertyName].y, progression);
1139 }
1140 }
1141}
1142function getLinearProgression(number, progression, valueConvert) {
1143 let limit = valueConvert && progression.limit ? valueConvert(progression.limit) : progression.limit;
1144 let amt = valueConvert ? valueConvert(progression.amt) : progression.amt;
1145 if (limit !== void 0) {
1146 if (number > limit && amt > 0) {
1147 return limit;
1148 } else if (number < limit && amt < 0) {
1149 return limit;
1150 }
1151 }
1152 return number + amt;
1153}
1154function getExponentialProgression(number, progression, valueConvert) {
1155 let limit = valueConvert && progression.limit ? valueConvert(progression.limit) : progression.limit;
1156 if (limit !== void 0) {
1157 if (number > limit && progression.percentage > 0) {
1158 return limit;
1159 } else if (number < limit && progression.percentage < 0) {
1160 return limit;
1161 }
1162 }
1163 return number + number * progression.percentage;
1164}
1165
1166// src/classes/ticker/MoveTicker.ts
1167exports.MoveTicker = class MoveTicker extends TickerBase {
1168 fn(ticker, args, tags, tickerId) {
1169 let xSpeed = 1;
1170 let ySpeed = 1;
1171 if (args.speed) {
1172 if (typeof args.speed === "number") {
1173 xSpeed = this.speedConvert(args.speed);
1174 ySpeed = this.speedConvert(args.speed);
1175 } else {
1176 xSpeed = this.speedConvert(args.speed.x);
1177 ySpeed = this.speedConvert(args.speed.y);
1178 }
1179 }
1180 let destination = args.destination;
1181 let tagToRemoveAfter2 = args.tagToRemoveAfter || [];
1182 if (typeof tagToRemoveAfter2 === "string") {
1183 tagToRemoveAfter2 = [tagToRemoveAfter2];
1184 }
1185 tags.filter((tag) => {
1186 var _a;
1187 let element = GameWindowManager.getCanvasElement(tag);
1188 if (args.startOnlyIfHaveTexture) {
1189 if (element && element instanceof pixi_js.Sprite && ((_a = element.texture) == null ? void 0 : _a.label) == "EMPTY") {
1190 return false;
1191 }
1192 }
1193 return true;
1194 }).forEach((tag) => {
1195 let element = GameWindowManager.getCanvasElement(tag);
1196 if (element && element instanceof pixi_js.Container) {
1197 let xDistance = destination.x - element.x > 0 ? 1 : -1;
1198 if (xDistance != 0) {
1199 element.x += xDistance * xSpeed * ticker.deltaTime;
1200 let newDistance = destination.x - element.x;
1201 if (xDistance < 0 && newDistance > 0 || xDistance > 0 && newDistance < 0) {
1202 element.x = destination.x;
1203 }
1204 }
1205 let yDistance = destination.y - element.y > 0 ? 1 : -1;
1206 if (yDistance != 0) {
1207 element.y += yDistance * ySpeed * ticker.deltaTime;
1208 let newDistance = destination.y - element.y;
1209 if (yDistance < 0 && newDistance > 0 || yDistance > 0 && newDistance < 0) {
1210 element.y = destination.y;
1211 }
1212 }
1213 if (element.x == destination.x && element.y == destination.y) {
1214 GameWindowManager.onEndOfTicker(tag, this, tagToRemoveAfter2, tickerId);
1215 }
1216 }
1217 });
1218 if (args.speedProgression)
1219 updateTickerProgression(args, "speed", args.speedProgression, this.speedConvert);
1220 }
1221 speedConvert(speed) {
1222 return speed / 6;
1223 }
1224};
1225exports.MoveTicker = __decorateClass([
1226 tickerDecorator()
1227], exports.MoveTicker);
1228exports.RotateTicker = class RotateTicker extends TickerBase {
1229 fn(ticker, args, tags, tickerId) {
1230 let speed = this.speedConvert(args.speed === void 0 ? 1 : args.speed);
1231 let clockwise = args.clockwise === void 0 ? true : args.clockwise;
1232 let tagToRemoveAfter2 = args.tagToRemoveAfter || [];
1233 if (typeof tagToRemoveAfter2 === "string") {
1234 tagToRemoveAfter2 = [tagToRemoveAfter2];
1235 }
1236 tags.filter((tag) => {
1237 var _a;
1238 let element = GameWindowManager.getCanvasElement(tag);
1239 if (args.startOnlyIfHaveTexture) {
1240 if (element && element instanceof pixi_js.Sprite && ((_a = element.texture) == null ? void 0 : _a.label) == "EMPTY") {
1241 return false;
1242 }
1243 }
1244 return true;
1245 }).forEach((tag) => {
1246 let element = GameWindowManager.getCanvasElement(tag);
1247 if (element && element instanceof pixi_js.Container) {
1248 if (clockwise)
1249 element.rotation += speed * ticker.deltaTime;
1250 else
1251 element.rotation -= speed * ticker.deltaTime;
1252 if (speed < 1e-5 && !(args.speedProgression && args.speedProgression.type == "linear" && args.speedProgression.amt != 0)) {
1253 GameWindowManager.onEndOfTicker(tag, this, tagToRemoveAfter2, tickerId);
1254 }
1255 }
1256 });
1257 if (args.speedProgression)
1258 updateTickerProgression(args, "speed", args.speedProgression, this.speedConvert);
1259 }
1260 speedConvert(speed) {
1261 return speed / 60;
1262 }
1263};
1264exports.RotateTicker = __decorateClass([
1265 tickerDecorator()
1266], exports.RotateTicker);
1267exports.ZoomTicker = class ZoomTicker extends TickerBase {
1268 fn(ticker, args, tags, tickerId) {
1269 let xSpeed = 0.1;
1270 let ySpeed = 0.1;
1271 if (args.speed) {
1272 if (typeof args.speed === "number") {
1273 xSpeed = this.speedConvert(args.speed);
1274 ySpeed = this.speedConvert(args.speed);
1275 } else {
1276 xSpeed = this.speedConvert(args.speed.x);
1277 ySpeed = this.speedConvert(args.speed.y);
1278 }
1279 }
1280 let tagToRemoveAfter2 = args.tagToRemoveAfter || [];
1281 if (typeof tagToRemoveAfter2 === "string") {
1282 tagToRemoveAfter2 = [tagToRemoveAfter2];
1283 }
1284 let type = args.type || "zoom";
1285 let xLimit = type === "zoom" ? Infinity : 0;
1286 let yLimit = type === "zoom" ? Infinity : 0;
1287 if (args.limit) {
1288 if (typeof args.limit === "number") {
1289 xLimit = args.limit;
1290 yLimit = args.limit;
1291 } else {
1292 xLimit = args.limit.x;
1293 yLimit = args.limit.y;
1294 }
1295 }
1296 tags.filter((tag) => {
1297 var _a;
1298 let element = GameWindowManager.getCanvasElement(tag);
1299 if (args.startOnlyIfHaveTexture) {
1300 if (element && element instanceof pixi_js.Sprite && ((_a = element.texture) == null ? void 0 : _a.label) == "EMPTY") {
1301 return false;
1302 }
1303 }
1304 return true;
1305 }).forEach((tag) => {
1306 let element = GameWindowManager.getCanvasElement(tag);
1307 if (element && element instanceof pixi_js.Container) {
1308 if (type === "zoom" && (element.scale.x < xLimit || element.scale.y < yLimit)) {
1309 element.scale.x += xSpeed * ticker.deltaTime;
1310 element.scale.y += ySpeed * ticker.deltaTime;
1311 } else if (type === "unzoom" && (element.scale.x > xLimit || element.scale.y > yLimit)) {
1312 element.scale.x -= xSpeed * ticker.deltaTime;
1313 element.scale.y -= ySpeed * ticker.deltaTime;
1314 }
1315 if (type === "zoom") {
1316 if (element.scale.x > xLimit) {
1317 element.scale.x = xLimit;
1318 }
1319 if (element.scale.y > yLimit) {
1320 element.scale.y = yLimit;
1321 }
1322 if (element.scale.x >= xLimit && element.scale.y >= yLimit) {
1323 element.scale.x = xLimit;
1324 element.scale.y = yLimit;
1325 this.onEndOfTicker(tag, tickerId, element, tagToRemoveAfter2);
1326 }
1327 } else if (type === "unzoom") {
1328 if (element.scale.x < xLimit) {
1329 element.scale.x = xLimit;
1330 }
1331 if (element.scale.y < yLimit) {
1332 element.scale.y = yLimit;
1333 }
1334 if (element.scale.x <= xLimit && element.scale.y <= yLimit) {
1335 element.scale.x = xLimit;
1336 element.scale.y = yLimit;
1337 this.onEndOfTicker(tag, tickerId, element, tagToRemoveAfter2);
1338 }
1339 }
1340 if (xSpeed < 1e-5 && ySpeed < 1e-5 && !(args.speedProgression && args.speedProgression.type == "linear" && args.speedProgression.amt != 0)) {
1341 this.onEndOfTicker(tag, tickerId, element, tagToRemoveAfter2);
1342 }
1343 }
1344 });
1345 if (args.speedProgression)
1346 updateTickerProgression(args, "speed", args.speedProgression, this.speedConvert);
1347 }
1348 speedConvert(speed) {
1349 return speed / 60;
1350 }
1351 onEndOfTicker(tag, tickerId, _element, tagToRemoveAfter2) {
1352 GameWindowManager.onEndOfTicker(tag, this, tagToRemoveAfter2, tickerId);
1353 }
1354};
1355exports.ZoomTicker = __decorateClass([
1356 tickerDecorator()
1357], exports.ZoomTicker);
1358var ZoomInOutTicker = class extends exports.ZoomTicker {
1359 constructor(props, duration, priority) {
1360 super(props, duration, priority);
1361 }
1362 onEndOfTicker(tag, tickerId, element, tagToRemoveAfter2) {
1363 if (element.children.length > 0) {
1364 let elementChild = element.children[0];
1365 GameWindowManager.addCanvasElement(tag, elementChild);
1366 }
1367 super.onEndOfTicker(tag, tickerId, element, tagToRemoveAfter2);
1368 }
1369};
1370
1371// src/constants.ts
1372var PIXIVN_VERSION = "0.6.14";
1373var Repeat = "repeat";
1374function Pause(duration) {
1375 return {
1376 type: "pause",
1377 duration
1378 };
1379}
1380
1381// src/functions/ImageUtility.ts
1382function addImage(tag, imageUrl) {
1383 let image = new CanvasImage();
1384 image.imageLink = imageUrl;
1385 GameWindowManager.addCanvasElement(tag, image);
1386 return image;
1387}
1388function loadImage(canvasImages) {
1389 return __async(this, null, function* () {
1390 if (!Array.isArray(canvasImages)) {
1391 return [canvasImages];
1392 }
1393 let promises = Array(canvasImages.length);
1394 for (let i = 0; i < canvasImages.length; i++) {
1395 promises[i] = getTexture(canvasImages[i].imageLink);
1396 }
1397 return Promise.all(promises).then((textures) => {
1398 return textures.map((texture, index) => {
1399 if (texture) {
1400 canvasImages[index].texture = texture;
1401 return canvasImages[index];
1402 }
1403 canvasImages[index].load();
1404 return canvasImages[index];
1405 });
1406 });
1407 });
1408}
1409function showImage(tag, imageUrl) {
1410 return __async(this, null, function* () {
1411 let image = addImage(tag, imageUrl);
1412 yield image.load();
1413 return image;
1414 });
1415}
1416function removeCanvasElement(tag) {
1417 GameWindowManager.removeCanvasElement(tag);
1418}
1419function showWithDissolveTransition(_0, _1) {
1420 return __async(this, arguments, function* (tag, image, props = {}, priority) {
1421 var _a;
1422 let oldCanvasTag = void 0;
1423 if (GameWindowManager.getCanvasElement(tag)) {
1424 oldCanvasTag = tag + "_temp_disolve";
1425 GameWindowManager.editCanvasElementTag(tag, oldCanvasTag);
1426 }
1427 let canvasElement;
1428 if (typeof image === "string") {
1429 canvasElement = addImage(tag, image);
1430 } else {
1431 canvasElement = image;
1432 GameWindowManager.addCanvasElement(tag, canvasElement);
1433 }
1434 if (canvasElement instanceof CanvasImage && ((_a = canvasElement.texture) == null ? void 0 : _a.label) == "EMPTY") {
1435 yield canvasElement.load();
1436 }
1437 canvasElement.alpha = 0;
1438 let effect = new exports.FadeAlphaTicker(__spreadProps(__spreadValues({}, props), {
1439 type: "show",
1440 tagToRemoveAfter: oldCanvasTag,
1441 startOnlyIfHaveTexture: true
1442 }), 10, priority);
1443 GameWindowManager.addTicker(tag, effect);
1444 return;
1445 });
1446}
1447function removeWithDissolveTransition(tag, props = {}, priority) {
1448 if (typeof tag === "string") {
1449 tag = [tag];
1450 }
1451 let effect = new exports.FadeAlphaTicker(__spreadProps(__spreadValues({}, props), {
1452 type: "hide",
1453 tagToRemoveAfter: tag,
1454 startOnlyIfHaveTexture: true
1455 }), 10, priority);
1456 GameWindowManager.addTicker(tag, effect);
1457}
1458function showWithFadeTransition(_0, _1) {
1459 return __async(this, arguments, function* (tag, image, props = {}, priority) {
1460 var _a;
1461 if (!GameWindowManager.getCanvasElement(tag)) {
1462 return showWithDissolveTransition(tag, image, props, priority);
1463 }
1464 let oldCanvasTag = tag + "_temp_fade";
1465 GameWindowManager.editCanvasElementTag(tag, oldCanvasTag);
1466 let canvasElement;
1467 if (typeof image === "string") {
1468 canvasElement = addImage(tag, image);
1469 } else {
1470 canvasElement = image;
1471 GameWindowManager.addCanvasElement(tag, canvasElement);
1472 }
1473 if (canvasElement instanceof CanvasImage && ((_a = canvasElement.texture) == null ? void 0 : _a.label) == "EMPTY") {
1474 yield canvasElement.load();
1475 }
1476 canvasElement.alpha = 0;
1477 GameWindowManager.addTickersSteps(oldCanvasTag, [
1478 new exports.FadeAlphaTicker(__spreadProps(__spreadValues({}, props), {
1479 type: "hide",
1480 startOnlyIfHaveTexture: true
1481 }))
1482 ]);
1483 GameWindowManager.addTickersSteps(tag, [
1484 Pause(props.duration || 1),
1485 new exports.FadeAlphaTicker(__spreadProps(__spreadValues({}, props), {
1486 type: "show",
1487 startOnlyIfHaveTexture: true
1488 }))
1489 ]);
1490 });
1491}
1492function removeWithFadeTransition(tag, props = {}, priority) {
1493 return removeWithDissolveTransition(tag, props, priority);
1494}
1495function moveIn(_0, _1) {
1496 return __async(this, arguments, function* (tag, image, props = { direction: "right" }, priority) {
1497 var _a;
1498 let canvasElement;
1499 if (typeof image === "string") {
1500 canvasElement = addImage(tag, image);
1501 } else {
1502 canvasElement = image;
1503 GameWindowManager.addCanvasElement(tag, canvasElement);
1504 }
1505 if (canvasElement instanceof CanvasImage && ((_a = canvasElement.texture) == null ? void 0 : _a.label) == "EMPTY") {
1506 yield canvasElement.load();
1507 }
1508 let destination = { x: canvasElement.x, y: canvasElement.y };
1509 if (props.direction == "up") {
1510 canvasElement.y = GameWindowManager.canvasHeight + canvasElement.height;
1511 } else if (props.direction == "down") {
1512 canvasElement.y = -canvasElement.height;
1513 } else if (props.direction == "left") {
1514 canvasElement.x = GameWindowManager.canvasWidth + canvasElement.width;
1515 } else if (props.direction == "right") {
1516 canvasElement.x = -canvasElement.width;
1517 }
1518 let effect = new exports.MoveTicker(__spreadProps(__spreadValues({}, props), {
1519 destination,
1520 startOnlyIfHaveTexture: true
1521 }), priority);
1522 GameWindowManager.addTicker(tag, effect);
1523 });
1524}
1525function moveOut(tag, props = { direction: "right" }, priority) {
1526 let canvasElement = GameWindowManager.getCanvasElement(tag);
1527 if (!canvasElement) {
1528 console.warn("[Pixi'VN] The canvas element is not found.");
1529 return;
1530 }
1531 let destination = { x: canvasElement.x, y: canvasElement.y };
1532 if (props.direction == "up") {
1533 destination.y = -canvasElement.height;
1534 } else if (props.direction == "down") {
1535 destination.y = GameWindowManager.canvasHeight + canvasElement.height;
1536 } else if (props.direction == "left") {
1537 destination.x = -canvasElement.width;
1538 } else if (props.direction == "right") {
1539 destination.x = GameWindowManager.canvasWidth + canvasElement.width;
1540 }
1541 let effect = new exports.MoveTicker(__spreadProps(__spreadValues({}, props), {
1542 destination,
1543 startOnlyIfHaveTexture: true,
1544 tagToRemoveAfter: tag
1545 }), priority);
1546 GameWindowManager.addTicker(tag, effect);
1547}
1548function zoomIn(_0, _1) {
1549 return __async(this, arguments, function* (tag, image, props = { direction: "right" }, priority) {
1550 var _a;
1551 let canvasElement;
1552 if (typeof image === "string") {
1553 canvasElement = new CanvasImage({}, image);
1554 } else {
1555 canvasElement = image;
1556 }
1557 let container = new CanvasContainer();
1558 container.addChild(canvasElement);
1559 container.height = GameWindowManager.canvasHeight;
1560 container.width = GameWindowManager.canvasWidth;
1561 GameWindowManager.addCanvasElement(tag, container);
1562 if (canvasElement instanceof CanvasImage && ((_a = canvasElement.texture) == null ? void 0 : _a.label) == "EMPTY") {
1563 yield canvasElement.load();
1564 }
1565 if (props.direction == "up") {
1566 container.pivot.y = GameWindowManager.canvasHeight;
1567 container.pivot.x = GameWindowManager.canvasWidth / 2;
1568 container.y = GameWindowManager.canvasHeight;
1569 container.x = GameWindowManager.canvasWidth / 2;
1570 } else if (props.direction == "down") {
1571 container.pivot.y = 0;
1572 container.pivot.x = GameWindowManager.canvasWidth / 2;
1573 container.y = 0;
1574 container.x = GameWindowManager.canvasWidth / 2;
1575 } else if (props.direction == "left") {
1576 container.pivot.x = GameWindowManager.canvasWidth;
1577 container.pivot.y = GameWindowManager.canvasHeight / 2;
1578 container.x = GameWindowManager.canvasWidth;
1579 container.y = GameWindowManager.canvasHeight / 2;
1580 } else if (props.direction == "right") {
1581 container.pivot.x = 0;
1582 container.pivot.y = GameWindowManager.canvasHeight / 2;
1583 container.x = 0;
1584 container.y = GameWindowManager.canvasHeight / 2;
1585 }
1586 container.scale.set(0);
1587 let effect = new ZoomInOutTicker(__spreadProps(__spreadValues({}, props), {
1588 startOnlyIfHaveTexture: true,
1589 type: "zoom",
1590 limit: 1
1591 }), priority);
1592 GameWindowManager.addTicker(tag, effect);
1593 });
1594}
1595function zoomOut(tag, props = { direction: "right" }, priority) {
1596 let canvasElement = GameWindowManager.getCanvasElement(tag);
1597 if (!canvasElement) {
1598 console.warn("[Pixi'VN] The canvas element is not found.");
1599 return;
1600 }
1601 let container = new CanvasContainer();
1602 container.addChild(canvasElement);
1603 container.height = GameWindowManager.canvasHeight;
1604 container.width = GameWindowManager.canvasWidth;
1605 GameWindowManager.addCanvasElement(tag, container);
1606 if (props.direction == "up") {
1607 container.pivot.y = GameWindowManager.canvasHeight;
1608 container.pivot.x = GameWindowManager.canvasWidth / 2;
1609 container.y = GameWindowManager.canvasHeight;
1610 container.x = GameWindowManager.canvasWidth / 2;
1611 } else if (props.direction == "down") {
1612 container.pivot.y = 0;
1613 container.pivot.x = GameWindowManager.canvasWidth / 2;
1614 container.y = 0;
1615 container.x = GameWindowManager.canvasWidth / 2;
1616 } else if (props.direction == "left") {
1617 container.pivot.x = GameWindowManager.canvasWidth;
1618 container.pivot.y = GameWindowManager.canvasHeight / 2;
1619 container.x = GameWindowManager.canvasWidth;
1620 container.y = GameWindowManager.canvasHeight / 2;
1621 } else if (props.direction == "right") {
1622 container.pivot.x = 0;
1623 container.pivot.y = GameWindowManager.canvasHeight / 2;
1624 container.x = 0;
1625 container.y = GameWindowManager.canvasHeight / 2;
1626 }
1627 container.scale.set(1);
1628 let effect = new ZoomInOutTicker(__spreadProps(__spreadValues({}, props), {
1629 startOnlyIfHaveTexture: true,
1630 type: "unzoom",
1631 limit: 0,
1632 tagToRemoveAfter: tag
1633 }), priority);
1634 GameWindowManager.addTicker(tag, effect);
1635}
1636
1637// src/functions/Importer.ts
1638function importPixiVNJson(data) {
1639 try {
1640 if (typeof data === "string") {
1641 data = JSON.parse(data);
1642 }
1643 } catch (e) {
1644 console.error("[Pixi'VN] Error parsing imported Pixi'VN JSON", e);
1645 return;
1646 }
1647 if (typeof data !== "object") {
1648 console.error("[Pixi'VN] Error parsing imported Pixi'VN JSON: data is not an object");
1649 return;
1650 }
1651 if (data.labels) {
1652 let labels = data.labels;
1653 for (const labelId in labels) {
1654 try {
1655 const steps = labels[labelId];
1656 let label = new LabelJson2(labelId, steps);
1657 saveLabel(label);
1658 } catch (e) {
1659 console.error(`[Pixi'VN] Error creating JSON label ${labelId}`, e);
1660 }
1661 }
1662 }
1663}
1664
1665// src/functions/SavesUtility.ts
1666function getSaveData() {
1667 return {
1668 pixivn_version: PIXIVN_VERSION,
1669 stepData: GameStepManager.export(),
1670 storageData: GameStorageManager.export(),
1671 canvasData: GameWindowManager.export(),
1672 path: window.location.pathname
1673 };
1674}
1675function getSaveJson() {
1676 const saveData = getSaveData();
1677 return JSON.stringify(saveData);
1678}
1679function loadSaveData(data, navigate) {
1680 return __async(this, null, function* () {
1681 yield GameStepManager.import(data.stepData);
1682 GameStorageManager.import(data.storageData);
1683 GameWindowManager.import(data.canvasData);
1684 navigate(data.path);
1685 });
1686}
1687function loadSaveJson(dataString, navigate) {
1688 return __async(this, null, function* () {
1689 yield loadSaveData(jsonToSaveData(dataString), navigate);
1690 });
1691}
1692function jsonToSaveData(json) {
1693 return JSON.parse(json);
1694}
1695
1696// src/functions/ExportUtility.ts
1697function createExportableElement(element) {
1698 try {
1699 let elementString = JSON.stringify(element);
1700 return JSON.parse(elementString);
1701 } catch (e) {
1702 console.error("[Pixi'VN] Error creating exportable element", e);
1703 throw new Error("[Pixi'VN] Error creating exportable element");
1704 }
1705}
1706
1707// src/functions/DiffUtility.ts
1708function restoreDeepDiffChanges(data, differences) {
1709 let result = createExportableElement(data);
1710 differences.forEach((diff2) => {
1711 let dataToEdit = result;
1712 if (diff2.path && diff2.path.length > 0) {
1713 diff2.path.forEach((path, index) => {
1714 if (diff2.path && index === diff2.path.length - 1) {
1715 if (diff2.kind === "E" || diff2.kind === "D") {
1716 dataToEdit[path] = diff2.lhs;
1717 } else if (diff2.kind === "N") {
1718 if (Number.isInteger(path)) {
1719 if (Array.isArray(dataToEdit)) {
1720 dataToEdit.splice(path, 1);
1721 }
1722 } else if (typeof path === "string") {
1723 delete dataToEdit[path];
1724 }
1725 } else if (diff2.kind === "A") {
1726 let index2 = diff2.index;
1727 if (diff2.item.kind === "N") {
1728 dataToEdit[path].splice(index2, 1);
1729 } else if (diff2.item.kind === "E" || diff2.item.kind === "D") {
1730 dataToEdit[path][index2] = diff2.item.lhs;
1731 } else if (diff2.item.kind === "A") {
1732 console.warn("[Pixi'VN] Nested array found, skipping diff", diff2);
1733 } else {
1734 console.warn("[Pixi'VN] No array found, skipping diff", diff2);
1735 }
1736 }
1737 } else {
1738 dataToEdit = dataToEdit[path];
1739 }
1740 });
1741 } else {
1742 console.warn("[Pixi'VN] No path found, skipping diff", diff2);
1743 }
1744 });
1745 return result;
1746}
1747
1748// src/managers/StorageManager.ts
1749var _GameStorageManager = class _GameStorageManager {
1750 constructor() {
1751 }
1752 static get keysSystem() {
1753 return {
1754 /**
1755 * The key of the current dialogue memory
1756 */
1757 CURRENT_DIALOGUE_MEMORY_KEY: "___current_dialogue_memory___",
1758 /**
1759 * The key of the last dialogue added in the step memory
1760 */
1761 LAST_DIALOGUE_ADDED_IN_STEP_MEMORY_KEY: "___last_dialogue_added_in_step_memory___",
1762 /**
1763 * The key of the current menu options memory
1764 */
1765 CURRENT_MENU_OPTIONS_MEMORY_KEY: "___current_menu_options_memory___",
1766 /**
1767 * The key of the last menu options added in the step memory
1768 */
1769 LAST_MENU_OPTIONS_ADDED_IN_STEP_MEMORY_KEY: "___last_menu_options_added_in_step_memory___",
1770 /**
1771 * The key of the characters memory
1772 */
1773 CHARACTER_CATEGORY_KEY: "___character___",
1774 /**
1775 * The key of the flags memory
1776 */
1777 FLAGS_CATEGORY_KEY: "___flags___",
1778 /**
1779 * This variable is used to add the next dialog text into the current dialog memory.
1780 * This value was added to introduce Ink Glue functionality https://github.com/inkle/ink/blob/master/Documentation/WritingWithInk.md#glue
1781 */
1782 ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY: "___glue___"
1783 };
1784 }
1785 /**
1786 * Set a variable in the storage
1787 * @param key The key of the variable
1788 * @param value The value of the variable. If undefined, the variable will be removed
1789 * @returns
1790 */
1791 static setVariable(key, value) {
1792 key = key.toLowerCase();
1793 if (value === void 0 || value === null) {
1794 if (_GameStorageManager.storage.hasOwnProperty(key)) {
1795 delete _GameStorageManager.storage[key];
1796 }
1797 return;
1798 }
1799 _GameStorageManager.storage[key] = value;
1800 }
1801 /**
1802 * Get a variable from the storage
1803 * @param key The key of the variable
1804 * @returns The value of the variable. If the variable does not exist, it will return undefined
1805 */
1806 static getVariable(key) {
1807 key = key.toLowerCase();
1808 if (_GameStorageManager.storage.hasOwnProperty(key)) {
1809 return _GameStorageManager.storage[key];
1810 }
1811 return void 0;
1812 }
1813 /**
1814 * Remove a variable from the storage
1815 * @param key The key of the variable
1816 * @returns
1817 */
1818 static removeVariable(key) {
1819 key = key.toLowerCase();
1820 if (_GameStorageManager.storage.hasOwnProperty(key)) {
1821 delete _GameStorageManager.storage[key];
1822 }
1823 }
1824 /**
1825 * Clear the storage and the oidsUsed
1826 * @returns
1827 */
1828 static clear() {
1829 _GameStorageManager.storage = {};
1830 }
1831 static exportJson() {
1832 return JSON.stringify(this.export());
1833 }
1834 static export() {
1835 return createExportableElement(_GameStorageManager.storage);
1836 }
1837 static importJson(dataString) {
1838 _GameStorageManager.import(JSON.parse(dataString));
1839 }
1840 static import(data) {
1841 _GameStorageManager.clear();
1842 try {
1843 if (data) {
1844 _GameStorageManager.storage = data;
1845 } else {
1846 console.warn("[Pixi'VN] No storage data found");
1847 }
1848 } catch (e) {
1849 console.error("[Pixi'VN] Error importing data", e);
1850 }
1851 }
1852};
1853_GameStorageManager.storage = {};
1854var GameStorageManager = _GameStorageManager;
1855
1856// src/functions/EasterEgg.ts
1857function asciiArtLog() {
1858 console.info(`
1859 ____ _ _ ___ ___ _
1860 | _ \\(_)_ _(_| ) \\ / / \\ | |
1861 | |_) | \\ \\/ / |/ \\ \\ / /| \\| |
1862 | __/| |> <| | \\ V / | |\\ |
1863 |_| |_/_/\\_\\_| \\_/ |_| \\_|
1864 `);
1865}
1866
1867// src/types/ticker/TagToRemoveAfterType.ts
1868var tagToRemoveAfter = "tagToRemoveAfter";
1869
1870// src/managers/WindowManager.ts
1871var _GameWindowManager = class _GameWindowManager {
1872 constructor() {
1873 }
1874 /**
1875 * The PIXI Application instance.
1876 * It not recommended to use this property directly.
1877 */
1878 static get app() {
1879 if (!_GameWindowManager._app) {
1880 throw new Error("[Pixi'VN] GameWindowManager.app is undefined");
1881 }
1882 return _GameWindowManager._app;
1883 }
1884 /**
1885 * If the manager is initialized.
1886 */
1887 static get isInitialized() {
1888 return _GameWindowManager._isInitialized;
1889 }
1890 static get screen() {
1891 return _GameWindowManager.app.screen;
1892 }
1893 /**
1894 * Initialize the PIXI Application and the interface div.
1895 * This method should be called before any other method.
1896 * @param element The html element where I will put the canvas. Example: document.body
1897 * @param width The width of the canvas
1898 * @param height The height of the canvas
1899 * @param options The options of PIXI Application
1900 * @example
1901 * ```typescript
1902 * const body = document.body
1903 * if (!body) {
1904 * throw new Error('body element not found')
1905 * }
1906 * await GameWindowManager.initialize(body, 1920, 1080, {
1907 * backgroundColor: "#303030"
1908 * })
1909 * ```
1910 */
1911 static initialize(element, width, height, options) {
1912 return __async(this, null, function* () {
1913 _GameWindowManager.canvasWidth = width;
1914 _GameWindowManager.canvasHeight = height;
1915 _GameWindowManager._app = new pixi_js.Application();
1916 return _GameWindowManager.app.init(__spreadValues({
1917 resolution: window.devicePixelRatio || 1,
1918 autoDensity: true,
1919 width,
1920 height
1921 }, options)).then(() => {
1922 devtools.initDevtools({ app: _GameWindowManager._app });
1923 _GameWindowManager._isInitialized = true;
1924 this.addCanvasIntoHTMLElement(element);
1925 window.addEventListener("resize", _GameWindowManager.resize);
1926 _GameWindowManager.resize();
1927 asciiArtLog();
1928 });
1929 });
1930 }
1931 /**
1932 * Add the canvas into a html element.
1933 * @param element it is the html element where I will put the canvas. Example: document.body
1934 */
1935 static addCanvasIntoHTMLElement(element) {
1936 if (_GameWindowManager.isInitialized) {
1937 element.appendChild(_GameWindowManager.app.canvas);
1938 } else {
1939 console.error("[Pixi'VN] GameWindowManager is not initialized");
1940 }
1941 }
1942 /**
1943 * Initialize the interface div and add it into a html element.
1944 * @param element it is the html element where I will put the interface div. Example: document.getElementById('root')
1945 * @example
1946 * ```tsx
1947 * const root = document.getElementById('root')
1948 * if (!root) {
1949 * throw new Error('root element not found')
1950 * }
1951 * GameWindowManager.initializeHTMLLayout(root)
1952 * const reactRoot = createRoot(GameWindowManager.htmlLayout)
1953 * reactRoot.render(
1954 * <App />
1955 * )
1956 * ```
1957 */
1958 static initializeHTMLLayout(element) {
1959 let div = document.createElement("div");
1960 div.style.position = "absolute";
1961 div.style.pointerEvents = "none";
1962 element.appendChild(div);
1963 _GameWindowManager.htmlLayout = div;
1964 _GameWindowManager.resize();
1965 }
1966 /* Resize Metods */
1967 /**
1968 * This method returns the scale of the screen.
1969 */
1970 static get screenScale() {
1971 let screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
1972 let screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
1973 return Math.min(screenWidth / _GameWindowManager.canvasWidth, screenHeight / _GameWindowManager.canvasHeight);
1974 }
1975 /**
1976 * This method returns the width of the screen enlarged by the scale.
1977 */
1978 static get screenWidth() {
1979 return Math.floor(_GameWindowManager.screenScale * _GameWindowManager.canvasWidth);
1980 }
1981 /**
1982 * This method returns the height of the screen enlarged by the scale.
1983 */
1984 static get screenHeight() {
1985 return Math.floor(_GameWindowManager.screenScale * _GameWindowManager.canvasHeight);
1986 }
1987 /**
1988 * This method returns the horizontal margin of the screen.
1989 */
1990 static get horizontalMargin() {
1991 let screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
1992 return (screenWidth - _GameWindowManager.screenWidth) / 2;
1993 }
1994 /**
1995 * This method returns the vertical margin of the screen.
1996 */
1997 static get verticalMargin() {
1998 let screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
1999 return (screenHeight - _GameWindowManager.screenHeight) / 2;
2000 }
2001 /**
2002 * This method is called when the screen is resized.
2003 */
2004 static resize() {
2005 if (_GameWindowManager.isInitialized) {
2006 let style = _GameWindowManager.app.canvas.style;
2007 style.width = `${_GameWindowManager.screenWidth}px`;
2008 style.height = `${_GameWindowManager.screenHeight}px`;
2009 style.marginLeft = `${_GameWindowManager.horizontalMargin}px`;
2010 style.marginRight = `${_GameWindowManager.horizontalMargin}px`;
2011 style.marginTop = `${_GameWindowManager.verticalMargin}px`;
2012 style.marginBottom = `${_GameWindowManager.verticalMargin}px`;
2013 }
2014 if (_GameWindowManager.htmlLayout) {
2015 _GameWindowManager.htmlLayout.style.width = `${_GameWindowManager.screenWidth}px`;
2016 _GameWindowManager.htmlLayout.style.height = `${_GameWindowManager.screenHeight}px`;
2017 _GameWindowManager.htmlLayout.style.marginLeft = `${_GameWindowManager.horizontalMargin}px`;
2018 _GameWindowManager.htmlLayout.style.marginRight = `${_GameWindowManager.horizontalMargin}px`;
2019 _GameWindowManager.htmlLayout.style.marginTop = `${_GameWindowManager.verticalMargin}px`;
2020 _GameWindowManager.htmlLayout.style.marginBottom = `${_GameWindowManager.verticalMargin}px`;
2021 }
2022 }
2023 /* Edit Canvas Elements Methods */
2024 /**
2025 * This is a dictionary that contains all Canvas Elements of Canvas, currently.
2026 */
2027 static get currentCanvasElements() {
2028 return _GameWindowManager._children;
2029 }
2030 /**
2031 * Add a canvas element to the canvas.
2032 * If there is a canvas element with the same tag, it will be removed.
2033 * @param tag The tag of the canvas element.
2034 * @param canvasElement The canvas elements to be added.
2035 * @example
2036 * ```typescript
2037 * const texture = await Assets.load('https://pixijs.com/assets/bunny.png');
2038 * const sprite = CanvasSprite.from(texture);
2039 * GameWindowManager.addCanvasElement("bunny", sprite);
2040 * ```
2041 */
2042 static addCanvasElement(tag, canvasElement) {
2043 if (_GameWindowManager._children[tag]) {
2044 _GameWindowManager.removeCanvasElement(tag);
2045 }
2046 _GameWindowManager.app.stage.addChild(canvasElement);
2047 _GameWindowManager._children[tag] = canvasElement;
2048 _GameWindowManager.childrenTagsOrder.push(tag);
2049 }
2050 /**
2051 * Remove a canvas element from the canvas.
2052 * And remove all tickers that are not connected to any canvas element.
2053 * @param tags The tag of the canvas element to be removed.
2054 * @returns
2055 * @example
2056 * ```typescript
2057 * GameWindowManager.removeCanvasElement("bunny");
2058 * ```
2059 */
2060 static removeCanvasElement(tags) {
2061 if (typeof tags === "string") {
2062 tags = [tags];
2063 }
2064 tags.forEach((tag) => {
2065 if (_GameWindowManager._children[tag]) {
2066 _GameWindowManager.app.stage.removeChild(_GameWindowManager._children[tag]);
2067 delete _GameWindowManager._children[tag];
2068 _GameWindowManager.removeTickerByCanvasElement(tag);
2069 }
2070 });
2071 _GameWindowManager.childrenTagsOrder = _GameWindowManager.childrenTagsOrder.filter((t) => !tags.includes(t));
2072 }
2073 /**
2074 * Get a canvas element by the tag.
2075 * @param tag The tag of the canvas element.
2076 * @returns The canvas element.
2077 * @example
2078 * ```typescript
2079 * const sprite = GameWindowManager.getCanvasElement<CanvasSprite>("bunny");
2080 * ```
2081 */
2082 static getCanvasElement(tag) {
2083 return _GameWindowManager._children[tag];
2084 }
2085 /**
2086 * Check if a DisplayObject is on the canvas.
2087 * @param pixiElement The DisplayObject to be checked.
2088 * @returns If the DisplayObject is on the canvas.
2089 */
2090 static canvasElementIsOnCanvas(pixiElement) {
2091 return _GameWindowManager.app.stage.children.includes(pixiElement);
2092 }
2093 /**
2094 * Remove all canvas elements from the canvas.
2095 * And remove all tickers that are not connected to any canvas element.
2096 */
2097 static removeCanvasElements() {
2098 _GameWindowManager.app.stage.removeChildren();
2099 _GameWindowManager._children = {};
2100 _GameWindowManager.childrenTagsOrder = [];
2101 _GameWindowManager.removeAllTickers();
2102 }
2103 /**
2104 * Edit the tag of a canvas element.
2105 * @param oldTag The old tag of the canvas element.
2106 * @param newTag The new tag of the canvas element.
2107 */
2108 static editCanvasElementTag(oldTag, newTag) {
2109 if (_GameWindowManager._children[oldTag]) {
2110 _GameWindowManager._children[newTag] = _GameWindowManager._children[oldTag];
2111 delete _GameWindowManager._children[oldTag];
2112 }
2113 if (_GameWindowManager._currentTickersSteps[oldTag]) {
2114 _GameWindowManager._currentTickersSteps[newTag] = _GameWindowManager._currentTickersSteps[oldTag];
2115 delete _GameWindowManager._currentTickersSteps[oldTag];
2116 }
2117 for (let id in _GameWindowManager._currentTickers) {
2118 let ticker = _GameWindowManager._currentTickers[id];
2119 if (ticker.canvasElementTags.includes(oldTag)) {
2120 ticker.canvasElementTags = ticker.canvasElementTags.map((t) => t === oldTag ? newTag : t);
2121 if (ticker.args.hasOwnProperty(tagToRemoveAfter)) {
2122 let tagToRemoveAfter2 = ticker.args.tagToRemoveAfter;
2123 if (typeof tagToRemoveAfter2 === "string") {
2124 tagToRemoveAfter2 = [tagToRemoveAfter2];
2125 }
2126 if (Array.isArray(tagToRemoveAfter2)) {
2127 ticker.args.tagToRemoveAfter = tagToRemoveAfter2.map((t) => t === oldTag ? newTag : t);
2128 }
2129 }
2130 }
2131 }
2132 for (let timeout in _GameWindowManager._currentTickersTimeouts) {
2133 let TickerTimeout = _GameWindowManager._currentTickersTimeouts[timeout];
2134 if (TickerTimeout.tags.includes(oldTag)) {
2135 TickerTimeout.tags = TickerTimeout.tags.map((t) => t === oldTag ? newTag : t);
2136 }
2137 }
2138 }
2139 /** Edit Tickers Methods */
2140 /**
2141 * Currently tickers that are running.
2142 */
2143 static get currentTickers() {
2144 return _GameWindowManager._currentTickers;
2145 }
2146 static get currentTickersList() {
2147 return Object.values(_GameWindowManager._currentTickers);
2148 }
2149 static get currentTickersWithoutCreatedBySteps() {
2150 return Object.fromEntries(Object.entries(_GameWindowManager._currentTickers).filter(([_, ticker]) => !ticker.createdByTicketStepsId));
2151 }
2152 /**
2153 * The steps of the tickers
2154 */
2155 static get currentTickersSteps() {
2156 return _GameWindowManager._currentTickersSteps;
2157 }
2158 static generateTickerId(tickerData) {
2159 try {
2160 return sha1__default.default(JSON.stringify(tickerData)).toString() + "_" + Math.random().toString(36).substring(7);
2161 } catch (e) {
2162 throw new Error(`[Pixi'VN] Error to generate ticker id: ${e}`);
2163 }
2164 }
2165 /**
2166 * Run a ticker. You can run multiple addTicker with the same tag and different tickerClasses.
2167 * If you run a ticker with the same tag and tickerClass, the old ticker will be removed.
2168 * If already exists a sequence of tickers with the same tag, it will be removed.
2169 * @param canvasEslementTag The tag of the canvas element that will use the ticker.
2170 * @param ticker The ticker class to be run.
2171 * @param args The arguments to be used in the ticker.
2172 * @param duration The time to be used in the ticker. This number is in seconds. If it is undefined, the ticker will run forever.
2173 * @param priority The priority to be used in the ticker.
2174 * @returns
2175 * @example
2176 * ```typescript
2177 * GameWindowManager.addTicker("alien", new RotateTicker({ speed: 0.2 }))
2178 * ```
2179 */
2180 static addTicker(canvasElementTag, ticker) {
2181 let tickerId = ticker.id;
2182 if (typeof canvasElementTag === "string") {
2183 canvasElementTag = [canvasElementTag];
2184 }
2185 if (!geTickerInstanceById(tickerId, ticker.args, ticker.duration, ticker.priority)) {
2186 console.error(`[Pixi'VN] Ticker ${tickerId} not found`);
2187 return;
2188 }
2189 let tickerHistory = {
2190 fn: () => {
2191 },
2192 id: tickerId,
2193 args: createExportableElement(ticker.args),
2194 canvasElementTags: canvasElementTag,
2195 priority: ticker.priority,
2196 duration: ticker.duration
2197 };
2198 let id = _GameWindowManager.generateTickerId(tickerHistory);
2199 _GameWindowManager.pushTicker(id, tickerHistory, ticker);
2200 if (ticker.duration) {
2201 let timeout = setTimeout(() => {
2202 _GameWindowManager.removeTickerTimeoutInfo(timeout);
2203 let tickerTimeoutInfo = _GameWindowManager._currentTickersTimeouts[timeout.toString()];
2204 if (tickerTimeoutInfo) {
2205 _GameWindowManager.removeTicker(id);
2206 }
2207 }, ticker.duration * 1e3);
2208 _GameWindowManager.addTickerTimeoutInfo(canvasElementTag, tickerId, timeout.toString(), true);
2209 }
2210 }
2211 static pushTicker(id, tickerData, ticker) {
2212 _GameWindowManager.removeAssociationBetweenTickerCanvasElement(tickerData.canvasElementTags, ticker);
2213 _GameWindowManager._currentTickers[id] = tickerData;
2214 tickerData.fn = (t) => {
2215 let data = _GameWindowManager._currentTickers[id];
2216 if (data) {
2217 ticker == null ? void 0 : ticker.fn(t, data.args, data.canvasElementTags, id);
2218 }
2219 };
2220 _GameWindowManager.app.ticker.add(tickerData.fn, void 0, tickerData.priority);
2221 }
2222 /**
2223 * Run a sequence of tickers. If exists a ticker steps with the same tag, it will be removed.
2224 * @param tag The tag of canvas element that will use the tickers.
2225 * @param steps The steps of the tickers.
2226 * @param currentStepNumber The current step number. It is used to continue the sequence of tickers.
2227 * @returns
2228 * @example
2229 * ```typescript
2230 * GameWindowManager.addTickersSteps("alien", [
2231 * new RotateTicker({ speed: 0.1, clockwise: true }, 2), // 2 seconds
2232 * Pause(1), // 1 second
2233 * new RotateTicker({ speed: 0.2, clockwise: false }, 2),
2234 * Repeat,
2235 * ])
2236 * ```
2237 */
2238 static addTickersSteps(tag, steps, currentStepNumber = 0) {
2239 if (steps.length == 0) {
2240 console.warn("[Pixi'VN] The steps of the tickers is empty");
2241 return;
2242 }
2243 _GameWindowManager.removeTickerStepByCanvasElement(tag);
2244 _GameWindowManager._currentTickersSteps[tag] = {
2245 currentStepNumber,
2246 steps: steps.map((step) => {
2247 if (step === Repeat) {
2248 return step;
2249 }
2250 if (step.hasOwnProperty("type") && step.type === "pause") {
2251 return step;
2252 }
2253 let tickerId = step.id;
2254 return {
2255 ticker: tickerId,
2256 args: createExportableElement(step.args),
2257 duration: step.duration
2258 };
2259 })
2260 };
2261 _GameWindowManager.runTickersSteps(tag);
2262 }
2263 static restoneTickersSteps(data) {
2264 for (let tag in data) {
2265 let steps = data[tag];
2266 _GameWindowManager._currentTickersSteps[tag] = steps;
2267 _GameWindowManager.runTickersSteps(tag);
2268 }
2269 }
2270 static runTickersSteps(tag) {
2271 let step = _GameWindowManager._currentTickersSteps[tag].steps[_GameWindowManager._currentTickersSteps[tag].currentStepNumber];
2272 if (step === Repeat) {
2273 step = _GameWindowManager._currentTickersSteps[tag].steps[0];
2274 _GameWindowManager._currentTickersSteps[tag].currentStepNumber = 0;
2275 if (step === Repeat) {
2276 console.error("[Pixi'VN] TikersSteps has a RepeatType in the first step");
2277 return;
2278 }
2279 }
2280 if (step.hasOwnProperty("type") && step.type === "pause") {
2281 let timeout = setTimeout(() => {
2282 let tickerTimeoutInfo = _GameWindowManager._currentTickersTimeouts[timeout.toString()];
2283 if (tickerTimeoutInfo) {
2284 tickerTimeoutInfo.tags.forEach((tag2) => {
2285 _GameWindowManager.nextTickerStep(tag2);
2286 });
2287 }
2288 _GameWindowManager.removeTickerTimeoutInfo(timeout);
2289 }, step.duration * 1e3);
2290 _GameWindowManager.addTickerTimeoutInfo(tag, "steps", timeout.toString(), false);
2291 return;
2292 }
2293 let ticker = geTickerInstanceById(step.ticker, step.args, step.duration, step.priority);
2294 if (!ticker) {
2295 console.error(`[Pixi'VN] Ticker ${step.ticker} not found`);
2296 return;
2297 }
2298 let tickerName = ticker.id;
2299 let tickerHistory = {
2300 fn: () => {
2301 },
2302 id: tickerName,
2303 args: createExportableElement(ticker.args),
2304 canvasElementTags: [tag],
2305 priority: ticker.priority,
2306 duration: ticker.duration,
2307 createdByTicketStepsId: tag
2308 };
2309 let id = _GameWindowManager.generateTickerId(tickerHistory);
2310 _GameWindowManager.pushTicker(id, tickerHistory, ticker);
2311 if (ticker.duration) {
2312 let timeout = setTimeout(() => {
2313 let tickerTimeoutInfo = _GameWindowManager._currentTickersTimeouts[timeout.toString()];
2314 if (tickerTimeoutInfo) {
2315 _GameWindowManager.removeTicker(id);
2316 tickerTimeoutInfo.tags.forEach((tag2) => {
2317 _GameWindowManager.nextTickerStep(tag2);
2318 });
2319 }
2320 _GameWindowManager.removeTickerTimeoutInfo(timeout);
2321 }, ticker.duration * 1e3);
2322 _GameWindowManager.addTickerTimeoutInfo(tag, tickerName, timeout.toString(), false);
2323 }
2324 }
2325 static nextTickerStep(tag) {
2326 if (_GameWindowManager._currentTickersSteps[tag]) {
2327 let steps = _GameWindowManager._currentTickersSteps[tag];
2328 if (steps.currentStepNumber + 1 < steps.steps.length) {
2329 steps.currentStepNumber++;
2330 _GameWindowManager._currentTickersSteps[tag] = steps;
2331 _GameWindowManager.runTickersSteps(tag);
2332 } else {
2333 _GameWindowManager.removeTickerStepByCanvasElement(tag);
2334 }
2335 }
2336 }
2337 static onEndOfTicker(canvasElementTags, ticker, canvasElementTagsToDelete, tickerId) {
2338 let tickerData = _GameWindowManager._currentTickers[tickerId];
2339 _GameWindowManager.removeAssociationBetweenTickerCanvasElement(canvasElementTags, ticker);
2340 _GameWindowManager.removeCanvasElement(canvasElementTagsToDelete);
2341 if (tickerData) {
2342 _GameWindowManager.removeTicker(tickerId);
2343 if (tickerData.duration == void 0 && tickerData.createdByTicketStepsId) {
2344 _GameWindowManager.nextTickerStep(tickerData.createdByTicketStepsId);
2345 }
2346 }
2347 }
2348 /**
2349 * Remove a connection between a canvas element and a ticker.
2350 * And remove the ticker if there is no canvas element connected to it.
2351 * @param tags The tag of the canvas element that will use the ticker.
2352 * @param ticker The ticker class to be removed.
2353 * @example
2354 * ```typescript
2355 * GameWindowManager.removeAssociationBetweenTickerCanvasElement("alien", RotateTicker)
2356 * ```
2357 */
2358 static removeAssociationBetweenTickerCanvasElement(tags, ticker) {
2359 let tickerId;
2360 if (typeof ticker === "string") {
2361 tickerId = ticker;
2362 } else if (ticker instanceof TickerBase) {
2363 tickerId = ticker.id;
2364 } else {
2365 tickerId = ticker.prototype.id;
2366 }
2367 if (typeof tags === "string") {
2368 tags = [tags];
2369 }
2370 for (let id in _GameWindowManager._currentTickers) {
2371 let ticker2 = _GameWindowManager._currentTickers[id];
2372 if (ticker2.id === tickerId) {
2373 _GameWindowManager._currentTickers[id].canvasElementTags = ticker2.canvasElementTags.filter((e) => !tags.includes(e));
2374 }
2375 }
2376 for (let timeout in _GameWindowManager._currentTickersTimeouts) {
2377 let TickerTimeout = _GameWindowManager._currentTickersTimeouts[timeout];
2378 if (TickerTimeout.ticker === tickerId && TickerTimeout.canBeDeletedBeforeEnd) {
2379 _GameWindowManager._currentTickersTimeouts[timeout].tags = TickerTimeout.tags.filter((t) => !tags.includes(t));
2380 }
2381 }
2382 _GameWindowManager.removeTickersWithoutAssociatedCanvasElement();
2383 }
2384 /**
2385 * Remove all tickers that are not connected to any existing canvas element.
2386 */
2387 static removeTickersWithoutAssociatedCanvasElement() {
2388 for (let id in _GameWindowManager._currentTickers) {
2389 let ticker = _GameWindowManager._currentTickers[id];
2390 ticker.canvasElementTags = ticker.canvasElementTags.filter((e) => _GameWindowManager._children[e]);
2391 if (ticker.canvasElementTags.length === 0) {
2392 _GameWindowManager.removeTicker(id);
2393 }
2394 }
2395 for (let tag in _GameWindowManager._currentTickersSteps) {
2396 if (_GameWindowManager._children[tag] === void 0) {
2397 delete _GameWindowManager._currentTickersSteps[tag];
2398 }
2399 }
2400 Object.entries(_GameWindowManager._currentTickersTimeouts).forEach(([timeout, { tags }]) => {
2401 if (tags.length === 0) {
2402 _GameWindowManager.removeTickerTimeout(timeout);
2403 }
2404 });
2405 }
2406 static addTickerTimeoutInfo(tags, ticker, timeout, canBeDeletedBeforeEnd) {
2407 if (typeof tags === "string") {
2408 tags = [tags];
2409 }
2410 _GameWindowManager._currentTickersTimeouts[timeout] = {
2411 tags,
2412 ticker,
2413 canBeDeletedBeforeEnd
2414 };
2415 }
2416 static removeTickerTimeoutInfo(timeout) {
2417 if (typeof timeout !== "string") {
2418 timeout = timeout.toString();
2419 }
2420 if (_GameWindowManager._currentTickersTimeouts[timeout]) {
2421 delete _GameWindowManager._currentTickersTimeouts[timeout];
2422 }
2423 }
2424 static removeTickerTimeout(timeout) {
2425 if (typeof timeout !== "string") {
2426 timeout = timeout.toString();
2427 }
2428 clearTimeout(Number(timeout));
2429 _GameWindowManager.removeTickerTimeoutInfo(timeout);
2430 }
2431 static removeTickerTimeoutsByTag(tag, checkCanBeDeletedBeforeEnd) {
2432 for (let timeout in _GameWindowManager._currentTickersTimeouts) {
2433 let tagsWithoutTagToRemove = _GameWindowManager._currentTickersTimeouts[timeout].tags.filter((t) => t !== tag);
2434 if (tagsWithoutTagToRemove.length === 0) {
2435 let canBeDeletedBeforeEnd = _GameWindowManager._currentTickersTimeouts[timeout].canBeDeletedBeforeEnd;
2436 if (!checkCanBeDeletedBeforeEnd || canBeDeletedBeforeEnd) {
2437 _GameWindowManager.removeTickerTimeout(timeout);
2438 }
2439 } else {
2440 _GameWindowManager._currentTickersTimeouts[timeout].tags = tagsWithoutTagToRemove;
2441 }
2442 }
2443 }
2444 /**
2445 * Remove all tickers from the canvas.
2446 */
2447 static removeAllTickers() {
2448 _GameWindowManager._currentTickersSteps = {};
2449 Object.keys(_GameWindowManager._currentTickers).forEach((id) => {
2450 _GameWindowManager.removeTicker(id);
2451 });
2452 _GameWindowManager._currentTickers = {};
2453 for (let timeout in _GameWindowManager._currentTickersTimeouts) {
2454 _GameWindowManager.removeTickerTimeout(timeout);
2455 }
2456 }
2457 /**
2458 * Remove all tickers from a canvas element.
2459 * @param tag The tag of the canvas element that will use the ticker.
2460 */
2461 static removeTickerByCanvasElement(tag) {
2462 if (typeof tag === "string") {
2463 tag = [tag];
2464 }
2465 tag.forEach((tag2) => {
2466 for (let id in _GameWindowManager._currentTickers) {
2467 let ticker = _GameWindowManager._currentTickers[id];
2468 if (ticker.canvasElementTags.includes(tag2)) {
2469 _GameWindowManager.removeTicker(id);
2470 }
2471 }
2472 if (_GameWindowManager._currentTickersSteps[tag2]) {
2473 delete _GameWindowManager._currentTickersSteps[tag2];
2474 }
2475 _GameWindowManager.removeTickerTimeoutsByTag(tag2, false);
2476 delete _GameWindowManager._currentTickersSteps[tag2];
2477 });
2478 }
2479 static removeTickerStepByCanvasElement(tag) {
2480 if (_GameWindowManager._currentTickersSteps[tag]) {
2481 delete _GameWindowManager._currentTickersSteps[tag];
2482 }
2483 for (let id in _GameWindowManager._currentTickers) {
2484 let ticker = _GameWindowManager._currentTickers[id];
2485 if (ticker.createdByTicketStepsId === tag) {
2486 _GameWindowManager.removeTicker(id);
2487 }
2488 }
2489 }
2490 static removeTicker(tickerId) {
2491 let ticker = _GameWindowManager._currentTickers[tickerId];
2492 if (ticker) {
2493 if (ticker.args.hasOwnProperty(tagToRemoveAfter)) {
2494 let tagToRemoveAfter2 = ticker.args.tagToRemoveAfter;
2495 _GameWindowManager.removeCanvasElement(tagToRemoveAfter2);
2496 }
2497 _GameWindowManager.app.ticker.remove(ticker.fn);
2498 delete _GameWindowManager._currentTickers[tickerId];
2499 }
2500 }
2501 /**
2502 * Clear the canvas and the tickers.
2503 */
2504 static clear() {
2505 _GameWindowManager.removeCanvasElements();
2506 }
2507 /* Export and Import Methods */
2508 /**
2509 * Export the canvas and the tickers to a JSON string.
2510 * @returns The JSON string.
2511 */
2512 static exportJson() {
2513 return JSON.stringify(this.export());
2514 }
2515 /**
2516 * Export the canvas and the tickers to an object.
2517 * @returns The object.
2518 */
2519 static export() {
2520 let currentElements = {};
2521 for (let tag in _GameWindowManager._children) {
2522 currentElements[tag] = exportCanvasElement(_GameWindowManager._children[tag]);
2523 }
2524 return {
2525 currentTickers: createExportableElement(_GameWindowManager.currentTickersWithoutCreatedBySteps),
2526 currentTickersSteps: createExportableElement(_GameWindowManager._currentTickersSteps),
2527 currentElements: createExportableElement(currentElements),
2528 childrenTagsOrder: createExportableElement(_GameWindowManager.childrenTagsOrder)
2529 };
2530 }
2531 /**
2532 * Import the canvas and the tickers from a JSON string.
2533 * @param dataString The JSON string.
2534 */
2535 static importJson(dataString) {
2536 _GameWindowManager.import(JSON.parse(dataString));
2537 }
2538 /**
2539 * Import the canvas and the tickers from an object.
2540 * @param data The object.
2541 */
2542 static import(data) {
2543 _GameWindowManager.clear();
2544 try {
2545 if (data.hasOwnProperty("childrenTagsOrder") && data.hasOwnProperty("currentElements")) {
2546 let currentElements = data["currentElements"];
2547 let childrenTagsOrder = data["childrenTagsOrder"];
2548 childrenTagsOrder.forEach((tag) => {
2549 if (currentElements[tag]) {
2550 let element = importCanvasElement(currentElements[tag]);
2551 _GameWindowManager.addCanvasElement(tag, element);
2552 _GameWindowManager.childrenTagsOrder.push(tag);
2553 }
2554 });
2555 } else {
2556 console.error("[Pixi'VN] The data does not have the properties childrenTagsOrder and currentElements");
2557 return;
2558 }
2559 if (data.hasOwnProperty("currentTickers")) {
2560 let currentTickers = data["currentTickers"];
2561 for (let id in currentTickers) {
2562 let t = currentTickers[id];
2563 let tags = t.canvasElementTags;
2564 let ticker = geTickerInstanceById(t.id, t.args, t.duration, t.priority);
2565 if (ticker) {
2566 _GameWindowManager.addTicker(tags, ticker);
2567 } else {
2568 console.error(`[Pixi'VN] Ticker ${t.id} not found`);
2569 }
2570 }
2571 }
2572 if (data.hasOwnProperty("currentTickersSteps")) {
2573 let currentTickersSteps = data["currentTickersSteps"];
2574 _GameWindowManager.restoneTickersSteps(currentTickersSteps);
2575 }
2576 } catch (e) {
2577 console.error("[Pixi'VN] Error importing data", e);
2578 }
2579 }
2580};
2581_GameWindowManager._app = void 0;
2582_GameWindowManager._isInitialized = false;
2583_GameWindowManager._children = {};
2584/**
2585 * The order of the children tags.
2586 */
2587_GameWindowManager.childrenTagsOrder = [];
2588_GameWindowManager._currentTickers = {};
2589_GameWindowManager._currentTickersSteps = {};
2590_GameWindowManager._currentTickersTimeouts = {};
2591var GameWindowManager = _GameWindowManager;
2592
2593// src/managers/StepManager.ts
2594var _GameStepManager = class _GameStepManager {
2595 constructor() {
2596 }
2597 static get stepsHistory() {
2598 return _GameStepManager._stepsHistory;
2599 }
2600 /**
2601 * lastStepIndex is the last step index that occurred during the progression of the steps. **Not is the length of the stepsHistory - 1.**
2602 */
2603 static get lastStepIndex() {
2604 return _GameStepManager._lastStepIndex;
2605 }
2606 /**
2607 * Increase the last step index that occurred during the progression of the steps.
2608 */
2609 static increaseLastStepIndex() {
2610 _GameStepManager._lastStepIndex++;
2611 }
2612 static get openedLabels() {
2613 return _GameStepManager._openedLabels;
2614 }
2615 /**
2616 * currentLabelId is the current label id that occurred during the progression of the steps.
2617 */
2618 static get currentLabelId() {
2619 if (_GameStepManager._openedLabels.length > 0) {
2620 let item = _GameStepManager._openedLabels[_GameStepManager._openedLabels.length - 1];
2621 return item.label;
2622 }
2623 return void 0;
2624 }
2625 /**
2626 * currentLabel is the current label that occurred during the progression of the steps.
2627 */
2628 static get currentLabel() {
2629 if (_GameStepManager.currentLabelId) {
2630 return getLabelById(_GameStepManager.currentLabelId);
2631 }
2632 }
2633 static get currentLabelStepIndex() {
2634 if (_GameStepManager._openedLabels.length > 0) {
2635 let item = _GameStepManager._openedLabels[_GameStepManager._openedLabels.length - 1];
2636 return item.currentStepIndex;
2637 }
2638 return null;
2639 }
2640 /**
2641 * lastHistoryStep is the last history step that occurred during the progression of the steps.
2642 */
2643 static get lastHistoryStep() {
2644 if (_GameStepManager._stepsHistory.length > 0) {
2645 return _GameStepManager._stepsHistory[_GameStepManager._stepsHistory.length - 1];
2646 }
2647 return null;
2648 }
2649 static get originalStepData() {
2650 if (!_GameStepManager._originalStepData) {
2651 return {
2652 path: "",
2653 storage: {},
2654 canvas: {
2655 childrenTagsOrder: [],
2656 currentElements: {},
2657 currentTickers: {},
2658 currentTickersSteps: {}
2659 },
2660 labelIndex: -1,
2661 openedLabels: []
2662 };
2663 }
2664 return createExportableElement(_GameStepManager._originalStepData);
2665 }
2666 static set originalStepData(value) {
2667 _GameStepManager._originalStepData = createExportableElement(value);
2668 }
2669 static get currentStepData() {
2670 let currentStepData = {
2671 path: window.location.pathname,
2672 storage: GameStorageManager.export(),
2673 canvas: GameWindowManager.export(),
2674 labelIndex: _GameStepManager.currentLabelStepIndex || 0,
2675 openedLabels: createExportableElement(_GameStepManager._openedLabels)
2676 };
2677 return currentStepData;
2678 }
2679 /* Edit History Methods */
2680 /**
2681 * Add a label to the history.
2682 * @param label The label to add to the history.
2683 */
2684 static addStepHistory(step, choiseMade) {
2685 let stepHistory = getStepSha1(step);
2686 let currentStepData = _GameStepManager.currentStepData;
2687 if (_GameStepManager.originalStepData) {
2688 if (_GameStepManager.originalStepData.openedLabels.length === currentStepData.openedLabels.length) {
2689 try {
2690 let lastStepDataOpenedLabelsString = JSON.stringify(_GameStepManager.originalStepData.openedLabels);
2691 let historyStepOpenedLabelsString = JSON.stringify(currentStepData.openedLabels);
2692 if (lastStepDataOpenedLabelsString === historyStepOpenedLabelsString && _GameStepManager.originalStepData.path === currentStepData.path && _GameStepManager.originalStepData.labelIndex === currentStepData.labelIndex) {
2693 return;
2694 }
2695 } catch (e) {
2696 console.error("[Pixi'VN] Error comparing openedLabels", e);
2697 }
2698 }
2699 }
2700 let data = deepDiff.diff(_GameStepManager.originalStepData, currentStepData);
2701 if (data) {
2702 let dialoge = void 0;
2703 let requiredChoices = void 0;
2704 if (GameStorageManager.getVariable(GameStorageManager.keysSystem.LAST_DIALOGUE_ADDED_IN_STEP_MEMORY_KEY) === _GameStepManager.lastStepIndex) {
2705 dialoge = getDialogue();
2706 }
2707 if (GameStorageManager.getVariable(GameStorageManager.keysSystem.LAST_MENU_OPTIONS_ADDED_IN_STEP_MEMORY_KEY) === _GameStepManager.lastStepIndex) {
2708 requiredChoices = GameStorageManager.getVariable(GameStorageManager.keysSystem.CURRENT_MENU_OPTIONS_MEMORY_KEY);
2709 }
2710 _GameStepManager._stepsHistory.push({
2711 diff: data,
2712 currentLabel: _GameStepManager.currentLabelId,
2713 dialoge,
2714 choices: requiredChoices,
2715 stepSha1: stepHistory,
2716 index: _GameStepManager.lastStepIndex,
2717 choiceIndexMade: choiseMade
2718 });
2719 _GameStepManager.originalStepData = currentStepData;
2720 }
2721 _GameStepManager.increaseLastStepIndex();
2722 }
2723 /**
2724 * Add a label to the history.
2725 * @param label The label to add to the history.
2726 */
2727 static pushNewLabel(label) {
2728 let currentLabel = getLabelById(label);
2729 if (!currentLabel) {
2730 throw new Error(`[Pixi'VN] Label ${label} not found`);
2731 }
2732 _GameStepManager._openedLabels.push({
2733 label,
2734 currentStepIndex: 0
2735 });
2736 }
2737 /**
2738 * Close the current label and add it to the history.
2739 * @returns
2740 */
2741 static closeCurrentLabel() {
2742 if (!_GameStepManager.currentLabelId) {
2743 console.warn("[Pixi'VN] No label to close");
2744 return;
2745 }
2746 if (!_GameStepManager.currentLabel) {
2747 console.error("[Pixi'VN] currentLabel not found");
2748 return;
2749 }
2750 _GameStepManager._openedLabels.pop();
2751 }
2752 /**
2753 * Close all labels and add them to the history. **Attention: This method can cause an unhandled game ending.**
2754 */
2755 static closeAllLabels() {
2756 while (_GameStepManager._openedLabels.length > 0) {
2757 _GameStepManager.closeCurrentLabel();
2758 }
2759 }
2760 /**
2761 * Increase the current step index of the current label.
2762 */
2763 static increaseCurrentStepIndex() {
2764 let item = _GameStepManager._openedLabels[_GameStepManager._openedLabels.length - 1];
2765 _GameStepManager._openedLabels[_GameStepManager._openedLabels.length - 1] = __spreadProps(__spreadValues({}, item), {
2766 currentStepIndex: item.currentStepIndex + 1
2767 });
2768 }
2769 static restorLastLabelList() {
2770 _GameStepManager._openedLabels = _GameStepManager.originalStepData.openedLabels;
2771 }
2772 /* Run Methods */
2773 static get canGoNext() {
2774 let options = getChoiceMenuOptions();
2775 if (options && options.length > 0) {
2776 return false;
2777 }
2778 return true;
2779 }
2780 /**
2781 * Execute the next step and add it to the history.
2782 * @param props The props to pass to the step.
2783 * @param choiseMade The index of the choise made by the player. (This params is used in the choice menu)
2784 * @returns StepLabelResultType or undefined.
2785 * @example
2786 * ```typescript
2787 * function nextOnClick() {
2788 * setLoading(true)
2789 * GameStepManager.goNext(yourParams)
2790 * .then((result) => {
2791 * setUpdate((p) => p + 1)
2792 * setLoading(false)
2793 * if (result) {
2794 * // your code
2795 * }
2796 * })
2797 * .catch((e) => {
2798 * setLoading(false)
2799 * console.error(e)
2800 * })
2801 * }
2802 * ```
2803 */
2804 static goNext(props, choiseMade) {
2805 return __async(this, null, function* () {
2806 if (!_GameStepManager.canGoNext) {
2807 console.warn("[Pixi'VN] The player must make a choice");
2808 return;
2809 }
2810 if (_GameStepManager.currentLabel && _GameStepManager.currentLabel.onStepEnd) {
2811 yield _GameStepManager.currentLabel.onStepEnd(_GameStepManager.currentLabelStepIndex || 0, _GameStepManager.currentLabel);
2812 }
2813 _GameStepManager.increaseCurrentStepIndex();
2814 return yield _GameStepManager.runCurrentStep(props, choiseMade);
2815 });
2816 }
2817 /**
2818 * Execute the current step and add it to the history.
2819 * @param props The props to pass to the step.
2820 * @param choiseMade The choise made by the player.
2821 * @returns StepLabelResultType or undefined.
2822 */
2823 static runCurrentStep(props, choiseMade) {
2824 return __async(this, null, function* () {
2825 if (_GameStepManager.currentLabelId) {
2826 let currentLabelStepIndex = _GameStepManager.currentLabelStepIndex;
2827 if (currentLabelStepIndex === null) {
2828 console.error("[Pixi'VN] currentLabelStepIndex is null");
2829 return;
2830 }
2831 let currentLabel = _GameStepManager.currentLabel;
2832 if (!currentLabel) {
2833 console.error("[Pixi'VN] currentLabel not found");
2834 return;
2835 }
2836 if (currentLabel.steps.length > currentLabelStepIndex) {
2837 let onStepRun = currentLabel.onStepStart;
2838 if (onStepRun) {
2839 yield onStepRun(currentLabelStepIndex, currentLabel);
2840 }
2841 let step = currentLabel.steps[currentLabelStepIndex];
2842 let result = yield step(props);
2843 _GameStepManager.addStepHistory(step, choiseMade);
2844 return result;
2845 } else if (_GameStepManager.openedLabels.length > 1) {
2846 _GameStepManager.closeCurrentLabel();
2847 return yield _GameStepManager.goNext(props, choiseMade);
2848 } else {
2849 _GameStepManager.restorLastLabelList();
2850 if (_GameStepManager.gameEnd) {
2851 return yield _GameStepManager.gameEnd(props);
2852 }
2853 console.error("[Pixi'VN] The end of the game is not managed, so the game is blocked. Read this documentation to know how to manage the end of the game: https://pixi-vn.web.app/start/labels.html#how-manage-the-end-of-the-game");
2854 return;
2855 }
2856 }
2857 });
2858 }
2859 /**
2860 * Execute the label and add it to the history. (It's similar to Ren'Py's call function)
2861 * @param label The label to execute or the id of the label
2862 * @param props The props to pass to the label.
2863 * @returns StepLabelResultType or undefined.
2864 * @example
2865 * ```typescript
2866 * GameStepManager.callLabel(startLabel, yourParams).then((result) => {
2867 * if (result) {
2868 * // your code
2869 * }
2870 * })
2871 * ```
2872 * @example
2873 * ```typescript
2874 * // if you use it in a step label you should return the result.
2875 * return GameStepManager.callLabel(startLabel).then((result) => {
2876 * return result
2877 * })
2878 * ```
2879 */
2880 static callLabel(label, props) {
2881 return __async(this, null, function* () {
2882 let choiseMade = void 0;
2883 let labelId;
2884 if (typeof label === "string") {
2885 labelId = label;
2886 } else {
2887 labelId = label.id;
2888 if (typeof label.choiseIndex === "number") {
2889 choiseMade = label.choiseIndex;
2890 }
2891 }
2892 try {
2893 if (labelId === CLOSE_LABEL_ID) {
2894 let closeCurrentLabel = newCloseLabel(choiseMade);
2895 let choice = {
2896 label: closeCurrentLabel,
2897 text: "",
2898 closeCurrentLabel: false,
2899 type: "close",
2900 props: {}
2901 };
2902 return _GameStepManager.closeChoiceMenu(choice, props);
2903 }
2904 let tempLabel = getLabelById(labelId);
2905 if (!tempLabel) {
2906 throw new Error(`[Pixi'VN] Label ${labelId} not found`);
2907 }
2908 if (_GameStepManager.currentLabel && _GameStepManager.currentLabel.onStepEnd) {
2909 yield _GameStepManager.currentLabel.onStepEnd(_GameStepManager.currentLabelStepIndex || 0, _GameStepManager.currentLabel);
2910 }
2911 _GameStepManager.pushNewLabel(tempLabel.id);
2912 } catch (e) {
2913 console.error("[Pixi'VN] Error calling label", e);
2914 return;
2915 }
2916 return yield _GameStepManager.runCurrentStep(props, choiseMade);
2917 });
2918 }
2919 /**
2920 * Execute the label, close the current label, execute the new label and add the new label to the history. (It's similar to Ren'Py's jump function)
2921 * @param label The label to execute.
2922 * @param props The props to pass to the label or the id of the label
2923 * @returns StepLabelResultType or undefined.
2924 * @example
2925 * ```typescript
2926 * GameStepManager.jumpLabel(startLabel, yourParams).then((result) => {
2927 * if (result) {
2928 * // your code
2929 * }
2930 * })
2931 * ```
2932 * @example
2933 * ```typescript
2934 * // if you use it in a step label you should return the result.
2935 * return GameStepManager.jumpLabel(startLabel).then((result) => {
2936 * return result
2937 * })
2938 * ```
2939 */
2940 static jumpLabel(label, props) {
2941 return __async(this, null, function* () {
2942 _GameStepManager.closeCurrentLabel();
2943 let choiseMade = void 0;
2944 let labelId;
2945 if (typeof label === "string") {
2946 labelId = label;
2947 } else {
2948 labelId = label.id;
2949 if (typeof label.choiseIndex === "number") {
2950 choiseMade = label.choiseIndex;
2951 }
2952 }
2953 try {
2954 if (labelId === CLOSE_LABEL_ID) {
2955 let closeCurrentLabel = newCloseLabel(choiseMade);
2956 let choice = {
2957 label: closeCurrentLabel,
2958 text: "",
2959 closeCurrentLabel: false,
2960 type: "close",
2961 props: {}
2962 };
2963 return _GameStepManager.closeChoiceMenu(choice, props);
2964 }
2965 let tempLabel = getLabelById(labelId);
2966 if (!tempLabel) {
2967 throw new Error(`[Pixi'VN] Label ${labelId} not found`);
2968 }
2969 if (_GameStepManager.currentLabel && _GameStepManager.currentLabel.onStepEnd) {
2970 yield _GameStepManager.currentLabel.onStepEnd(_GameStepManager.currentLabelStepIndex || 0, _GameStepManager.currentLabel);
2971 }
2972 _GameStepManager.pushNewLabel(tempLabel.id);
2973 } catch (e) {
2974 console.error("[Pixi'VN] Error jumping label", e);
2975 return;
2976 }
2977 return yield _GameStepManager.runCurrentStep(props, choiseMade);
2978 });
2979 }
2980 /**
2981 * When the player is in a choice menu, can use this function to exit to the choice menu.
2982 * @param choice
2983 * @param props
2984 * @returns StepLabelResultType or undefined.
2985 * @example
2986 * ```typescript
2987 * GameStepManager.closeChoiceMenu(yourParams).then((result) => {
2988 * if (result) {
2989 * // your code
2990 * }
2991 * })
2992 * ```
2993 */
2994 static closeChoiceMenu(choice, props) {
2995 return __async(this, null, function* () {
2996 let label = choice.label;
2997 let choiseMade = void 0;
2998 if (typeof label.choiseIndex === "number") {
2999 choiseMade = label.choiseIndex;
3000 }
3001 if (choice.closeCurrentLabel) {
3002 _GameStepManager.closeCurrentLabel();
3003 }
3004 return _GameStepManager.goNext(props, choiseMade);
3005 });
3006 }
3007 /* After Update Methods */
3008 // /**
3009 // * After the update or code edit, some steps or labels may no longer match.
3010 // * - In case of step mismatch, the game will be updated to the last matching step.
3011 // * - In case of label mismatch, the game gives an error.
3012 // * @returns
3013 // */
3014 // private static afterUpdate() {
3015 // // TODO: implement
3016 // if (!GameStepManager.currentLabel) {
3017 // // TODO: implement
3018 // return
3019 // }
3020 // let currentLabel = getLabelInstanceByClassName(GameStepManager.currentLabel)
3021 // if (!currentLabel) {
3022 // console.error("Label not found")
3023 // return
3024 // }
3025 // let oldSteps = GameStepManager.stepsAfterLastHistoryLabel
3026 // let currentStepIndex = currentLabel.getCorrespondingStepsNumber(oldSteps)
3027 // let stepToRemove = oldSteps.length - currentStepIndex
3028 // GameStepManager.removeLastHistoryNodes(stepToRemove)
3029 // GameStepManager.loadLastStep()
3030 // }
3031 // private static loadLastStep() {
3032 // // TODO: implement
3033 // }
3034 // /**
3035 // * Remove a number of items from the last of the history.
3036 // * @param itemNumber The number of items to remove from the last of the history.
3037 // */
3038 // private static removeLastHistoryNodes(itemNumber: number) {
3039 // // TODO: implement
3040 // for (let i = 0; i < itemNumber; i++) {
3041 // GameStepManager._stepsHistory.pop()
3042 // }
3043 // }
3044 // /**
3045 // * stepsAfterLastHistoryLabel is a list of steps that occurred after the last history label.
3046 // */
3047 // private static get stepsAfterLastHistoryLabel(): StepHistoryDataType[] {
3048 // let length = GameStepManager._stepsHistory.length
3049 // let steps: StepHistoryDataType[] = []
3050 // for (let i = length - 1; i >= 0; i--) {
3051 // let element = GameStepManager._stepsHistory[i]
3052 // if (typeof element === "object" && "stepSha1" in element) {
3053 // steps.push(element.stepSha1)
3054 // }
3055 // else {
3056 // break
3057 // }
3058 // }
3059 // steps = steps.reverse()
3060 // return steps
3061 // }
3062 /* Go Back & Refresh Methods */
3063 /**
3064 * Go back to the last step and add it to the history.
3065 * @param navigate The navigate function.
3066 * @param steps The number of steps to go back.
3067 * @returns
3068 * @example
3069 * ```typescript
3070 * export function goBack(navigate: (path: string) => void, afterBack?: () => void) {
3071 * GameStepManager.goBack(navigate)
3072 * afterBack && afterBack()
3073 * }
3074 * ```
3075 */
3076 static goBack(navigate, steps = 1) {
3077 return __async(this, null, function* () {
3078 if (steps <= 0) {
3079 console.warn("[Pixi'VN] Steps must be greater than 0");
3080 return;
3081 }
3082 if (_GameStepManager._stepsHistory.length <= 1) {
3083 console.warn("[Pixi'VN] No steps to go back");
3084 return;
3085 }
3086 let restoredStep = _GameStepManager.goBackInternal(steps, _GameStepManager.originalStepData);
3087 if (restoredStep) {
3088 _GameStepManager._originalStepData = restoredStep;
3089 _GameStepManager._openedLabels = createExportableElement(restoredStep.openedLabels);
3090 if (_GameStepManager.currentLabel && _GameStepManager.currentLabel.onLoadStep) {
3091 yield _GameStepManager.currentLabel.onLoadStep(_GameStepManager.currentLabelStepIndex || 0, _GameStepManager.currentLabel);
3092 }
3093 GameStorageManager.import(createExportableElement(restoredStep.storage));
3094 GameWindowManager.import(createExportableElement(restoredStep.canvas));
3095 navigate(restoredStep.path);
3096 } else {
3097 console.error("[Pixi'VN] Error going back");
3098 }
3099 });
3100 }
3101 static goBackInternal(steps, restoredStep) {
3102 if (steps <= 0) {
3103 return restoredStep;
3104 }
3105 if (_GameStepManager._stepsHistory.length == 0) {
3106 return restoredStep;
3107 }
3108 let lastHistoryStep = _GameStepManager.lastHistoryStep;
3109 if (lastHistoryStep) {
3110 try {
3111 let result = restoreDeepDiffChanges(restoredStep, lastHistoryStep.diff);
3112 _GameStepManager._lastStepIndex = lastHistoryStep.index;
3113 _GameStepManager._stepsHistory.pop();
3114 return _GameStepManager.goBackInternal(steps - 1, result);
3115 } catch (e) {
3116 console.error("[Pixi'VN] Error applying diff", e);
3117 return restoredStep;
3118 }
3119 } else {
3120 return restoredStep;
3121 }
3122 }
3123 /**
3124 * Return true if it is possible to go back.
3125 */
3126 static get canGoBack() {
3127 return _GameStepManager._stepsHistory.length > 1;
3128 }
3129 /**
3130 * Add a label to the history.
3131 */
3132 static clear() {
3133 _GameStepManager._stepsHistory = [];
3134 _GameStepManager._openedLabels = [];
3135 }
3136 /* Export and Import Methods */
3137 /**
3138 * Export the history to a JSON string.
3139 * @returns The history in a JSON string.
3140 */
3141 static exportJson() {
3142 return JSON.stringify(this.export());
3143 }
3144 /**
3145 * Export the history to an object.
3146 * @returns The history in an object.
3147 */
3148 static export() {
3149 return {
3150 stepsHistory: _GameStepManager._stepsHistory,
3151 openedLabels: _GameStepManager._openedLabels,
3152 lastStepIndex: _GameStepManager._lastStepIndex,
3153 originalStepData: _GameStepManager._originalStepData
3154 };
3155 }
3156 /**
3157 * Import the history from a JSON string.
3158 * @param dataString The history in a JSON string.
3159 */
3160 static importJson(dataString) {
3161 return __async(this, null, function* () {
3162 yield _GameStepManager.import(JSON.parse(dataString));
3163 });
3164 }
3165 /**
3166 * Import the history from an object.
3167 * @param data The history in an object.
3168 */
3169 static import(data) {
3170 return __async(this, null, function* () {
3171 _GameStepManager.clear();
3172 try {
3173 if (data.hasOwnProperty("stepsHistory")) {
3174 _GameStepManager._stepsHistory = data["stepsHistory"];
3175 } else {
3176 console.warn("[Pixi'VN] Could not import stepsHistory data, so will be ignored");
3177 }
3178 if (data.hasOwnProperty("openedLabels")) {
3179 _GameStepManager._openedLabels = data["openedLabels"];
3180 } else {
3181 console.warn("[Pixi'VN] Could not import openedLabels data, so will be ignored");
3182 }
3183 if (data.hasOwnProperty("lastStepIndex")) {
3184 _GameStepManager._lastStepIndex = data["lastStepIndex"];
3185 } else {
3186 console.warn("[Pixi'VN] Could not import lastStepIndex data, so will be ignored");
3187 }
3188 if (data.hasOwnProperty("originalStepData")) {
3189 _GameStepManager._originalStepData = data["originalStepData"];
3190 } else {
3191 console.warn("[Pixi'VN] Could not import originalStepData data, so will be ignored");
3192 }
3193 if (_GameStepManager.currentLabel && _GameStepManager.currentLabel.onLoadStep) {
3194 yield _GameStepManager.currentLabel.onLoadStep(_GameStepManager.currentLabelStepIndex || 0, _GameStepManager.currentLabel);
3195 }
3196 } catch (e) {
3197 console.error("[Pixi'VN] Error importing data", e);
3198 }
3199 });
3200 }
3201};
3202/**
3203 * stepHistory is a list of label events and steps that occurred during the progression of the steps.
3204 */
3205_GameStepManager._stepsHistory = [];
3206_GameStepManager._lastStepIndex = 0;
3207_GameStepManager._openedLabels = [];
3208_GameStepManager._originalStepData = void 0;
3209/**
3210 * Function to be executed at the end of the game. It should be set in the game initialization.
3211 * @example
3212 * ```typescript
3213 * GameStepManager.gameEnd = async (props) => {
3214 * props.navigate("/end")
3215 * }
3216 * ```
3217 */
3218_GameStepManager.gameEnd = void 0;
3219var GameStepManager = _GameStepManager;
3220
3221// src/classes/StoredClassModel.ts
3222var StoredClassModel = class {
3223 /**
3224 * @param categoryId The id of the category. For example if you are storing a character class, you can use "characters" as categoryId. so all instances of the character class will be stored in the "characters" category.
3225 * @param id The id of instance of the class. This id must be unique for the category.
3226 */
3227 constructor(categoryId, id) {
3228 this.categoryId = categoryId;
3229 this._id = id;
3230 }
3231 /**
3232 * Is id of the stored class. is unique for this class.
3233 */
3234 get id() {
3235 return this._id;
3236 }
3237 /**
3238 * Update a property in the storage.
3239 * @param propertyName The name of the property to set.
3240 * @param value The value to set. If is undefined, the property will be removed from the storage.
3241 */
3242 setStorageProperty(propertyName, value) {
3243 let storage = GameStorageManager.getVariable(this.categoryId);
3244 if (!storage) {
3245 storage = {};
3246 }
3247 if (!storage.hasOwnProperty(this.id)) {
3248 storage[this.id] = {};
3249 }
3250 if (value === void 0 || value === null) {
3251 if (storage[this.id].hasOwnProperty(propertyName)) {
3252 delete storage[this.id][propertyName];
3253 }
3254 } else {
3255 storage[this.id] = __spreadProps(__spreadValues({}, storage[this.id]), { [propertyName]: value });
3256 }
3257 if (Object.keys(storage[this.id]).length === 0) {
3258 delete storage[this.id];
3259 }
3260 GameStorageManager.setVariable(this.categoryId, storage);
3261 }
3262 /**
3263 * Get a property from the storage.
3264 * @param propertyName The name of the property to get.
3265 * @returns The value of the property. If the property is not found, returns undefined.
3266 */
3267 getStorageProperty(propertyName) {
3268 let storage = GameStorageManager.getVariable(this.categoryId);
3269 if (storage && storage.hasOwnProperty(this.id) && storage[this.id].hasOwnProperty(propertyName)) {
3270 return storage[this.id][propertyName];
3271 }
3272 return void 0;
3273 }
3274};
3275
3276// src/classes/CharacterBaseModel.ts
3277var CharacterBaseModel2 = class extends StoredClassModel {
3278 /**
3279 * @param id The id of the character.
3280 * @param props The properties of the character.
3281 */
3282 constructor(id, props) {
3283 super(GameStorageManager.keysSystem.CHARACTER_CATEGORY_KEY, id);
3284 this.defaultName = "";
3285 this.defaultName = props.name;
3286 this.defaultSurname = props.surname;
3287 this.defaultAge = props.age;
3288 this._icon = props.icon;
3289 this._color = props.color;
3290 }
3291 /***
3292 * The name of the character.
3293 * If you set undefined, it will return the default name.
3294 */
3295 get name() {
3296 return this.getStorageProperty("name") || this.defaultName;
3297 }
3298 set name(value) {
3299 this.setStorageProperty("name", value);
3300 }
3301 /**
3302 * The surname of the character.
3303 * If you set undefined, it will return the default surname.
3304 */
3305 get surname() {
3306 return this.getStorageProperty("surname") || this.defaultSurname;
3307 }
3308 set surname(value) {
3309 this.setStorageProperty("surname", value);
3310 }
3311 /**
3312 * The age of the character.
3313 * If you set undefined, it will return the default age.
3314 */
3315 get age() {
3316 return this.getStorageProperty("age") || this.defaultAge;
3317 }
3318 set age(value) {
3319 this.setStorageProperty("age", value);
3320 }
3321 /**
3322 * The icon of the character.
3323 */
3324 get icon() {
3325 return this._icon;
3326 }
3327 /**
3328 * The color of the character.
3329 */
3330 get color() {
3331 return this._color;
3332 }
3333};
3334
3335// src/classes/DialogueBaseModel.ts
3336var DialogueBaseModel = class {
3337 /**
3338 * @param text The text of the dialogue.
3339 * @param character The id of the character that is speaking.
3340 * @param oltherParams Other parameters that can be stored in the dialogue.
3341 */
3342 constructor(text, character, oltherParams = {}) {
3343 /**
3344 * The text of the dialogue.
3345 */
3346 this.text = "";
3347 /**
3348 * Other parameters that can be stored in the dialogue.
3349 */
3350 this.oltherParams = {};
3351 if (typeof text === "string") {
3352 this.text = text;
3353 if (typeof character === "string") {
3354 this.character = character;
3355 } else {
3356 this.character = character == null ? void 0 : character.id;
3357 }
3358 this.oltherParams = oltherParams;
3359 } else {
3360 this.text = text.text;
3361 if (text.character) {
3362 this.character = text.character;
3363 }
3364 this.oltherParams = text.oltherParams || {};
3365 }
3366 }
3367 /**
3368 * Export the dialogue to a DialogueBaseData object.
3369 *
3370 * @returns The data of the dialogue.
3371 */
3372 export() {
3373 return {
3374 text: this.text,
3375 character: this.character,
3376 oltherParams: this.oltherParams
3377 };
3378 }
3379};
3380
3381// src/classes/LabelJson.ts
3382var LabelJson2 = class extends LabelAbstract {
3383 /**
3384 * @param id is the id of the label
3385 * @param steps is the list of steps that the label will perform
3386 * @param props is the properties of the label
3387 */
3388 constructor(id, steps, props) {
3389 super(id, props);
3390 this._steps = steps;
3391 }
3392 /**
3393 * Get the steps of the label.
3394 */
3395 get steps() {
3396 if (typeof this._steps === "function") {
3397 return this._steps().map(this.stepConverter);
3398 }
3399 return this._steps.map(this.stepConverter);
3400 }
3401 stepConverter(step) {
3402 return (props) => {
3403 if (step.choices) {
3404 let options = step.choices.map((option) => {
3405 let text = "";
3406 if (Array.isArray(option.text)) {
3407 text = option.text.join();
3408 } else {
3409 text = option.text;
3410 }
3411 return new ChoiceMenuOption(text, option.label, option.props, option.type);
3412 });
3413 setChoiceMenuOptions(options);
3414 } else {
3415 clearChoiceMenuOptions();
3416 }
3417 if (step.glueEnabled) {
3418 setFlag(GameStorageManager.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY, true);
3419 } else if (step.glueEnabled === false) {
3420 setFlag(GameStorageManager.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY, false);
3421 }
3422 if (step.dialog) {
3423 setDialogue(step.dialog);
3424 }
3425 if (step.labelToOpen) {
3426 if (step.labelToOpen.type === "jump") {
3427 GameStepManager.jumpLabel(step.labelToOpen.labelId, props);
3428 } else {
3429 GameStepManager.callLabel(step.labelToOpen.labelId, props);
3430 }
3431 }
3432 if (step.goNextStep) {
3433 GameStepManager.goNext(props);
3434 }
3435 if (step.end === "game_end") {
3436 GameStepManager.closeAllLabels();
3437 GameStepManager.goNext(props);
3438 } else if (step.end === "label_end") {
3439 GameStepManager.closeCurrentLabel();
3440 }
3441 };
3442 }
3443};
3444
3445// src/labels/TestConstant.ts
3446var juliette = new CharacterBaseModel2("___pixivn_juliette___", {
3447 name: "Juliette",
3448 age: 25,
3449 icon: "https://firebasestorage.googleapis.com/v0/b/pixi-vn.appspot.com/o/public%2Fcharacters%2Fjuliette-square.webp?alt=media",
3450 color: "#ac0086"
3451});
3452saveCharacter(juliette);
3453var eggHeadImage = "https://pixijs.com/assets/eggHead.png";
3454var eggHeadName = `<span style="color:purple">Egg Head</span>`;
3455var flowerTopImage = "https://pixijs.com/assets/flowerTop.png";
3456var flowerTopName = `<span style="color:green">Flower Top</span>`;
3457var helmlokImage = "https://pixijs.com/assets/helmlok.png";
3458var helmlokName = `<span style="color:blue">Helmlok</span>`;
3459var skullyImage = "https://pixijs.com/assets/skully.png";
3460var skullyName = `<span style="color:red">Skully</span>`;
3461var bunnyImage = "https://pixijs.com/assets/bunny.png";
3462var bunnyName = `Bunny`;
3463
3464// src/labels/BaseCanvasElementTestLabel.ts
3465var BASE_CANVAS_ELEMENT_LABEL = "___pixi_vn_base_canvas_element_label___";
3466var baseCanvasElementTestLabel = newLabel(
3467 BASE_CANVAS_ELEMENT_LABEL,
3468 [
3469 () => __async(void 0, null, function* () {
3470 let number = 25;
3471 setDialogue({
3472 character: juliette,
3473 text: `Here's what's going to happen: I'm going to create ${number} bunnies (CanvasSprites) and put them in a CanvasContainer.`
3474 });
3475 const container = new CanvasContainer();
3476 GameWindowManager.addCanvasElement("container", container);
3477 const texture = yield pixi_js.Assets.load(bunnyImage);
3478 for (let i = 0; i < number; i++) {
3479 const bunny = new CanvasSprite(texture);
3480 bunny.x = i % 5 * 40;
3481 bunny.y = Math.floor(i / 5) * 40;
3482 container.addChild(bunny);
3483 }
3484 container.x = GameWindowManager.screen.width / 2;
3485 container.y = GameWindowManager.screen.height / 2;
3486 container.pivot.x = container.width / 2;
3487 container.pivot.y = container.height / 2;
3488 GameWindowManager.addTicker("container", new exports.RotateTicker({ speed: 1 }));
3489 }),
3490 () => __async(void 0, null, function* () {
3491 removeCanvasElement("container");
3492 setDialogue({
3493 character: juliette,
3494 text: `Here's what's going to happen: I'm going to create some CanvasText with different styles and put them on the stage.
3495But it will generate a warn message, because the FillGradient or FillPattern has not yet been supported by the Pixi\u2019VN ( you can see the status of the issue here: [#76](https://github.com/DRincs-Productions/pixi-vn/issues/76)).`
3496 });
3497 const basicStyle = new pixi_js.TextStyle({
3498 fill: "#ffffff"
3499 });
3500 const basicText = new CanvasText({
3501 text: "Basic text in pixi",
3502 style: basicStyle
3503 });
3504 basicText.x = 50;
3505 basicText.y = 100;
3506 GameWindowManager.addCanvasElement("basicText", basicText);
3507 const fill = new pixi_js.FillGradient(0, 0, 0, 36 * 1.7 * 7);
3508 const colors = [16777215, 65433].map((color) => pixi_js.Color.shared.setValue(color).toNumber());
3509 colors.forEach((number, index) => {
3510 const ratio = index / colors.length;
3511 fill.addColorStop(ratio, number);
3512 });
3513 const style = new pixi_js.TextStyle({
3514 fontFamily: "Arial",
3515 fontSize: 36,
3516 fontStyle: "italic",
3517 fontWeight: "bold",
3518 fill: { fill },
3519 stroke: { color: "#4a1850", width: 5, join: "round" },
3520 dropShadow: {
3521 color: "#ff5f74",
3522 blur: 4,
3523 angle: Math.PI / 6,
3524 distance: 6
3525 },
3526 wordWrap: true,
3527 wordWrapWidth: 440
3528 });
3529 const richText = new CanvasText({
3530 text: "Rich text with a lot of options and across multiple lines",
3531 style
3532 });
3533 richText.x = 50;
3534 richText.y = 220;
3535 GameWindowManager.addCanvasElement("richText", richText);
3536 const skewStyle = new pixi_js.TextStyle({
3537 fontFamily: "Arial",
3538 dropShadow: {
3539 alpha: 0.8,
3540 angle: 2.1,
3541 blur: 4,
3542 color: "0x111111",
3543 distance: 10
3544 },
3545 fill: "#ffffff",
3546 stroke: { color: "#004620", width: 12, join: "round" },
3547 fontSize: 60,
3548 fontWeight: "lighter"
3549 });
3550 const skewText = new CanvasText({
3551 text: "SKEW IS COOL",
3552 style: skewStyle
3553 });
3554 skewText.skew.set(0.65, -0.3);
3555 skewText.anchor.set(0.5, 0.5);
3556 skewText.x = 300;
3557 skewText.y = 480;
3558 GameWindowManager.addCanvasElement("skewText", skewText);
3559 })
3560 ]
3561);
3562var EventTest1 = class extends CanvasEvent {
3563 fn(event, sprite) {
3564 if (event === "pointerdown") {
3565 sprite.scale.x *= 1.25;
3566 sprite.scale.y *= 1.25;
3567 }
3568 }
3569};
3570EventTest1 = __decorateClass([
3571 eventDecorator("___pixi_vn_canvas_events_test_event1___")
3572], EventTest1);
3573var EventTest2 = class extends CanvasEvent {
3574 fn(event, sprite) {
3575 if (event === "pointerdown") {
3576 sprite.isdown = true;
3577 sprite.texture = pixi_js.Texture.from("https://pixijs.com/assets/button_down.png");
3578 sprite.alpha = 1;
3579 } else if (event === "pointerup" || event === "pointerupoutside") {
3580 sprite.isdown = false;
3581 if (sprite.isOver) {
3582 sprite.texture = pixi_js.Texture.from("https://pixijs.com/assets/button_over.png");
3583 } else {
3584 sprite.texture = pixi_js.Texture.from("https://pixijs.com/assets/button.png");
3585 }
3586 } else if (event === "pointerover") {
3587 sprite.isOver = true;
3588 if (sprite.isdown) {
3589 return;
3590 }
3591 sprite.texture = pixi_js.Texture.from("https://pixijs.com/assets/button_over.png");
3592 } else if (event === "pointerout") {
3593 sprite.isOver = false;
3594 if (sprite.isdown) {
3595 return;
3596 }
3597 sprite.texture = pixi_js.Texture.from("https://pixijs.com/assets/button.png");
3598 }
3599 }
3600};
3601EventTest2 = __decorateClass([
3602 eventDecorator("___pixi_vn_canvas_events_test_event2___")
3603], EventTest2);
3604var CANVAS_EVENTS_TEST_LABEL = "___pixi_vn_canvas_events_test___";
3605var canvasEventsTestLabel = newLabel(
3606 CANVAS_EVENTS_TEST_LABEL,
3607 [
3608 () => setDialogue({
3609 character: juliette,
3610 text: "This is the test of clickable elements in a canvas."
3611 }),
3612 () => __async(void 0, null, function* () {
3613 setDialogue({
3614 character: juliette,
3615 text: `This is my friend, ${bunnyName}. It's small now, but if you try to click on it it will get bigger and bigger. (This example is from the official [PixiJS website](https://pixijs.com/8.x/examples/events/click).)`
3616 });
3617 const texture = yield pixi_js.Assets.load(bunnyImage);
3618 const sprite = CanvasSprite.from(texture);
3619 sprite.scale.set(3);
3620 sprite.anchor.set(0.5);
3621 sprite.x = GameWindowManager.screen.width / 2;
3622 sprite.y = GameWindowManager.screen.height / 2;
3623 sprite.eventMode = "static";
3624 sprite.cursor = "pointer";
3625 sprite.onEvent("pointerdown", EventTest1);
3626 GameWindowManager.addCanvasElement("bunny", sprite);
3627 }),
3628 () => __async(void 0, null, function* () {
3629 GameWindowManager.clear();
3630 setDialogue({
3631 character: juliette,
3632 text: `This is the test of buttons in a canvas. (This example is from the official [PixiJS website](https://pixijs.com/8.x/examples/events/interactivity).)`
3633 });
3634 const backgroundT = yield pixi_js.Assets.load("https://pixijs.com/assets/bg_button.jpg");
3635 const background = new CanvasSprite(backgroundT);
3636 background.width = GameWindowManager.screen.width;
3637 background.height = GameWindowManager.screen.height;
3638 GameWindowManager.addCanvasElement("bg", background);
3639 const textureButton = yield pixi_js.Assets.load("https://pixijs.com/assets/button.png");
3640 const buttons = [];
3641 const buttonPositions = [175, 75, 655, 75, 410, 325, 150, 465, 685, 445];
3642 for (let i = 0; i < 5; i++) {
3643 const button = new CanvasSprite(textureButton);
3644 button.anchor.set(0.5);
3645 button.x = buttonPositions[i * 2];
3646 button.y = buttonPositions[i * 2 + 1];
3647 button.eventMode = "static";
3648 button.cursor = "pointer";
3649 button.onEvent("pointerdown", EventTest2).onEvent("pointerup", EventTest2).onEvent("pointerupoutside", EventTest2).onEvent("pointerover", EventTest2).onEvent("pointerout", EventTest2);
3650 GameWindowManager.addCanvasElement("button" + i, button);
3651 buttons.push(button);
3652 }
3653 buttons[0].scale.set(1.2);
3654 buttons[2].rotation = Math.PI / 10;
3655 buttons[3].scale.set(0.8);
3656 buttons[4].scale.set(0.8, 1.2);
3657 buttons[4].rotation = Math.PI;
3658 })
3659 ],
3660 {
3661 onLoadStep: () => __async(void 0, null, function* () {
3662 yield pixi_js.Assets.load([
3663 "https://pixijs.com/assets/bg_button.jpg",
3664 "https://pixijs.com/assets/button.png",
3665 "https://pixijs.com/assets/button_down.png",
3666 "https://pixijs.com/assets/button_over.png"
3667 ]);
3668 })
3669 }
3670);
3671var AlienTintingTest = class extends CanvasSprite {
3672 constructor() {
3673 super(...arguments);
3674 this.direction = 0;
3675 this.turningSpeed = 0;
3676 this.speed = 0;
3677 }
3678 get memory() {
3679 return __spreadProps(__spreadValues({}, super.memory), {
3680 direction: this.direction,
3681 turningSpeed: this.turningSpeed,
3682 speed: this.speed
3683 });
3684 }
3685 set memory(memory) {
3686 super.memory = memory;
3687 this.direction = memory.direction;
3688 this.turningSpeed = memory.turningSpeed;
3689 this.speed = memory.speed;
3690 }
3691 static from(source, skipCache) {
3692 let sprite = pixi_js.Sprite.from(source, skipCache);
3693 let mySprite = new AlienTintingTest();
3694 mySprite.texture = sprite.texture;
3695 return mySprite;
3696 }
3697};
3698AlienTintingTest = __decorateClass([
3699 canvasElementDecorator("___pixi_vn_custom_canvas_element___")
3700], AlienTintingTest);
3701var TintingTestTicker = class extends TickerBase {
3702 constructor() {
3703 super({});
3704 }
3705 fn(_t, _args, tags) {
3706 tags.forEach((tag) => {
3707 const dudeBoundsPadding = 100;
3708 const dudeBounds = new pixi_js.Rectangle(
3709 -dudeBoundsPadding,
3710 -dudeBoundsPadding,
3711 GameWindowManager.screen.width + dudeBoundsPadding * 2,
3712 GameWindowManager.screen.height + dudeBoundsPadding * 2
3713 );
3714 let dude = GameWindowManager.getCanvasElement(tag);
3715 if (dude && dude instanceof AlienTintingTest) {
3716 dude.direction += dude.turningSpeed * 0.01;
3717 dude.x += Math.sin(dude.direction) * dude.speed;
3718 dude.y += Math.cos(dude.direction) * dude.speed;
3719 dude.rotation = -dude.direction - Math.PI / 2;
3720 if (dude.x < dudeBounds.x) {
3721 dude.x += dudeBounds.width;
3722 } else if (dude.x > dudeBounds.x + dudeBounds.width) {
3723 dude.x -= dudeBounds.width;
3724 }
3725 if (dude.y < dudeBounds.y) {
3726 dude.y += dudeBounds.height;
3727 } else if (dude.y > dudeBounds.y + dudeBounds.height) {
3728 dude.y -= dudeBounds.height;
3729 }
3730 }
3731 });
3732 }
3733};
3734TintingTestTicker = __decorateClass([
3735 tickerDecorator("___pixi_vn_custom_ticker___")
3736], TintingTestTicker);
3737var CUSTOM_TICKER_CANVAS_ELEMENT_TEST_LABEL = "___pixi_vn_custom_ticker_canvas_element_test___";
3738var customTickerCanvasElementTestLabel = newLabel(
3739 CUSTOM_TICKER_CANVAS_ELEMENT_TEST_LABEL,
3740 [
3741 () => __async(void 0, null, function* () {
3742 const totalDudes = 100;
3743 for (let i = 0; i < totalDudes; i++) {
3744 const texture = yield pixi_js.Assets.load(eggHeadImage);
3745 const dude = AlienTintingTest.from(texture);
3746 dude.anchor.set(0.5);
3747 dude.scale.set(0.8 + Math.random() * 0.3);
3748 dude.x = Math.random() * GameWindowManager.screen.width;
3749 dude.y = Math.random() * GameWindowManager.screen.height;
3750 dude.tint = Math.random() * 16777215;
3751 dude.direction = Math.random() * Math.PI * 2;
3752 dude.turningSpeed = Math.random() - 0.8;
3753 dude.speed = 2 + Math.random() * 2;
3754 GameWindowManager.addCanvasElement("alien" + i, dude);
3755 GameWindowManager.addTicker("alien" + i, new TintingTestTicker());
3756 }
3757 setDialogue({
3758 character: juliette,
3759 text: `This is a test of custom ticker and canvas element. In this test, we have created ${totalDudes} ${eggHeadName} with random tint, scale, position, direction, turning speed, and speed. With the custom ticker, we are moving the custom canvas element in a random direction. (This example is from the official [PixiJS website](https://pixijs.com/8.x/examples/events/interactivity).)`
3760 });
3761 })
3762 ]
3763);
3764
3765// src/labels/ImagesAnimationsTestLabel.ts
3766var IMAGE_ANIMAIONS_TEST_LABEL = "___pixi_vn_images_animations_test___";
3767var imagesAnimationsTest = newLabel(IMAGE_ANIMAIONS_TEST_LABEL, [
3768 () => __async(void 0, null, function* () {
3769 setDialogue({ character: juliette, text: `These are my 4 puppets: ${eggHeadName}, ${flowerTopName}, ${helmlokName} and ${skullyName}. They can appear, disappear and animate at my will.` });
3770 let eggHead = addImage("eggHead", eggHeadImage);
3771 yield eggHead.load();
3772 eggHead.x = 100;
3773 eggHead.y = 100;
3774 let flowerTop = addImage("flowerTop", flowerTopImage);
3775 flowerTop.x = 300;
3776 flowerTop.y = 100;
3777 flowerTop.load();
3778 let helmlok = addImage("helmlok", helmlokImage);
3779 helmlok.x = 100;
3780 helmlok.y = 300;
3781 let skully = addImage("skully", skullyImage);
3782 skully.x = 300;
3783 skully.y = 300;
3784 yield loadImage([helmlok, skully]);
3785 }),
3786 () => __async(void 0, null, function* () {
3787 setDialogue({ character: juliette, text: "Here's what they can do." });
3788 setChoiceMenuOptions([
3789 new ChoiceMenuOption("Dissolve effect", imagesDissolveTest, {}),
3790 new ChoiceMenuOption("Fade effect", imagesFadeTest, {}),
3791 new ChoiceMenuOption("Rotate", imagesRotateTest, {}),
3792 new ChoiceMenuOption("Move", imagesMoveTest, {}),
3793 new ChoiceMenuOption("Zoom", imagesZoomTest, {}),
3794 new ChoiceMenuOption("Move in/out", imagesMoveInOutTest, {}),
3795 new ChoiceMenuOption("Zoom in/out", imagesZoomInOutTest, {}),
3796 new ChoiceMenuOptionClose("Cancel", true)
3797 ]);
3798 }),
3799 (props) => GameStepManager.jumpLabel(IMAGE_ANIMAIONS_TEST_LABEL, props)
3800]);
3801var imagesDissolveTest = newLabel("___pixi_vn_images_dissolve_test___", [
3802 () => {
3803 setDialogue({
3804 character: juliette,
3805 text: `Here's what's going to happen:
3806- ${eggHeadName} will disappear with a dissolve effect. If you go next, ${eggHeadName} reappears with a dissolve effect without stopping the dissolve effect
3807- ${eggHeadName} will appear instead of ${flowerTopName}.
3808- ${helmlokName} will disappear with a fade effect and reappear with a fade effect, and repeat.
3809- ${skullyName} will disappear with a fade effect, wait for 0.5 seconds, and reappear with a fade effect.`
3810 });
3811 removeWithDissolveTransition(["eggHead"], { duration: 2 });
3812 let eggHead = new CanvasImage({ x: 300, y: 100 }, eggHeadImage);
3813 showWithDissolveTransition("flowerTop", eggHead, { duration: 1 });
3814 GameWindowManager.addTickersSteps(
3815 "helmlok",
3816 [
3817 new exports.FadeAlphaTicker({
3818 duration: 1,
3819 type: "hide"
3820 }, 1),
3821 new exports.FadeAlphaTicker({
3822 duration: 1,
3823 type: "show"
3824 }, 1),
3825 Repeat
3826 ]
3827 );
3828 GameWindowManager.addTickersSteps(
3829 "skully",
3830 [
3831 new exports.FadeAlphaTicker({
3832 duration: 0.5,
3833 type: "hide",
3834 limit: 0.3
3835 }, 1),
3836 Pause(0.5),
3837 new exports.FadeAlphaTicker({
3838 duration: 1,
3839 type: "show"
3840 }, 1)
3841 ]
3842 );
3843 },
3844 () => __async(void 0, null, function* () {
3845 showWithDissolveTransition("eggHead", eggHeadImage, { duration: 0.5 });
3846 })
3847]);
3848var imagesFadeTest = newLabel("___pixi_vn_images_fade_test___", [
3849 () => {
3850 setDialogue({
3851 character: juliette,
3852 text: `Here's what's going to happen:
3853- ${eggHeadName} will disappear with a dissolve effect. If you go next, ${eggHeadName} reappears with a dissolve effect with stopping the dissolve effect
3854- ${eggHeadName} will appear instead of ${flowerTopName}.
3855- ${helmlokName} will disappear with a fade effect and reappear with a fade effect, and repeat.
3856- ${skullyName} will disappear with a fade effect, wait for 0.5 seconds, and reappear with a fade effect.`
3857 });
3858 removeWithFadeTransition(["eggHead"], { duration: 2 });
3859 let eggHead = new CanvasImage({ x: 300, y: 100 }, eggHeadImage);
3860 showWithFadeTransition("flowerTop", eggHead, { duration: 1 });
3861 GameWindowManager.addTickersSteps(
3862 "helmlok",
3863 [
3864 new exports.FadeAlphaTicker({
3865 duration: 1,
3866 type: "hide"
3867 }),
3868 new exports.FadeAlphaTicker({
3869 duration: 1,
3870 type: "show"
3871 }),
3872 Repeat
3873 ]
3874 );
3875 GameWindowManager.addTickersSteps(
3876 "skully",
3877 [
3878 new exports.FadeAlphaTicker({
3879 duration: 0.5,
3880 type: "hide",
3881 limit: 0.3
3882 }),
3883 Pause(0.5),
3884 new exports.FadeAlphaTicker({
3885 duration: 1,
3886 type: "show"
3887 })
3888 ]
3889 );
3890 },
3891 () => __async(void 0, null, function* () {
3892 let eggHeadOld = GameWindowManager.getCanvasElement("eggHead");
3893 if (eggHeadOld)
3894 eggHeadOld.alpha = 0;
3895 showWithFadeTransition("eggHead", eggHeadImage, { duration: 0.5 });
3896 })
3897]);
3898var imagesRotateTest = newLabel("___pixi_vn_images_rotate_test___", [
3899 () => {
3900 setDialogue({
3901 character: juliette,
3902 text: `Here's what's going to happen:
3903- ${eggHeadName} will rotate with a anchor set to 0.
3904- ${flowerTopName} will rotate with a anchor set to 0.5 and a exponential speed progression.
3905- ${helmlokName} will rotate with a anchor set to 0.5, rotate clockwise for 2 seconds, rotate counterclockwise with a exponential (-0.05) speed progression, and when it reaches 0, it will repeat.
3906- ${skullyName} will rotate with a anchor set to 1, rotate 3 seconds clockwise, wait for 0.5 seconds, and rotate 7 seconds counterclockwise.`
3907 });
3908 let eggHead = GameWindowManager.getCanvasElement("eggHead");
3909 if (eggHead)
3910 eggHead.anchor.set(0);
3911 let flowerTop = GameWindowManager.getCanvasElement("flowerTop");
3912 if (flowerTop)
3913 flowerTop.anchor.set(0.5);
3914 let helmlok = GameWindowManager.getCanvasElement("helmlok");
3915 if (helmlok)
3916 helmlok.anchor.set(0.5);
3917 let skully = GameWindowManager.getCanvasElement("skully");
3918 if (skully)
3919 skully.anchor.set(1);
3920 GameWindowManager.addTicker("eggHead", new exports.RotateTicker({
3921 speed: 6,
3922 clockwise: true
3923 }));
3924 GameWindowManager.addTicker("flowerTop", new exports.RotateTicker({
3925 speed: 6,
3926 clockwise: false,
3927 speedProgression: { type: "exponential", percentage: 0.01, limit: 300 }
3928 }));
3929 GameWindowManager.addTickersSteps("helmlok", [
3930 new exports.RotateTicker({
3931 speed: 6,
3932 clockwise: true
3933 }, 2),
3934 new exports.RotateTicker({
3935 speed: 100,
3936 clockwise: false,
3937 speedProgression: { type: "exponential", percentage: -0.05 }
3938 }),
3939 Repeat
3940 ]);
3941 GameWindowManager.addTickersSteps("skully", [
3942 new exports.RotateTicker({
3943 speed: 6,
3944 clockwise: true
3945 }, 3),
3946 Pause(0.5),
3947 new exports.RotateTicker({
3948 speed: 6,
3949 clockwise: false
3950 }, 7)
3951 ]);
3952 }
3953]);
3954var imagesMoveTest = newLabel("___pixi_vn_images_move_test___", [
3955 () => {
3956 setDialogue({
3957 character: juliette,
3958 text: `Here's what's going to happen:
3959- ${eggHeadName} will move to { x: 500, y: 100 } with a speed of 24.
3960- ${flowerTopName} will move to { x: 500, y: 300 } with a speed of 18.
3961- ${helmlokName} will move to { x: 100, y: 500 } with a speed of 150 and a linear speed progression of -2 ( limit 10 ), and then move to { x: 1700, y: 500 } with a speed of 10 and a linear speed progression of 2 ( limit 150 ), and repeat.
3962- ${skullyName} will move to { x: 500, y: 500 } with a speed of 40, wait for 0.5 seconds, and move to { x: 100, y: 100 } with a speed of 40.`
3963 });
3964 GameWindowManager.addTicker("eggHead", new exports.MoveTicker({
3965 destination: { x: 500, y: 100 },
3966 speed: 24
3967 }));
3968 GameWindowManager.addTicker("flowerTop", new exports.MoveTicker({
3969 destination: { x: 500, y: 300 },
3970 speed: 18
3971 }));
3972 GameWindowManager.addTickersSteps("helmlok", [
3973 new exports.MoveTicker({
3974 destination: { x: 100, y: 500 },
3975 speed: 150,
3976 speedProgression: { type: "linear", amt: -2, limit: 10 }
3977 }),
3978 new exports.MoveTicker({
3979 destination: { x: 1700, y: 500 },
3980 speed: 10,
3981 speedProgression: { type: "linear", amt: 2, limit: 150 }
3982 }),
3983 Repeat
3984 ]);
3985 GameWindowManager.addTickersSteps("skully", [
3986 new exports.MoveTicker({
3987 destination: { x: 500, y: 500 },
3988 speed: 40
3989 }),
3990 Pause(0.5),
3991 new exports.MoveTicker({
3992 destination: { x: 100, y: 100 },
3993 speed: 40
3994 })
3995 ]);
3996 }
3997]);
3998var imagesZoomTest = newLabel("___pixi_vn_images_zoom_test___", [
3999 () => {
4000 setDialogue({
4001 character: juliette,
4002 text: `Here's what's going to happen:
4003- ${eggHeadName} will zoom out with a speed of 3 and a limit of -0.5.
4004- ${flowerTopName} will zoom in with a speed of 3 and a limit of 2.
4005- ${helmlokName} will unzoom with a speed of 3 and a limit of -1, and zoom in with a speed of 3 and a limit of 1, and repeat.
4006- ${skullyName} will zoom in with a speed of 0.1 and a limit of 5, wait for 0.5 seconds, and zoom out with a speed of 3 and a limit of 1.`
4007 });
4008 let eggHead = GameWindowManager.getCanvasElement("eggHead");
4009 if (eggHead)
4010 eggHead.scale.set(2);
4011 let helmlok = GameWindowManager.getCanvasElement("helmlok");
4012 if (helmlok)
4013 helmlok.anchor.set(0.5);
4014 GameWindowManager.addTicker("eggHead", new exports.ZoomTicker({
4015 speed: 3,
4016 limit: -0.5,
4017 type: "unzoom"
4018 }));
4019 GameWindowManager.addTicker("flowerTop", new exports.ZoomTicker({
4020 speed: 3,
4021 limit: 2
4022 }));
4023 GameWindowManager.addTickersSteps("helmlok", [
4024 new exports.ZoomTicker({
4025 speed: 3,
4026 limit: -1,
4027 type: "unzoom"
4028 }),
4029 new exports.ZoomTicker({
4030 speed: 3,
4031 limit: 1
4032 }),
4033 Repeat
4034 ]);
4035 GameWindowManager.addTickersSteps("skully", [
4036 new exports.ZoomTicker({
4037 speed: 0.1,
4038 limit: 5,
4039 speedProgression: { type: "exponential", percentage: 0.02 }
4040 }),
4041 Pause(0.5),
4042 new exports.ZoomTicker({
4043 "type": "unzoom",
4044 speed: 3,
4045 limit: 1
4046 })
4047 ]);
4048 }
4049]);
4050var imagesMoveInOutTest = newLabel("___pixi_vn_images_move_in_out_test___", [
4051 () => __async(void 0, null, function* () {
4052 setDialogue({
4053 character: juliette,
4054 text: `Here's what's going to happen:
4055- ${eggHeadName} will move in from the top with a speed of 80. If you go next, ${eggHeadName} will move out from the bottom with a speed of 80.
4056- ${flowerTopName} will move in from the right with a speed of 80 and a speed progression of 0.02. If you go next, ${flowerTopName} will move out from the left with a speed of 80 and a speed progression of 0.02.
4057- ${helmlokName} will move in from the left with a speed of 80. If you go next, ${helmlokName} will move out from the right with a speed of 80.
4058- ${skullyName} will move in from the bottom with a speed of 80 and a speed progression of 0.02. If you go next, ${skullyName} will move out from the top with a speed of 80 and a speed progression of 0.02.`
4059 });
4060 let eggHead = new CanvasImage({ x: 100, y: 100 }, eggHeadImage);
4061 let flowerTop = new CanvasImage({ x: 300, y: 100 }, flowerTopImage);
4062 let helmlok = new CanvasImage({ x: 100, y: 300 }, helmlokImage);
4063 let skully = new CanvasImage({ x: 300, y: 300 }, skullyImage);
4064 moveIn("eggHead", eggHead, { speed: 80, direction: "down" });
4065 moveIn("flowerTop", flowerTop, {
4066 speed: 80,
4067 direction: "left",
4068 speedProgression: { type: "exponential", percentage: 0.02 }
4069 });
4070 moveIn("helmlok", helmlok, { speed: 80, direction: "right" });
4071 moveIn("skully", skully, {
4072 speed: 80,
4073 direction: "up",
4074 speedProgression: { type: "exponential", percentage: 0.02 }
4075 });
4076 }),
4077 () => {
4078 moveOut("eggHead", { speed: 80, direction: "down" });
4079 moveOut("flowerTop", { speed: 80, direction: "left" });
4080 moveOut("helmlok", { speed: 80, direction: "right" });
4081 moveOut("skully", { speed: 80, direction: "up" });
4082 }
4083]);
4084var imagesZoomInOutTest = newLabel("___pixi_vn_images_zoom_in_out_test___", [
4085 () => __async(void 0, null, function* () {
4086 setDialogue({
4087 character: juliette,
4088 text: `Here's what's going to happen:
4089- ${eggHeadName} will zoom in with a speed of 3. If you go next, ${eggHeadName} will zoom out with a speed of 3.
4090- ${flowerTopName} will zoom in with a speed of 3 and a speed progression of 0.02. If you go next, ${flowerTopName} will zoom out with a speed of 3.
4091- ${helmlokName} will zoom in with a speed of 3. If you go next, ${helmlokName} will zoom out with a speed of 1.
4092- ${skullyName} will zoom in with a speed of 3 and a speed progression of 0.02. If you go next, ${skullyName} will zoom out with a speed of 3 and a speed progression of 0.02.`
4093 });
4094 GameWindowManager.removeCanvasElements();
4095 let eggHead = new CanvasImage({ x: 100, y: 100 }, eggHeadImage);
4096 let flowerTop = new CanvasImage({ x: 300, y: 100 }, flowerTopImage);
4097 let helmlok = new CanvasImage({ x: 100, y: 300 }, helmlokImage);
4098 let skully = new CanvasImage({ x: 300, y: 300 }, skullyImage);
4099 zoomIn("eggHead", eggHead, { speed: 3, direction: "down" });
4100 zoomIn("flowerTop", flowerTop, {
4101 speed: 3,
4102 direction: "left",
4103 speedProgression: { type: "exponential", percentage: 0.02 }
4104 });
4105 zoomIn("helmlok", helmlok, { speed: 3, direction: "right" });
4106 zoomIn("skully", skully, {
4107 speed: 3,
4108 direction: "up",
4109 speedProgression: { type: "exponential", percentage: 0.02 }
4110 });
4111 }),
4112 () => __async(void 0, null, function* () {
4113 zoomOut("eggHead", {
4114 speed: 3,
4115 direction: "down",
4116 speedProgression: { type: "exponential", percentage: 0.02 }
4117 });
4118 zoomOut("flowerTop", { speed: 3, direction: "left" });
4119 zoomOut("helmlok", { speed: 1, direction: "right" });
4120 zoomOut("skully", {
4121 speed: 3,
4122 direction: "up",
4123 speedProgression: { type: "exponential", percentage: 0.02 }
4124 });
4125 })
4126]);
4127
4128// src/labels/MarkdownTest.ts
4129var MARKDOWN_TEST_LABEL = "___pixi_vn_markdown_test___";
4130var markdownTest = newLabel(MARKDOWN_TEST_LABEL, [
4131 () => __async(void 0, null, function* () {
4132 setDialogue({
4133 character: juliette,
4134 text: `
4135# Markdown Test
4136
4137Hello, this is a test of the markdown parser. Pixi'VN does not manage markdown, but you can implement a markdown parser to display text with markdown syntax.
4138
4139For example in React, you can use the library [react-markdown](https://www.npmjs.com/package/react-markdown).
4140
4141## Colored Text
4142
4143<span style="color:blue">some *blue* text</span>.
4144
4145<span style="color:red">some *red* text</span>.
4146
4147<span style="color:green">some *green* text</span>.
4148
4149## Bold Text
4150
4151**This is bold text.**
4152
4153## Italic Text
4154
4155*This is italic text.*
4156
4157## Delete Text
4158
4159~~This is deleted text.~~
4160
4161## Link Test
4162
4163[Link to Google](https://www.google.com)
4164
4165## H2 Test
4166
4167### H3 Test
4168
4169#### H4 Test
4170
4171## Code Test
4172
4173\`Hello World\`
4174
4175\`\`\`js
4176console.log("Hello World")
4177\`\`\`
4178
4179## List Test
4180
4181- Item 1
4182* Item 2
4183- [x] Item 3
4184
4185## Table Test
4186
4187| Header 1 | Header 2 |
4188| -------- | -------- |
4189| Cell 1 | Cell 2 |
4190
4191## Separator Test
4192
4193***
4194Footer
4195
4196`
4197 });
4198 })
4199]);
4200
4201// src/labels/StepLabelTest.ts
4202var STEP_LABEL_TEST_LABEL = "___pixi_vn_step_label_test___";
4203var stepLabelTestLAbel = newLabel(STEP_LABEL_TEST_LABEL, [
4204 () => __async(void 0, null, function* () {
4205 setDialogue({ character: juliette, text: `Pixi'VN manages the succession of "screens" with steps. Each step is a function that can be asynchronous.` });
4206 }),
4207 () => __async(void 0, null, function* () {
4208 setDialogue({ character: juliette, text: "The labels are containers of steps, they are used to organize the steps in a more readable way. For start a steps sequence, you must call or jump to a label." });
4209 }),
4210 () => __async(void 0, null, function* () {
4211 setDialogue({ character: juliette, text: "It is also possible to ask the player to make a choice." });
4212 }),
4213 () => __async(void 0, null, function* () {
4214 setDialogue({ character: juliette, text: "Browsing through available tests is one way to test the steps/labels system." });
4215 })
4216]);
4217
4218// src/labels/StartLabel.ts
4219var pixivnTestStartLabel = newLabel(
4220 "___pixi_vn_example_start_label___",
4221 [
4222 () => {
4223 let currentTimeName = "";
4224 const hour = (/* @__PURE__ */ new Date()).getHours();
4225 if (hour >= 5 && hour < 12) {
4226 currentTimeName = "morning\u{1F505}";
4227 } else if (hour >= 12 && hour < 18) {
4228 currentTimeName = "afternoon\u{1F506}";
4229 } else if (hour >= 18 && hour < 22) {
4230 currentTimeName = "evening\u26C5";
4231 } else {
4232 currentTimeName = "night\u{1F319}";
4233 }
4234 setDialogue({ character: juliette, text: `Good ${currentTimeName}! I'm ${juliette.name}, your virtual assistant. I'm here to help you with your tests.` });
4235 },
4236 () => setDialogue({ character: juliette, text: `You are running the Pixi\u2019VN v${PIXIVN_VERSION} test. This test will guide you through the different features of the library.` }),
4237 (props) => GameStepManager.jumpLabel(pixivnTestStartLabel2, props)
4238 ]
4239);
4240var openLink = newLabel(
4241 "___pixi_vn_open_link___",
4242 [
4243 (props) => {
4244 window.open(props.link);
4245 GameStepManager.goNext(props);
4246 }
4247 ]
4248);
4249var RESTART_TEST_LABEL = "___pixi_vn_restart_test_label___";
4250var pixivnTestStartLabel2 = newLabel(
4251 RESTART_TEST_LABEL,
4252 [
4253 () => {
4254 GameWindowManager.clear();
4255 setDialogue({ character: juliette, text: "Which test would you like to start with?" });
4256 setChoiceMenuOptions([
4257 new ChoiceMenuOption("Open Pixi\u2019VN Wiki", openLink, { link: "https://pixi-vn.web.app/" }),
4258 new ChoiceMenuOption("Images, Transitions and Animations Test", imagesAnimationsTest, {}),
4259 new ChoiceMenuOption("Canvas Events Test", canvasEventsTestLabel, {}),
4260 new ChoiceMenuOption("Base Canvas Element Test", baseCanvasElementTestLabel, {}),
4261 new ChoiceMenuOption("Custom Ticker Canvas Element Test", customTickerCanvasElementTestLabel, {}),
4262 new ChoiceMenuOption("Steps and Labels Test", stepLabelTestLAbel, {}),
4263 new ChoiceMenuOption("Markdown Test", markdownTest, {}),
4264 new ChoiceMenuOption("Open Pixi\u2019VN Github Issues", openLink, { link: "https://github.com/DRincs-Productions/pixi-vn/issues" })
4265 ]);
4266 },
4267 (props) => GameStepManager.jumpLabel(RESTART_TEST_LABEL, props)
4268 ]
4269);
4270
4271Object.defineProperty(exports, "Assets", {
4272 enumerable: true,
4273 get: function () { return pixi_js.Assets; }
4274});
4275exports.CanvasBase = CanvasBase;
4276exports.CanvasContainer = CanvasContainer;
4277exports.CanvasEvent = CanvasEvent;
4278exports.CanvasImage = CanvasImage;
4279exports.CanvasSprite = CanvasSprite;
4280exports.CanvasText = CanvasText;
4281exports.CharacterBaseModel = CharacterBaseModel2;
4282exports.ChoiceMenuOption = ChoiceMenuOption;
4283exports.ChoiceMenuOptionClose = ChoiceMenuOptionClose;
4284exports.Close = Close;
4285exports.DialogueBaseModel = DialogueBaseModel;
4286exports.GameStepManager = GameStepManager;
4287exports.GameStorageManager = GameStorageManager;
4288exports.GameWindowManager = GameWindowManager;
4289exports.Label = Label;
4290exports.LabelJson = LabelJson2;
4291exports.Pause = Pause;
4292exports.Repeat = Repeat;
4293exports.StoredClassModel = StoredClassModel;
4294exports.TickerBase = TickerBase;
4295exports.addImage = addImage;
4296exports.canvasElementDecorator = canvasElementDecorator;
4297exports.clearAllGameDatas = clearAllGameDatas;
4298exports.clearChoiceMenuOptions = clearChoiceMenuOptions;
4299exports.clearDialogue = clearDialogue;
4300exports.eventDecorator = eventDecorator;
4301exports.getAllCharacters = getAllCharacters;
4302exports.getCharacterById = getCharacterById;
4303exports.getChoiceMenuOptions = getChoiceMenuOptions;
4304exports.getDialogue = getDialogue;
4305exports.getDialogueHistory = getDialogueHistory;
4306exports.getFlag = getFlag;
4307exports.getLabelById = getLabelById;
4308exports.getSaveData = getSaveData;
4309exports.getSaveJson = getSaveJson;
4310exports.getTexture = getTexture;
4311exports.importPixiVNJson = importPixiVNJson;
4312exports.juliette = juliette;
4313exports.loadImage = loadImage;
4314exports.loadSaveData = loadSaveData;
4315exports.loadSaveJson = loadSaveJson;
4316exports.moveIn = moveIn;
4317exports.moveOut = moveOut;
4318exports.newLabel = newLabel;
4319exports.pixivnTestStartLabel = pixivnTestStartLabel;
4320exports.removeCanvasElement = removeCanvasElement;
4321exports.removeWithDissolveTransition = removeWithDissolveTransition;
4322exports.removeWithFadeTransition = removeWithFadeTransition;
4323exports.saveCharacter = saveCharacter;
4324exports.setChoiceMenuOptions = setChoiceMenuOptions;
4325exports.setDialogue = setDialogue;
4326exports.setFlag = setFlag;
4327exports.showImage = showImage;
4328exports.showWithDissolveTransition = showWithDissolveTransition;
4329exports.showWithFadeTransition = showWithFadeTransition;
4330exports.tickerDecorator = tickerDecorator;
4331exports.zoomIn = zoomIn;
4332exports.zoomOut = zoomOut;
4333//# sourceMappingURL=index.js.map
4334//# sourceMappingURL=index.js.map
\No newline at end of file