@rpgjs/client 5.0.0-beta.22 → 5.0.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/Game/Object.d.ts +6 -0
- package/dist/Game/Object.js +58 -2
- package/dist/Game/Object.js.map +1 -1
- package/dist/RpgClientEngine.d.ts +2 -0
- package/dist/RpgClientEngine.js +15 -6
- package/dist/RpgClientEngine.js.map +1 -1
- package/dist/components/character-hitbox.d.ts +13 -0
- package/dist/components/character-hitbox.js +38 -0
- package/dist/components/character-hitbox.js.map +1 -0
- package/dist/components/character-hitbox.spec.d.ts +1 -0
- package/dist/components/character.ce.js +38 -29
- package/dist/components/character.ce.js.map +1 -1
- package/dist/components/gui/dialogbox/index.ce.js +31 -2
- package/dist/components/gui/dialogbox/index.ce.js.map +1 -1
- package/dist/components/gui/hud/hud.ce.js +2 -2
- package/dist/components/gui/hud/hud.ce.js.map +1 -1
- package/dist/components/gui/menu/items-menu.ce.js +27 -4
- package/dist/components/gui/menu/items-menu.ce.js.map +1 -1
- package/dist/components/gui/menu/main-menu.ce.js +210 -155
- package/dist/components/gui/menu/main-menu.ce.js.map +1 -1
- package/dist/components/gui/save-load.ce.js +33 -4
- package/dist/components/gui/save-load.ce.js.map +1 -1
- package/dist/components/gui/shop/shop.ce.js +47 -4
- package/dist/components/gui/shop/shop.ce.js.map +1 -1
- package/dist/services/standalone.d.ts +6 -1
- package/dist/services/standalone.js +35 -17
- package/dist/services/standalone.js.map +1 -1
- package/dist/utils/syncHitbox.d.ts +1 -0
- package/dist/utils/syncHitbox.js +69 -0
- package/dist/utils/syncHitbox.js.map +1 -0
- package/dist/utils/syncHitbox.spec.d.ts +1 -0
- package/package.json +4 -4
- package/src/Game/Object.spec.ts +70 -6
- package/src/Game/Object.ts +90 -2
- package/src/RpgClientEngine.ts +19 -6
- package/src/components/character-hitbox.spec.ts +33 -0
- package/src/components/character-hitbox.ts +72 -0
- package/src/components/character.ce +52 -45
- package/src/components/gui/dialogbox/index.ce +56 -40
- package/src/components/gui/hud/hud.ce +2 -2
- package/src/components/gui/menu/items-menu.ce +12 -2
- package/src/components/gui/menu/main-menu.ce +37 -6
- package/src/components/gui/save-load.ce +48 -32
- package/src/components/gui/shop/shop.ce +28 -3
- package/src/services/standalone.spec.ts +47 -0
- package/src/services/standalone.ts +53 -20
- package/src/utils/syncHitbox.spec.ts +79 -0
- package/src/utils/syncHitbox.ts +104 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @rpgjs/client
|
|
2
2
|
|
|
3
|
+
## 5.0.0-beta.24
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e11f2ed: Fix main menu Escape handling, add outside-click and touch close controls for prebuilt modal GUIs, make menu layouts responsive on small screens, restore a compact desktop menu with an integrated sidebar and column-based item views, use fade-only menu transitions, improve Skills/Equipment and save slot spacing, make active menu rows less visually harsh, and improve HUD and dialog border rendering.
|
|
8
|
+
- 3fb2765: Apply Studio media scale as a multiplier of the default RPGJS display scale, then combine it with event instance scale instead of overwriting it.
|
|
9
|
+
- be412cf: Let Studio event-touch pressure plates overlap pushed events without physical separation, wait until ground sensors are mostly covered before firing, clean up touch tracking when collisions exit after z changes, and clamp route overshoot frames that could make pushed events jitter.
|
|
10
|
+
- Updated dependencies [e11f2ed]
|
|
11
|
+
- Updated dependencies [be412cf]
|
|
12
|
+
- @rpgjs/ui-css@5.0.0-beta.22
|
|
13
|
+
- @rpgjs/common@5.0.0-beta.23
|
|
14
|
+
- @rpgjs/server@5.0.0-beta.24
|
|
15
|
+
|
|
16
|
+
## 5.0.0-beta.23
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- e7d8d13: Hydrate Studio event hitboxes from the API initially, apply synchronized hitbox object payloads to client physics bodies, publish runtime Studio hitbox changes through the synced event collection instead of a separate setHitbox websocket path, and keep standalone map transfers on the restored room so transferred player positions and hitboxes are preserved in sample-dev.
|
|
21
|
+
- Updated dependencies [e7d8d13]
|
|
22
|
+
- @rpgjs/common@5.0.0-beta.22
|
|
23
|
+
- @rpgjs/server@5.0.0-beta.23
|
|
24
|
+
|
|
3
25
|
## 5.0.0-beta.22
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/dist/Game/Object.d.ts
CHANGED
|
@@ -25,8 +25,11 @@ type FlashTriggerOptions = Omit<FlashOptions, "tint"> & {
|
|
|
25
25
|
type ConfigurableTrigger<T> = Omit<Trigger<T>, "start"> & {
|
|
26
26
|
start(config?: T): Promise<void>;
|
|
27
27
|
};
|
|
28
|
+
export declare const multiplyGraphicDisplayScale: (baseScale: unknown, instanceScale: unknown) => [number, number];
|
|
28
29
|
export declare const withGraphicDisplayScale: (spritesheet: any, scale: unknown) => any;
|
|
29
30
|
export declare const appendFramePayload: (current: unknown, items: unknown) => Frame[];
|
|
31
|
+
export declare const getFrameTimestamp: (frame: Frame) => number;
|
|
32
|
+
export declare const mergeFreshFramePayload: (current: unknown, items: unknown, lastAppliedFrameTs?: number) => Frame[];
|
|
30
33
|
export declare abstract class RpgClientObject extends RpgCommonPlayer {
|
|
31
34
|
abstract _type: string;
|
|
32
35
|
emitParticleTrigger: Trigger<any>;
|
|
@@ -37,8 +40,10 @@ export declare abstract class RpgClientObject extends RpgCommonPlayer {
|
|
|
37
40
|
frames: Frame[];
|
|
38
41
|
graphicsSignals: import('canvasengine').WritableArraySignal<any[]>;
|
|
39
42
|
flashTrigger: ConfigurableTrigger<FlashTriggerOptions>;
|
|
43
|
+
private lastAppliedFrameTs;
|
|
40
44
|
private animationRestoreState?;
|
|
41
45
|
constructor();
|
|
46
|
+
private getFrameTimestamp;
|
|
42
47
|
/**
|
|
43
48
|
* Access the shared client hook registry.
|
|
44
49
|
*
|
|
@@ -51,6 +56,7 @@ export declare abstract class RpgClientObject extends RpgCommonPlayer {
|
|
|
51
56
|
* @returns The active {@link RpgClientEngine} instance.
|
|
52
57
|
*/
|
|
53
58
|
get engine(): RpgClientEngine<unknown>;
|
|
59
|
+
setHitbox(width: number, height: number): void;
|
|
54
60
|
private animationSubscription?;
|
|
55
61
|
private animationResetTimeout?;
|
|
56
62
|
private animationWaitResolve?;
|
package/dist/Game/Object.js
CHANGED
|
@@ -4,18 +4,57 @@ import { signal, trigger } from "canvasengine";
|
|
|
4
4
|
import { ModulesToken, RpgCommonPlayer } from "@rpgjs/common";
|
|
5
5
|
import { combineLatest, from, map, of, startWith, switchMap } from "rxjs";
|
|
6
6
|
//#region src/Game/Object.ts
|
|
7
|
+
var toFiniteScale = (value, fallback) => {
|
|
8
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
9
|
+
if (typeof value === "string" && value.trim()) {
|
|
10
|
+
const parsed = Number(value);
|
|
11
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
12
|
+
}
|
|
13
|
+
return fallback;
|
|
14
|
+
};
|
|
15
|
+
var normalizeGraphicScale = (value, fallback = [1, 1]) => {
|
|
16
|
+
if (typeof value === "number" || typeof value === "string") {
|
|
17
|
+
const scale = toFiniteScale(value, fallback[0]);
|
|
18
|
+
return [scale, scale];
|
|
19
|
+
}
|
|
20
|
+
if (Array.isArray(value)) {
|
|
21
|
+
const x = toFiniteScale(value[0], fallback[0]);
|
|
22
|
+
return [x, toFiniteScale(value[1] ?? value[0], x)];
|
|
23
|
+
}
|
|
24
|
+
if (value && typeof value === "object") {
|
|
25
|
+
const scale = value;
|
|
26
|
+
const x = toFiniteScale(scale.x, fallback[0]);
|
|
27
|
+
return [x, toFiniteScale(scale.y ?? scale.x, x)];
|
|
28
|
+
}
|
|
29
|
+
return fallback;
|
|
30
|
+
};
|
|
31
|
+
var multiplyGraphicDisplayScale = (baseScale, instanceScale) => {
|
|
32
|
+
const base = normalizeGraphicScale(baseScale);
|
|
33
|
+
const instance = normalizeGraphicScale(instanceScale);
|
|
34
|
+
return [base[0] * instance[0], base[1] * instance[1]];
|
|
35
|
+
};
|
|
7
36
|
var withGraphicDisplayScale = (spritesheet, scale) => {
|
|
8
37
|
if (!spritesheet || typeof spritesheet !== "object") return spritesheet;
|
|
9
38
|
if (scale === void 0 || scale === null) return spritesheet;
|
|
10
39
|
return {
|
|
11
40
|
...spritesheet,
|
|
12
|
-
displayScale: scale
|
|
41
|
+
displayScale: multiplyGraphicDisplayScale(spritesheet.displayScale, scale)
|
|
13
42
|
};
|
|
14
43
|
};
|
|
15
44
|
var appendFramePayload = (current, items) => {
|
|
16
45
|
const nextFrames = (Array.isArray(items) ? items : items ? [items] : []).flatMap((item) => Array.isArray(item) ? item : [item]);
|
|
17
46
|
return (Array.isArray(current) ? current : []).concat(nextFrames);
|
|
18
47
|
};
|
|
48
|
+
var getFrameTimestamp = (frame) => {
|
|
49
|
+
const timestamp = Number(frame.ts);
|
|
50
|
+
return Number.isFinite(timestamp) ? timestamp : 0;
|
|
51
|
+
};
|
|
52
|
+
var mergeFreshFramePayload = (current, items, lastAppliedFrameTs = 0) => {
|
|
53
|
+
return appendFramePayload(current, items).filter((frame) => {
|
|
54
|
+
const timestamp = getFrameTimestamp(frame);
|
|
55
|
+
return timestamp === 0 || timestamp > lastAppliedFrameTs;
|
|
56
|
+
}).sort((a, b) => getFrameTimestamp(a) - getFrameTimestamp(b));
|
|
57
|
+
};
|
|
19
58
|
var RpgClientObject = class extends RpgCommonPlayer {
|
|
20
59
|
constructor() {
|
|
21
60
|
super();
|
|
@@ -27,11 +66,12 @@ var RpgClientObject = class extends RpgCommonPlayer {
|
|
|
27
66
|
this.frames = [];
|
|
28
67
|
this.graphicsSignals = signal([]);
|
|
29
68
|
this.flashTrigger = trigger();
|
|
69
|
+
this.lastAppliedFrameTs = 0;
|
|
30
70
|
const engine = this.engine;
|
|
31
71
|
this.hooks.callHooks("client-sprite-onInit", this).subscribe();
|
|
32
72
|
this._frames.observable.subscribe(({ items }) => {
|
|
33
73
|
if (!this.id) return;
|
|
34
|
-
this.frames =
|
|
74
|
+
this.frames = mergeFreshFramePayload(this.frames, items, this.lastAppliedFrameTs);
|
|
35
75
|
});
|
|
36
76
|
combineLatest([this.graphics.observable.pipe(map(({ items }) => items)), this._graphicScale.observable.pipe(startWith({ value: this._graphicScale() }), map((payload) => payload?.value ?? payload))]).pipe(switchMap(([graphics, scale]) => {
|
|
37
77
|
const graphicRefs = Array.isArray(graphics) ? graphics : [];
|
|
@@ -46,10 +86,16 @@ var RpgClientObject = class extends RpgCommonPlayer {
|
|
|
46
86
|
const frame = this.frames.shift();
|
|
47
87
|
if (frame) {
|
|
48
88
|
if (typeof frame.x !== "number" || typeof frame.y !== "number") return;
|
|
89
|
+
const frameTs = this.getFrameTimestamp(frame);
|
|
90
|
+
if (frameTs > 0 && frameTs <= this.lastAppliedFrameTs) return;
|
|
49
91
|
engine.scene.setBodyPosition(this.id, frame.x, frame.y, "top-left");
|
|
92
|
+
if (frameTs > this.lastAppliedFrameTs) this.lastAppliedFrameTs = frameTs;
|
|
50
93
|
}
|
|
51
94
|
});
|
|
52
95
|
}
|
|
96
|
+
getFrameTimestamp(frame) {
|
|
97
|
+
return getFrameTimestamp(frame);
|
|
98
|
+
}
|
|
53
99
|
/**
|
|
54
100
|
* Access the shared client hook registry.
|
|
55
101
|
*
|
|
@@ -66,6 +112,16 @@ var RpgClientObject = class extends RpgCommonPlayer {
|
|
|
66
112
|
get engine() {
|
|
67
113
|
return inject(RpgClientEngine);
|
|
68
114
|
}
|
|
115
|
+
setHitbox(width, height) {
|
|
116
|
+
if (typeof width !== "number" || width <= 0) throw new Error("setHitbox: width must be a positive number");
|
|
117
|
+
if (typeof height !== "number" || height <= 0) throw new Error("setHitbox: height must be a positive number");
|
|
118
|
+
this.hitbox.set({
|
|
119
|
+
w: width,
|
|
120
|
+
h: height
|
|
121
|
+
});
|
|
122
|
+
const sceneMap = this.engine?.sceneMap;
|
|
123
|
+
if (sceneMap && this.id) sceneMap.updateHitbox?.(this.id, this.x(), this.y(), width, height);
|
|
124
|
+
}
|
|
69
125
|
clearAnimationControls() {
|
|
70
126
|
if (this.animationSubscription) {
|
|
71
127
|
this.animationSubscription.unsubscribe();
|
package/dist/Game/Object.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Object.js","names":[],"sources":["../../src/Game/Object.ts"],"sourcesContent":["import { Hooks, ModulesToken, RpgCommonPlayer } from \"@rpgjs/common\";\nimport { trigger, signal, type Trigger } from \"canvasengine\";\nimport { combineLatest, from, map, of, startWith, Subscription, switchMap } from \"rxjs\";\nimport { inject } from \"../core/inject\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\ntype Frame = { x: number; y: number; ts: number };\n\ntype AnimationRestoreOptions = {\n restoreAnimationName?: string;\n restoreGraphics?: any[];\n timeoutMs?: number;\n};\n\ntype FlashType = 'alpha' | 'tint' | 'both';\n\ntype FlashOptions = {\n type?: FlashType;\n duration?: number;\n cycles?: number;\n alpha?: number;\n tint?: number | string;\n};\n\ntype FlashTriggerOptions = Omit<FlashOptions, \"tint\"> & {\n tint: number;\n};\n\ntype ConfigurableTrigger<T> = Omit<Trigger<T>, \"start\"> & {\n start(config?: T): Promise<void>;\n};\n\nexport const withGraphicDisplayScale = (spritesheet: any, scale: unknown): any => {\n if (!spritesheet || typeof spritesheet !== \"object\") return spritesheet;\n if (scale === undefined || scale === null) return spritesheet;\n return {\n ...spritesheet,\n displayScale: scale,\n };\n};\n\nexport const appendFramePayload = (current: unknown, items: unknown): Frame[] => {\n const frameItems = Array.isArray(items) ? items : items ? [items] : [];\n const nextFrames = frameItems.flatMap((item): Frame[] =>\n Array.isArray(item) ? item : [item as Frame]\n );\n const currentFrames = Array.isArray(current) ? current as Frame[] : [];\n return currentFrames.concat(nextFrames);\n};\n\nexport abstract class RpgClientObject extends RpgCommonPlayer {\n abstract _type: string;\n emitParticleTrigger = trigger();\n particleName = signal(\"\");\n animationCurrentIndex = signal(0);\n animationIsPlaying = signal(false);\n _param = signal({});\n frames: Frame[] = [];\n graphicsSignals = signal<any[]>([]);\n flashTrigger: ConfigurableTrigger<FlashTriggerOptions> = trigger<FlashTriggerOptions>();\n private animationRestoreState?: {\n animationName: string;\n graphics: any[];\n };\n\n constructor() {\n super();\n const engine = this.engine;\n this.hooks.callHooks(\"client-sprite-onInit\", this).subscribe();\n\n this._frames.observable.subscribe(({ items }) => {\n if (!this.id) return;\n //if (this.id == this.engine.playerIdSignal()!) return;\n this.frames = appendFramePayload(this.frames, items);\n });\n\n const graphics$ = this.graphics.observable.pipe(map(({ items }) => items));\n const graphicScale$ = this._graphicScale.observable.pipe(\n startWith({ value: this._graphicScale() }),\n map((payload: any) => payload?.value ?? payload),\n );\n\n combineLatest([graphics$, graphicScale$])\n .pipe(\n switchMap(([graphics, scale]) => {\n const graphicRefs = Array.isArray(graphics) ? graphics : [];\n if (graphicRefs.length === 0) return of([]);\n return from(Promise.all(graphicRefs.map(async (graphic) => {\n const spritesheet = await engine.getSpriteSheet(graphic);\n return withGraphicDisplayScale(spritesheet, scale);\n })));\n })\n )\n .subscribe((sheets) => { \n this.graphicsSignals.set(sheets);\n });\n\n engine.tick\n .pipe\n //throttleTime(10)\n ()\n .subscribe(() => {\n const frame = this.frames.shift();\n if (frame) {\n if (typeof frame.x !== \"number\" || typeof frame.y !== \"number\") return;\n engine.scene.setBodyPosition(\n this.id,\n frame.x,\n frame.y,\n \"top-left\"\n );\n }\n });\n }\n\n /**\n * Access the shared client hook registry.\n *\n * @returns The hook service used to register and trigger client-side hooks.\n */\n get hooks() {\n return inject<Hooks>(ModulesToken);\n }\n\n /**\n * Access the current client engine instance.\n *\n * @returns The active {@link RpgClientEngine} instance.\n */\n get engine() {\n return inject(RpgClientEngine);\n }\n\n private animationSubscription?: Subscription;\n private animationResetTimeout?: ReturnType<typeof setTimeout>;\n private animationWaitResolve?: () => void;\n\n private clearAnimationControls() {\n if (this.animationSubscription) {\n this.animationSubscription.unsubscribe();\n this.animationSubscription = undefined;\n }\n if (this.animationResetTimeout) {\n clearTimeout(this.animationResetTimeout);\n this.animationResetTimeout = undefined;\n }\n }\n\n private resolveAnimationWait() {\n const resolve = this.animationWaitResolve;\n this.animationWaitResolve = undefined;\n resolve?.();\n }\n\n private finishTemporaryAnimation() {\n const restoreState = this.animationRestoreState;\n this.clearAnimationControls();\n this.animationCurrentIndex.set(0);\n this.animationRestoreState = undefined;\n this.animationIsPlaying.set(false);\n if (restoreState) {\n this.animationName.set(restoreState.animationName);\n this.graphics.set([...restoreState.graphics]);\n }\n this.resolveAnimationWait();\n }\n\n /**\n * Trigger a flash animation on this sprite\n * \n * This method triggers a flash effect using CanvasEngine's flash directive.\n * The flash can be configured with various options including type (alpha, tint, or both),\n * duration, cycles, and color.\n * \n * ## Design\n * \n * The flash uses a trigger system that is connected to the flash directive in the\n * character component. This allows for flexible configuration and can be triggered\n * from both server events and client-side code.\n * \n * @param options - Flash configuration options\n * @param options.type - Type of flash effect: 'alpha' (opacity), 'tint' (color), or 'both' (default: 'alpha')\n * @param options.duration - Duration of the flash animation in milliseconds (default: 300)\n * @param options.cycles - Number of flash cycles (flash on/off) (default: 1)\n * @param options.alpha - Alpha value when flashing, from 0 to 1 (default: 0.3)\n * @param options.tint - Tint color when flashing as hex value or color name (default: 0xffffff - white)\n * \n * @example\n * ```ts\n * // Simple flash with default settings (alpha flash)\n * player.flash();\n * \n * // Flash with red tint\n * player.flash({ type: 'tint', tint: 0xff0000 });\n * \n * // Flash with both alpha and tint\n * player.flash({ \n * type: 'both', \n * alpha: 0.5, \n * tint: 0xff0000,\n * duration: 200,\n * cycles: 2\n * });\n * \n * // Quick damage flash\n * player.flash({ \n * type: 'tint', \n * tint: 0xff0000, \n * duration: 150,\n * cycles: 1\n * });\n * ```\n */\n flash(options?: FlashOptions): void {\n const flashOptions = {\n type: options?.type || 'alpha',\n duration: options?.duration ?? 300,\n cycles: options?.cycles ?? 1,\n alpha: options?.alpha ?? 0.3,\n tint: options?.tint ?? 0xffffff,\n };\n \n // Convert color name to hex if needed\n let tintValue = flashOptions.tint;\n if (typeof tintValue === 'string') {\n // Common color name to hex mapping\n const colorMap: Record<string, number> = {\n 'white': 0xffffff,\n 'red': 0xff0000,\n 'green': 0x00ff00,\n 'blue': 0x0000ff,\n 'yellow': 0xffff00,\n 'cyan': 0x00ffff,\n 'magenta': 0xff00ff,\n 'black': 0x000000,\n };\n tintValue = colorMap[tintValue.toLowerCase()] ?? 0xffffff;\n }\n \n this.flashTrigger.start({\n ...flashOptions,\n tint: tintValue,\n });\n }\n\n /**\n * Reset animation state when animation changes externally\n *\n * This method should be called when the animation changes due to movement\n * or other external factors to ensure the animation system doesn't get stuck\n *\n * @example\n * ```ts\n * // Reset when player starts moving\n * player.resetAnimationState();\n * ```\n */\n resetAnimationState() {\n if (this.animationRestoreState) {\n this.finishTemporaryAnimation();\n return;\n }\n this.animationIsPlaying.set(false);\n this.animationCurrentIndex.set(0);\n this.clearAnimationControls();\n this.resolveAnimationWait();\n }\n\n /**\n * Set a custom animation for a specific number of times\n *\n * Plays a custom animation for the specified number of repetitions.\n * The animation system prevents overlapping animations and automatically\n * returns to the previous animation when complete.\n *\n * @param animationName - Name of the animation to play\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation 3 times\n * await player.setAnimation('attack', 3);\n *\n * // Play continuous spell animation\n * player.setAnimation('spell');\n * ```\n */\n setAnimation(animationName: string, nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n /**\n * Set a custom animation with temporary graphic change\n *\n * Plays a custom animation for the specified number of repetitions and temporarily\n * changes the player's graphic (sprite sheet) during the animation. The graphic\n * is automatically reset when the animation finishes.\n *\n * @param animationName - Name of the animation to play\n * @param graphic - The graphic(s) to temporarily use during the animation\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation with temporary graphic change\n * await player.setAnimation('attack', 'hero_attack', 3);\n * ```\n */\n setAnimation(animationName: string, graphic?: string | string[], nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n setAnimation(\n animationName: string,\n graphicOrNbTimes?: string | string[] | number,\n nbTimesOrOptions?: number | AnimationRestoreOptions,\n options?: AnimationRestoreOptions\n ): Promise<void> {\n let graphic: string | string[] | undefined;\n let finalNbTimes: number = Infinity;\n let restoreOptions: AnimationRestoreOptions | undefined = options;\n\n // Handle overloads\n if (typeof graphicOrNbTimes === 'number') {\n // setAnimation(animationName, nbTimes)\n finalNbTimes = graphicOrNbTimes;\n restoreOptions = typeof nbTimesOrOptions === 'object' ? nbTimesOrOptions : options;\n } else if (graphicOrNbTimes !== undefined) {\n // setAnimation(animationName, graphic, nbTimes)\n graphic = graphicOrNbTimes;\n if (typeof nbTimesOrOptions === 'number') {\n finalNbTimes = nbTimesOrOptions;\n } else {\n finalNbTimes = Infinity;\n restoreOptions = nbTimesOrOptions ?? options;\n }\n } else {\n // setAnimation(animationName) - nbTimes remains Infinity\n finalNbTimes = Infinity;\n }\n\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n\n const waitPromise =\n finalNbTimes === Infinity\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n this.animationWaitResolve = resolve;\n });\n\n this.animationIsPlaying.set(true);\n const previousAnimationName =\n restoreOptions?.restoreAnimationName ?? this.animationName();\n const previousGraphics = restoreOptions?.restoreGraphics\n ? [...restoreOptions.restoreGraphics]\n : [...this.graphics()];\n this.animationRestoreState = {\n animationName: previousAnimationName,\n graphics: previousGraphics,\n };\n this.animationCurrentIndex.set(0);\n\n // Temporarily change graphic if provided\n if (graphic !== undefined) {\n if (Array.isArray(graphic)) {\n this.graphics.set(graphic);\n } else {\n this.graphics.set([graphic]);\n }\n }\n\n this.clearAnimationControls();\n\n this.animationSubscription =\n this.animationCurrentIndex.observable.subscribe((index) => {\n if (index >= finalNbTimes) {\n this.finishTemporaryAnimation();\n }\n });\n\n if (finalNbTimes !== Infinity) {\n this.animationResetTimeout = setTimeout(() => {\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n }, restoreOptions?.timeoutMs ?? Math.max(1000, finalNbTimes * 1000));\n }\n\n this.animationName.set(animationName);\n\n return waitPromise;\n }\n\n /**\n * Display a registered component animation effect on this object.\n *\n * @param id - Identifier of the component animation to play.\n * @param params - Parameters forwarded to the animation effect.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showComponentAnimation(id: string, params: any): Promise<void> {\n const engine = inject(RpgClientEngine);\n return engine.getComponentAnimation(id).displayEffect(params, this);\n }\n\n /**\n * Display a registered spritesheet animation effect on this object.\n *\n * @param graphic - Identifier of the spritesheet to use.\n * @param animationName - Name of the animation inside the spritesheet.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showAnimation(graphic: string, animationName: string = 'default'): Promise<void> {\n return this.showComponentAnimation('animation', {\n graphic,\n animationName,\n });\n }\n \n /**\n * Check whether this client object represents an event.\n *\n * @returns `true` if the object type is `event`, otherwise `false`.\n */\n isEvent(): boolean {\n return this._type === 'event';\n }\n\n /**\n * Check whether this client object represents a player.\n *\n * @returns `true` if the object type is `player`, otherwise `false`.\n */\n isPlayer(): boolean {\n return this._type === 'player';\n }\n}\n"],"mappings":";;;;;;AA+BA,IAAa,2BAA2B,aAAkB,UAAwB;CAChF,IAAI,CAAC,eAAe,OAAO,gBAAgB,UAAU,OAAO;CAC5D,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,OAAO;EACL,GAAG;EACH,cAAc;CAChB;AACF;AAEA,IAAa,sBAAsB,SAAkB,UAA4B;CAE/E,MAAM,cADa,MAAM,QAAQ,KAAK,IAAI,QAAQ,QAAQ,CAAC,KAAK,IAAI,CAAC,GACvC,SAAS,SACrC,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAa,CAC7C;CAEA,QADsB,MAAM,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1B,KAAK,yBAAyB;EAElC,GAAG,gBAAgB,aAAa,KAAK,IAAI,KAAM,eAAe,GAAI,CAAC;EAGrE,KAAK,cAAc,IAAI,aAAa;EAEpC,OAAO;CACT;;;;;;;;CASA,uBAAuB,IAAY,QAA4B;EAE7D,OADe,OAAO,eACf,EAAO,sBAAsB,EAAE,EAAE,cAAc,QAAQ,IAAI;CACpE;;;;;;;;CASA,cAAc,SAAiB,gBAAwB,WAA0B;EAC/E,OAAO,KAAK,uBAAuB,aAAa;GAC9C;GACA;EACF,CAAC;CACH;;;;;;CAOA,UAAmB;EACjB,OAAO,KAAK,UAAU;CACxB;;;;;;CAOA,WAAoB;EAClB,OAAO,KAAK,UAAU;CACxB;AACF"}
|
|
1
|
+
{"version":3,"file":"Object.js","names":[],"sources":["../../src/Game/Object.ts"],"sourcesContent":["import { Hooks, ModulesToken, RpgCommonPlayer } from \"@rpgjs/common\";\nimport { trigger, signal, type Trigger } from \"canvasengine\";\nimport { combineLatest, from, map, of, startWith, Subscription, switchMap } from \"rxjs\";\nimport { inject } from \"../core/inject\";\nimport { RpgClientEngine } from \"../RpgClientEngine\";\ntype Frame = { x: number; y: number; ts: number };\n\ntype AnimationRestoreOptions = {\n restoreAnimationName?: string;\n restoreGraphics?: any[];\n timeoutMs?: number;\n};\n\ntype FlashType = 'alpha' | 'tint' | 'both';\n\ntype FlashOptions = {\n type?: FlashType;\n duration?: number;\n cycles?: number;\n alpha?: number;\n tint?: number | string;\n};\n\ntype FlashTriggerOptions = Omit<FlashOptions, \"tint\"> & {\n tint: number;\n};\n\ntype ConfigurableTrigger<T> = Omit<Trigger<T>, \"start\"> & {\n start(config?: T): Promise<void>;\n};\n\nconst toFiniteScale = (value: unknown, fallback: number): number => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : fallback;\n }\n return fallback;\n};\n\nconst normalizeGraphicScale = (value: unknown, fallback: [number, number] = [1, 1]): [number, number] => {\n if (typeof value === \"number\" || typeof value === \"string\") {\n const scale = toFiniteScale(value, fallback[0]);\n return [scale, scale];\n }\n if (Array.isArray(value)) {\n const x = toFiniteScale(value[0], fallback[0]);\n const y = toFiniteScale(value[1] ?? value[0], x);\n return [x, y];\n }\n if (value && typeof value === \"object\") {\n const scale = value as { x?: unknown; y?: unknown };\n const x = toFiniteScale(scale.x, fallback[0]);\n const y = toFiniteScale(scale.y ?? scale.x, x);\n return [x, y];\n }\n return fallback;\n};\n\nexport const multiplyGraphicDisplayScale = (\n baseScale: unknown,\n instanceScale: unknown,\n): [number, number] => {\n const base = normalizeGraphicScale(baseScale);\n const instance = normalizeGraphicScale(instanceScale);\n return [base[0] * instance[0], base[1] * instance[1]];\n};\n\nexport const withGraphicDisplayScale = (spritesheet: any, scale: unknown): any => {\n if (!spritesheet || typeof spritesheet !== \"object\") return spritesheet;\n if (scale === undefined || scale === null) return spritesheet;\n return {\n ...spritesheet,\n displayScale: multiplyGraphicDisplayScale(spritesheet.displayScale, scale),\n };\n};\n\nexport const appendFramePayload = (current: unknown, items: unknown): Frame[] => {\n const frameItems = Array.isArray(items) ? items : items ? [items] : [];\n const nextFrames = frameItems.flatMap((item): Frame[] =>\n Array.isArray(item) ? item : [item as Frame]\n );\n const currentFrames = Array.isArray(current) ? current as Frame[] : [];\n return currentFrames.concat(nextFrames);\n};\n\nexport const getFrameTimestamp = (frame: Frame): number => {\n const timestamp = Number(frame.ts);\n return Number.isFinite(timestamp) ? timestamp : 0;\n};\n\nexport const mergeFreshFramePayload = (\n current: unknown,\n items: unknown,\n lastAppliedFrameTs = 0,\n): Frame[] => {\n return appendFramePayload(current, items)\n .filter((frame) => {\n const timestamp = getFrameTimestamp(frame);\n return timestamp === 0 || timestamp > lastAppliedFrameTs;\n })\n .sort((a, b) => getFrameTimestamp(a) - getFrameTimestamp(b));\n};\n\nexport abstract class RpgClientObject extends RpgCommonPlayer {\n abstract _type: string;\n emitParticleTrigger = trigger();\n particleName = signal(\"\");\n animationCurrentIndex = signal(0);\n animationIsPlaying = signal(false);\n _param = signal({});\n frames: Frame[] = [];\n graphicsSignals = signal<any[]>([]);\n flashTrigger: ConfigurableTrigger<FlashTriggerOptions> = trigger<FlashTriggerOptions>();\n private lastAppliedFrameTs = 0;\n private animationRestoreState?: {\n animationName: string;\n graphics: any[];\n };\n\n constructor() {\n super();\n const engine = this.engine;\n this.hooks.callHooks(\"client-sprite-onInit\", this).subscribe();\n\n this._frames.observable.subscribe(({ items }) => {\n if (!this.id) return;\n //if (this.id == this.engine.playerIdSignal()!) return;\n this.frames = mergeFreshFramePayload(\n this.frames,\n items,\n this.lastAppliedFrameTs,\n );\n });\n\n const graphics$ = this.graphics.observable.pipe(map(({ items }) => items));\n const graphicScale$ = this._graphicScale.observable.pipe(\n startWith({ value: this._graphicScale() }),\n map((payload: any) => payload?.value ?? payload),\n );\n\n combineLatest([graphics$, graphicScale$])\n .pipe(\n switchMap(([graphics, scale]) => {\n const graphicRefs = Array.isArray(graphics) ? graphics : [];\n if (graphicRefs.length === 0) return of([]);\n return from(Promise.all(graphicRefs.map(async (graphic) => {\n const spritesheet = await engine.getSpriteSheet(graphic);\n return withGraphicDisplayScale(spritesheet, scale);\n })));\n })\n )\n .subscribe((sheets) => { \n this.graphicsSignals.set(sheets);\n });\n\n engine.tick\n .pipe\n //throttleTime(10)\n ()\n .subscribe(() => {\n const frame = this.frames.shift();\n if (frame) {\n if (typeof frame.x !== \"number\" || typeof frame.y !== \"number\") return;\n const frameTs = this.getFrameTimestamp(frame);\n if (frameTs > 0 && frameTs <= this.lastAppliedFrameTs) return;\n engine.scene.setBodyPosition(\n this.id,\n frame.x,\n frame.y,\n \"top-left\"\n );\n if (frameTs > this.lastAppliedFrameTs) {\n this.lastAppliedFrameTs = frameTs;\n }\n }\n });\n }\n\n private getFrameTimestamp(frame: Frame): number {\n return getFrameTimestamp(frame);\n }\n\n /**\n * Access the shared client hook registry.\n *\n * @returns The hook service used to register and trigger client-side hooks.\n */\n get hooks() {\n return inject<Hooks>(ModulesToken);\n }\n\n /**\n * Access the current client engine instance.\n *\n * @returns The active {@link RpgClientEngine} instance.\n */\n get engine() {\n return inject(RpgClientEngine);\n }\n\n setHitbox(width: number, height: number): void {\n if (typeof width !== \"number\" || width <= 0) {\n throw new Error(\"setHitbox: width must be a positive number\");\n }\n if (typeof height !== \"number\" || height <= 0) {\n throw new Error(\"setHitbox: height must be a positive number\");\n }\n\n this.hitbox.set({\n w: width,\n h: height,\n });\n\n const sceneMap = (this.engine as any)?.sceneMap;\n if (sceneMap && this.id) {\n sceneMap.updateHitbox?.(this.id, this.x(), this.y(), width, height);\n }\n }\n\n private animationSubscription?: Subscription;\n private animationResetTimeout?: ReturnType<typeof setTimeout>;\n private animationWaitResolve?: () => void;\n\n private clearAnimationControls() {\n if (this.animationSubscription) {\n this.animationSubscription.unsubscribe();\n this.animationSubscription = undefined;\n }\n if (this.animationResetTimeout) {\n clearTimeout(this.animationResetTimeout);\n this.animationResetTimeout = undefined;\n }\n }\n\n private resolveAnimationWait() {\n const resolve = this.animationWaitResolve;\n this.animationWaitResolve = undefined;\n resolve?.();\n }\n\n private finishTemporaryAnimation() {\n const restoreState = this.animationRestoreState;\n this.clearAnimationControls();\n this.animationCurrentIndex.set(0);\n this.animationRestoreState = undefined;\n this.animationIsPlaying.set(false);\n if (restoreState) {\n this.animationName.set(restoreState.animationName);\n this.graphics.set([...restoreState.graphics]);\n }\n this.resolveAnimationWait();\n }\n\n /**\n * Trigger a flash animation on this sprite\n * \n * This method triggers a flash effect using CanvasEngine's flash directive.\n * The flash can be configured with various options including type (alpha, tint, or both),\n * duration, cycles, and color.\n * \n * ## Design\n * \n * The flash uses a trigger system that is connected to the flash directive in the\n * character component. This allows for flexible configuration and can be triggered\n * from both server events and client-side code.\n * \n * @param options - Flash configuration options\n * @param options.type - Type of flash effect: 'alpha' (opacity), 'tint' (color), or 'both' (default: 'alpha')\n * @param options.duration - Duration of the flash animation in milliseconds (default: 300)\n * @param options.cycles - Number of flash cycles (flash on/off) (default: 1)\n * @param options.alpha - Alpha value when flashing, from 0 to 1 (default: 0.3)\n * @param options.tint - Tint color when flashing as hex value or color name (default: 0xffffff - white)\n * \n * @example\n * ```ts\n * // Simple flash with default settings (alpha flash)\n * player.flash();\n * \n * // Flash with red tint\n * player.flash({ type: 'tint', tint: 0xff0000 });\n * \n * // Flash with both alpha and tint\n * player.flash({ \n * type: 'both', \n * alpha: 0.5, \n * tint: 0xff0000,\n * duration: 200,\n * cycles: 2\n * });\n * \n * // Quick damage flash\n * player.flash({ \n * type: 'tint', \n * tint: 0xff0000, \n * duration: 150,\n * cycles: 1\n * });\n * ```\n */\n flash(options?: FlashOptions): void {\n const flashOptions = {\n type: options?.type || 'alpha',\n duration: options?.duration ?? 300,\n cycles: options?.cycles ?? 1,\n alpha: options?.alpha ?? 0.3,\n tint: options?.tint ?? 0xffffff,\n };\n \n // Convert color name to hex if needed\n let tintValue = flashOptions.tint;\n if (typeof tintValue === 'string') {\n // Common color name to hex mapping\n const colorMap: Record<string, number> = {\n 'white': 0xffffff,\n 'red': 0xff0000,\n 'green': 0x00ff00,\n 'blue': 0x0000ff,\n 'yellow': 0xffff00,\n 'cyan': 0x00ffff,\n 'magenta': 0xff00ff,\n 'black': 0x000000,\n };\n tintValue = colorMap[tintValue.toLowerCase()] ?? 0xffffff;\n }\n \n this.flashTrigger.start({\n ...flashOptions,\n tint: tintValue,\n });\n }\n\n /**\n * Reset animation state when animation changes externally\n *\n * This method should be called when the animation changes due to movement\n * or other external factors to ensure the animation system doesn't get stuck\n *\n * @example\n * ```ts\n * // Reset when player starts moving\n * player.resetAnimationState();\n * ```\n */\n resetAnimationState() {\n if (this.animationRestoreState) {\n this.finishTemporaryAnimation();\n return;\n }\n this.animationIsPlaying.set(false);\n this.animationCurrentIndex.set(0);\n this.clearAnimationControls();\n this.resolveAnimationWait();\n }\n\n /**\n * Set a custom animation for a specific number of times\n *\n * Plays a custom animation for the specified number of repetitions.\n * The animation system prevents overlapping animations and automatically\n * returns to the previous animation when complete.\n *\n * @param animationName - Name of the animation to play\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation 3 times\n * await player.setAnimation('attack', 3);\n *\n * // Play continuous spell animation\n * player.setAnimation('spell');\n * ```\n */\n setAnimation(animationName: string, nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n /**\n * Set a custom animation with temporary graphic change\n *\n * Plays a custom animation for the specified number of repetitions and temporarily\n * changes the player's graphic (sprite sheet) during the animation. The graphic\n * is automatically reset when the animation finishes.\n *\n * @param animationName - Name of the animation to play\n * @param graphic - The graphic(s) to temporarily use during the animation\n * @param nbTimes - Number of times to repeat the animation (default: Infinity for continuous)\n * @param options - Restore and timeout options\n * @returns A promise resolved when a finite animation finishes, is interrupted, or times out\n *\n * @example\n * ```ts\n * // Play attack animation with temporary graphic change\n * await player.setAnimation('attack', 'hero_attack', 3);\n * ```\n */\n setAnimation(animationName: string, graphic?: string | string[], nbTimes?: number, options?: AnimationRestoreOptions): Promise<void>;\n setAnimation(\n animationName: string,\n graphicOrNbTimes?: string | string[] | number,\n nbTimesOrOptions?: number | AnimationRestoreOptions,\n options?: AnimationRestoreOptions\n ): Promise<void> {\n let graphic: string | string[] | undefined;\n let finalNbTimes: number = Infinity;\n let restoreOptions: AnimationRestoreOptions | undefined = options;\n\n // Handle overloads\n if (typeof graphicOrNbTimes === 'number') {\n // setAnimation(animationName, nbTimes)\n finalNbTimes = graphicOrNbTimes;\n restoreOptions = typeof nbTimesOrOptions === 'object' ? nbTimesOrOptions : options;\n } else if (graphicOrNbTimes !== undefined) {\n // setAnimation(animationName, graphic, nbTimes)\n graphic = graphicOrNbTimes;\n if (typeof nbTimesOrOptions === 'number') {\n finalNbTimes = nbTimesOrOptions;\n } else {\n finalNbTimes = Infinity;\n restoreOptions = nbTimesOrOptions ?? options;\n }\n } else {\n // setAnimation(animationName) - nbTimes remains Infinity\n finalNbTimes = Infinity;\n }\n\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n\n const waitPromise =\n finalNbTimes === Infinity\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n this.animationWaitResolve = resolve;\n });\n\n this.animationIsPlaying.set(true);\n const previousAnimationName =\n restoreOptions?.restoreAnimationName ?? this.animationName();\n const previousGraphics = restoreOptions?.restoreGraphics\n ? [...restoreOptions.restoreGraphics]\n : [...this.graphics()];\n this.animationRestoreState = {\n animationName: previousAnimationName,\n graphics: previousGraphics,\n };\n this.animationCurrentIndex.set(0);\n\n // Temporarily change graphic if provided\n if (graphic !== undefined) {\n if (Array.isArray(graphic)) {\n this.graphics.set(graphic);\n } else {\n this.graphics.set([graphic]);\n }\n }\n\n this.clearAnimationControls();\n\n this.animationSubscription =\n this.animationCurrentIndex.observable.subscribe((index) => {\n if (index >= finalNbTimes) {\n this.finishTemporaryAnimation();\n }\n });\n\n if (finalNbTimes !== Infinity) {\n this.animationResetTimeout = setTimeout(() => {\n if (this.animationIsPlaying()) {\n this.finishTemporaryAnimation();\n }\n }, restoreOptions?.timeoutMs ?? Math.max(1000, finalNbTimes * 1000));\n }\n\n this.animationName.set(animationName);\n\n return waitPromise;\n }\n\n /**\n * Display a registered component animation effect on this object.\n *\n * @param id - Identifier of the component animation to play.\n * @param params - Parameters forwarded to the animation effect.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showComponentAnimation(id: string, params: any): Promise<void> {\n const engine = inject(RpgClientEngine);\n return engine.getComponentAnimation(id).displayEffect(params, this);\n }\n\n /**\n * Display a registered spritesheet animation effect on this object.\n *\n * @param graphic - Identifier of the spritesheet to use.\n * @param animationName - Name of the animation inside the spritesheet.\n * @returns A promise resolved when the animation component calls `onFinish`.\n */\n showAnimation(graphic: string, animationName: string = 'default'): Promise<void> {\n return this.showComponentAnimation('animation', {\n graphic,\n animationName,\n });\n }\n \n /**\n * Check whether this client object represents an event.\n *\n * @returns `true` if the object type is `event`, otherwise `false`.\n */\n isEvent(): boolean {\n return this._type === 'event';\n }\n\n /**\n * Check whether this client object represents a player.\n *\n * @returns `true` if the object type is `player`, otherwise `false`.\n */\n isPlayer(): boolean {\n return this._type === 'player';\n }\n}\n"],"mappings":";;;;;;AA+BA,IAAM,iBAAiB,OAAgB,aAA6B;CAClE,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG,OAAO;CAChE,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,GAAG;EAC7C,MAAM,SAAS,OAAO,KAAK;EAC3B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;CAC5C;CACA,OAAO;AACT;AAEA,IAAM,yBAAyB,OAAgB,WAA6B,CAAC,GAAG,CAAC,MAAwB;CACvG,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,UAAU;EAC1D,MAAM,QAAQ,cAAc,OAAO,SAAS,EAAE;EAC9C,OAAO,CAAC,OAAO,KAAK;CACtB;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,IAAI,cAAc,MAAM,IAAI,SAAS,EAAE;EAE7C,OAAO,CAAC,GADE,cAAc,MAAM,MAAM,MAAM,IAAI,CACnC,CAAC;CACd;CACA,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,QAAQ;EACd,MAAM,IAAI,cAAc,MAAM,GAAG,SAAS,EAAE;EAE5C,OAAO,CAAC,GADE,cAAc,MAAM,KAAK,MAAM,GAAG,CACjC,CAAC;CACd;CACA,OAAO;AACT;AAEA,IAAa,+BACX,WACA,kBACqB;CACrB,MAAM,OAAO,sBAAsB,SAAS;CAC5C,MAAM,WAAW,sBAAsB,aAAa;CACpD,OAAO,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,EAAE;AACtD;AAEA,IAAa,2BAA2B,aAAkB,UAAwB;CAChF,IAAI,CAAC,eAAe,OAAO,gBA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,IAAI,KAAK,mBAAmB,GAC1B,KAAK,yBAAyB;EAElC,GAAG,gBAAgB,aAAa,KAAK,IAAI,KAAM,eAAe,GAAI,CAAC;EAGrE,KAAK,cAAc,IAAI,aAAa;EAEpC,OAAO;CACT;;;;;;;;CASA,uBAAuB,IAAY,QAA4B;EAE7D,OADe,OAAO,eACf,EAAO,sBAAsB,EAAE,EAAE,cAAc,QAAQ,IAAI;CACpE;;;;;;;;CASA,cAAc,SAAiB,gBAAwB,WAA0B;EAC/E,OAAO,KAAK,uBAAuB,aAAa;GAC9C;GACA;EACF,CAAC;CACH;;;;;;CAOA,UAAmB;EACjB,OAAO,KAAK,UAAU;CACxB;;;;;;CAOA,WAAoB;EAClB,OAAO,KAAK,UAAU;CACxB;AACF"}
|
|
@@ -697,6 +697,8 @@ export declare class RpgClientEngine<T = any> {
|
|
|
697
697
|
private flushPendingMovePath;
|
|
698
698
|
private applyPredictedMovementInput;
|
|
699
699
|
private getLocalPlayerState;
|
|
700
|
+
private resolveHitboxDimension;
|
|
701
|
+
private resolveObjectHitboxSize;
|
|
700
702
|
private applyAuthoritativeState;
|
|
701
703
|
private initializePredictionController;
|
|
702
704
|
getCurrentPlayer(): import('.').RpgClientPlayer;
|
package/dist/RpgClientEngine.js
CHANGED
|
@@ -24,6 +24,7 @@ import { ProjectileManager } from "./Game/ProjectileManager.js";
|
|
|
24
24
|
import { ClientVisualRegistry } from "./Game/ClientVisuals.js";
|
|
25
25
|
import { createClientPointerContext } from "./services/pointerContext.js";
|
|
26
26
|
import { RpgClientInteractions } from "./services/interactions.js";
|
|
27
|
+
import { applySyncedHitboxPayload } from "./utils/syncHitbox.js";
|
|
27
28
|
import { EventComponentResolverRegistry } from "./Game/EventComponentResolver.js";
|
|
28
29
|
import { RpgClientBuiltinI18n } from "./i18n.js";
|
|
29
30
|
import { Howl, bootstrapCanvas, signal, trigger } from "canvasengine";
|
|
@@ -686,6 +687,7 @@ var RpgClientEngine = class {
|
|
|
686
687
|
const normalizedAck = ack && typeof ack.frame === "number" ? this.normalizeAckWithSyncState(ack, data) : void 0;
|
|
687
688
|
const payload = this.prepareSyncPayload(data);
|
|
688
689
|
load(this.sceneMap, payload, true);
|
|
690
|
+
applySyncedHitboxPayload(this.sceneMap, payload);
|
|
689
691
|
if (normalizedAck) this.applyServerAck(normalizedAck);
|
|
690
692
|
for (const playerId in payload.players ?? {}) {
|
|
691
693
|
const player = payload.players[playerId];
|
|
@@ -1603,12 +1605,21 @@ var RpgClientEngine = class {
|
|
|
1603
1605
|
direction: currentPlayer.direction()
|
|
1604
1606
|
};
|
|
1605
1607
|
}
|
|
1608
|
+
resolveHitboxDimension(source, fallback) {
|
|
1609
|
+
const value = typeof source === "string" ? Number(source) : source;
|
|
1610
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1611
|
+
}
|
|
1612
|
+
resolveObjectHitboxSize(object) {
|
|
1613
|
+
const hitbox = typeof object?.hitbox === "function" ? object.hitbox() : object?.hitbox;
|
|
1614
|
+
return {
|
|
1615
|
+
width: this.resolveHitboxDimension(hitbox?.w ?? hitbox?.width, 0),
|
|
1616
|
+
height: this.resolveHitboxDimension(hitbox?.h ?? hitbox?.height, 0)
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1606
1619
|
applyAuthoritativeState(state) {
|
|
1607
1620
|
const player = this.sceneMap?.getCurrentPlayer();
|
|
1608
1621
|
if (!player) return;
|
|
1609
|
-
const
|
|
1610
|
-
const width = hitbox?.w ?? 0;
|
|
1611
|
-
const height = hitbox?.h ?? 0;
|
|
1622
|
+
const { width, height } = this.resolveObjectHitboxSize(player);
|
|
1612
1623
|
if (!this.sceneMap.updateHitbox(player.id, state.x, state.y, width, height)) this.sceneMap.setBodyPosition(player.id, state.x, state.y, "top-left");
|
|
1613
1624
|
player.x.set(Math.round(state.x));
|
|
1614
1625
|
player.y.set(Math.round(state.y));
|
|
@@ -1795,9 +1806,7 @@ var RpgClientEngine = class {
|
|
|
1795
1806
|
const player = this.getCurrentPlayer();
|
|
1796
1807
|
const myId = this.playerIdSignal();
|
|
1797
1808
|
if (!player || !myId) return;
|
|
1798
|
-
const
|
|
1799
|
-
const width = hitbox?.w ?? 0;
|
|
1800
|
-
const height = hitbox?.h ?? 0;
|
|
1809
|
+
const { width, height } = this.resolveObjectHitboxSize(player);
|
|
1801
1810
|
if (!this.sceneMap.updateHitbox(myId, ack.x, ack.y, width, height)) this.sceneMap.setBodyPosition(myId, ack.x, ack.y, "top-left");
|
|
1802
1811
|
player.x.set(Math.round(ack.x));
|
|
1803
1812
|
player.y.set(Math.round(ack.y));
|