@rpgjs/server 5.0.0-alpha.8 → 5.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Gui/DialogGui.d.ts +5 -0
- package/dist/Gui/GameoverGui.d.ts +23 -0
- package/dist/Gui/Gui.d.ts +6 -0
- package/dist/Gui/MenuGui.d.ts +22 -3
- package/dist/Gui/NotificationGui.d.ts +1 -2
- package/dist/Gui/SaveLoadGui.d.ts +13 -0
- package/dist/Gui/ShopGui.d.ts +28 -3
- package/dist/Gui/TitleGui.d.ts +23 -0
- package/dist/Gui/index.d.ts +10 -1
- package/dist/Player/BattleManager.d.ts +44 -32
- package/dist/Player/ClassManager.d.ts +24 -4
- package/dist/Player/ComponentManager.d.ts +100 -7
- package/dist/Player/Components.d.ts +345 -0
- package/dist/Player/EffectManager.d.ts +50 -4
- package/dist/Player/ElementManager.d.ts +77 -4
- package/dist/Player/GoldManager.d.ts +1 -1
- package/dist/Player/GuiManager.d.ts +233 -5
- package/dist/Player/ItemFixture.d.ts +1 -1
- package/dist/Player/ItemManager.d.ts +431 -4
- package/dist/Player/MoveManager.d.ts +301 -34
- package/dist/Player/ParameterManager.d.ts +364 -28
- package/dist/Player/Player.d.ts +558 -14
- package/dist/Player/SkillManager.d.ts +187 -13
- package/dist/Player/StateManager.d.ts +75 -4
- package/dist/Player/VariableManager.d.ts +62 -4
- package/dist/RpgServer.d.ts +278 -63
- package/dist/RpgServerEngine.d.ts +2 -1
- package/dist/decorators/event.d.ts +46 -0
- package/dist/decorators/map.d.ts +299 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +17920 -29866
- package/dist/index.js.map +1 -1
- package/dist/logs/log.d.ts +2 -3
- package/dist/module-CaCW1SDh.js +11018 -0
- package/dist/module-CaCW1SDh.js.map +1 -0
- package/dist/module.d.ts +43 -1
- package/dist/node/connection.d.ts +51 -0
- package/dist/node/index.d.ts +5 -0
- package/dist/node/index.js +551 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/map.d.ts +16 -0
- package/dist/node/room.d.ts +21 -0
- package/dist/node/transport.d.ts +28 -0
- package/dist/node/types.d.ts +47 -0
- package/dist/presets/index.d.ts +0 -9
- package/dist/rooms/BaseRoom.d.ts +132 -0
- package/dist/rooms/lobby.d.ts +10 -2
- package/dist/rooms/map.d.ts +1359 -32
- package/dist/services/save.d.ts +43 -0
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/localStorage.d.ts +23 -0
- package/package.json +25 -10
- package/src/Gui/DialogGui.ts +19 -4
- package/src/Gui/GameoverGui.ts +39 -0
- package/src/Gui/Gui.ts +23 -1
- package/src/Gui/MenuGui.ts +155 -6
- package/src/Gui/NotificationGui.ts +1 -2
- package/src/Gui/SaveLoadGui.ts +60 -0
- package/src/Gui/ShopGui.ts +146 -16
- package/src/Gui/TitleGui.ts +39 -0
- package/src/Gui/index.ts +15 -2
- package/src/Player/BattleManager.ts +39 -56
- package/src/Player/ClassManager.ts +82 -74
- package/src/Player/ComponentManager.ts +401 -37
- package/src/Player/Components.ts +380 -0
- package/src/Player/EffectManager.ts +50 -96
- package/src/Player/ElementManager.ts +74 -152
- package/src/Player/GuiManager.ts +284 -149
- package/src/Player/ItemManager.ts +747 -341
- package/src/Player/MoveManager.ts +1532 -750
- package/src/Player/ParameterManager.ts +636 -106
- package/src/Player/Player.ts +1273 -79
- package/src/Player/SkillManager.ts +558 -197
- package/src/Player/StateManager.ts +131 -258
- package/src/Player/VariableManager.ts +85 -157
- package/src/RpgServer.ts +293 -62
- package/src/decorators/event.ts +61 -0
- package/src/decorators/map.ts +343 -0
- package/src/index.ts +11 -1
- package/src/logs/log.ts +10 -3
- package/src/module.ts +126 -3
- package/src/node/connection.ts +254 -0
- package/src/node/index.ts +22 -0
- package/src/node/map.ts +328 -0
- package/src/node/room.ts +63 -0
- package/src/node/transport.ts +532 -0
- package/src/node/types.ts +61 -0
- package/src/presets/index.ts +1 -10
- package/src/rooms/BaseRoom.ts +232 -0
- package/src/rooms/lobby.ts +25 -7
- package/src/rooms/map.ts +2682 -206
- package/src/services/save.ts +147 -0
- package/src/storage/index.ts +1 -0
- package/src/storage/localStorage.ts +76 -0
- package/tests/battle.spec.ts +375 -0
- package/tests/change-map.spec.ts +72 -0
- package/tests/class.spec.ts +274 -0
- package/tests/custom-websocket.spec.ts +127 -0
- package/tests/effect.spec.ts +219 -0
- package/tests/element.spec.ts +221 -0
- package/tests/event.spec.ts +80 -0
- package/tests/gold.spec.ts +99 -0
- package/tests/item.spec.ts +609 -0
- package/tests/module.spec.ts +38 -0
- package/tests/move.spec.ts +601 -0
- package/tests/node-transport.spec.ts +223 -0
- package/tests/player-param.spec.ts +45 -0
- package/tests/prediction-reconciliation.spec.ts +182 -0
- package/tests/random-move.spec.ts +65 -0
- package/tests/skill.spec.ts +658 -0
- package/tests/state.spec.ts +467 -0
- package/tests/variable.spec.ts +185 -0
- package/tests/world-maps.spec.ts +896 -0
- package/vite.config.ts +36 -3
- package/dist/Player/Event.d.ts +0 -0
- package/src/Player/Event.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module-CaCW1SDh.js","names":["isFunction","isFunction","context","isFunction","Symbol_observable","isFunction","isFunction","isFunction","isFunction","isFunction","isFunction","Symbol_observable","isFunction","isFunction","Symbol_iterator","isFunction","Symbol_observable","isFunction","process","iterator","Symbol_iterator","isFunction","isArray","isArray","isFunction","__defProp","__name","BehaviorSubject2","BehaviorSubject3","__defProp","__name","isFunction","__name","isSignal2","inject"],"sources":["../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isFunction.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/Subscription.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/config.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/noop.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/NotificationFactories.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/errorContext.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/Subscriber.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/symbol/observable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/identity.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/pipe.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/Observable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/lift.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/Subject.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/BehaviorSubject.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isScheduler.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/args.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isPromise.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/symbol/iterator.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isIterable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/observeOn.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/observable/from.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/map.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/argsArgArrayOrObject.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/util/createObject.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/observable/combineLatest.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/mergeInternals.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/filter.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/scanInternals.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/reduce.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/toArray.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/finalize.js","../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/esm5/internal/operators/share.js","../../../node_modules/.pnpm/@signe+reactive@2.8.3/node_modules/@signe/reactive/dist/index.js","../../../node_modules/.pnpm/@signe+sync@2.8.3/node_modules/@signe/sync/dist/chunk-7QVYU63E.js","../../../node_modules/.pnpm/@signe+sync@2.8.3/node_modules/@signe/sync/dist/index.js","../../common/src/database/Item.ts","../../common/src/database/Skill.ts","../../common/src/Player.ts","../../common/src/Shape.ts","../../physic/src/core/math/Vector2.ts","../../physic/src/core/math/AABB.ts","../../physic/src/core/types.ts","../../physic/src/utils/uuid.ts","../../physic/src/physics/Entity.ts","../../physic/src/physics/integrator.ts","../../physic/src/collision/AABBCollider.ts","../../physic/src/collision/CircleCollider.ts","../../physic/src/collision/CapsuleCollider.ts","../../physic/src/collision/PolygonCollider.ts","../../physic/src/collision/detector.ts","../../physic/src/collision/spatial-hash.ts","../../physic/src/collision/Ray.ts","../../physic/src/collision/raycast.ts","../../physic/src/collision/resolver.ts","../../physic/src/collision/sweep.ts","../../physic/src/world/events.ts","../../physic/src/world/World.ts","../../physic/src/region/Region.ts","../../physic/src/region/RegionManager.ts","../../physic/src/movement/adapters/EntityMovementBody.ts","../../physic/src/movement/MovementManager.ts","../../physic/src/api/ZoneManager.ts","../../physic/src/api/PhysicsEngine.ts","../../physic/src/movement/strategies/Dash.ts","../../physic/src/movement/strategies/IceMovement.ts","../../physic/src/movement/strategies/Knockback.ts","../../physic/src/movement/strategies/LinearRepulsion.ts","../../physic/src/movement/strategies/Oscillate.ts","../../physic/src/movement/strategies/PathFollow.ts","../../physic/src/movement/strategies/ProjectileMovement.ts","../../physic/src/movement/strategies/SeekAvoid.ts","../../common/src/movement/MovementManager.ts","../../common/src/rooms/Map.ts","../../common/src/rooms/WorldMaps.ts","../../common/src/modules.ts","../../common/src/Utils.ts","../../common/src/PrebuiltGui.ts","../../common/src/PerlinNoise.ts","../../common/src/Presets.ts","../../../node_modules/.pnpm/@signe+di@2.9.0/node_modules/@signe/di/dist/index.js","../src/core/inject.ts","../src/core/context.ts","../src/node/map.ts","../src/module.ts"],"sourcesContent":["/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n//# sourceMappingURL=isFunction.js.map","export function createErrorClass(createImpl) {\n var _super = function (instance) {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n var ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n//# sourceMappingURL=createErrorClass.js.map","import { createErrorClass } from './createErrorClass';\nexport var UnsubscriptionError = createErrorClass(function (_super) {\n return function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ')\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n };\n});\n//# sourceMappingURL=UnsubscriptionError.js.map","export function arrRemove(arr, item) {\n if (arr) {\n var index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrRemove.js.map","import { __read, __spreadArray, __values } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nvar Subscription = (function () {\n function Subscription(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n Subscription.prototype.unsubscribe = function () {\n var e_1, _a, e_2, _b;\n var errors;\n if (!this.closed) {\n this.closed = true;\n var _parentage = this._parentage;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n try {\n for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {\n var parent_1 = _parentage_1_1.value;\n parent_1.remove(this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n var initialFinalizer = this.initialTeardown;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n var _finalizers = this._finalizers;\n if (_finalizers) {\n this._finalizers = null;\n try {\n for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {\n var finalizer = _finalizers_1_1.value;\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n };\n Subscription.prototype.add = function (teardown) {\n var _a;\n if (teardown && teardown !== this) {\n if (this.closed) {\n execFinalizer(teardown);\n }\n else {\n if (teardown instanceof Subscription) {\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);\n }\n }\n };\n Subscription.prototype._hasParent = function (parent) {\n var _parentage = this._parentage;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n };\n Subscription.prototype._addParent = function (parent) {\n var _parentage = this._parentage;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n };\n Subscription.prototype._removeParent = function (parent) {\n var _parentage = this._parentage;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n };\n Subscription.prototype.remove = function (teardown) {\n var _finalizers = this._finalizers;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n };\n Subscription.EMPTY = (function () {\n var empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n return Subscription;\n}());\nexport { Subscription };\nexport var EMPTY_SUBSCRIPTION = Subscription.EMPTY;\nexport function isSubscription(value) {\n return (value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));\n}\nfunction execFinalizer(finalizer) {\n if (isFunction(finalizer)) {\n finalizer();\n }\n else {\n finalizer.unsubscribe();\n }\n}\n//# sourceMappingURL=Subscription.js.map","export var config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n//# sourceMappingURL=config.js.map","import { __read, __spreadArray } from \"tslib\";\nexport var timeoutProvider = {\n setTimeout: function (handler, timeout) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var delegate = timeoutProvider.delegate;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));\n }\n return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));\n },\n clearTimeout: function (handle) {\n var delegate = timeoutProvider.delegate;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n//# sourceMappingURL=timeoutProvider.js.map","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(function () {\n var onUnhandledError = config.onUnhandledError;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n//# sourceMappingURL=reportUnhandledError.js.map","export function noop() { }\n//# sourceMappingURL=noop.js.map","export var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();\nexport function errorNotification(error) {\n return createNotification('E', undefined, error);\n}\nexport function nextNotification(value) {\n return createNotification('N', value, undefined);\n}\nexport function createNotification(kind, value, error) {\n return {\n kind: kind,\n value: value,\n error: error,\n };\n}\n//# sourceMappingURL=NotificationFactories.js.map","import { config } from '../config';\nvar context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n var isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n var _a = context, errorThrown = _a.errorThrown, error = _a.error;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n }\n else {\n cb();\n }\n}\nexport function captureError(err) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n//# sourceMappingURL=errorContext.js.map","import { __extends } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\nvar Subscriber = (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destination) {\n var _this = _super.call(this) || this;\n _this.isStopped = false;\n if (destination) {\n _this.destination = destination;\n if (isSubscription(destination)) {\n destination.add(_this);\n }\n }\n else {\n _this.destination = EMPTY_OBSERVER;\n }\n return _this;\n }\n Subscriber.create = function (next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n };\n Subscriber.prototype.next = function (value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (!this.closed) {\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n this.destination = null;\n }\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n };\n Subscriber.prototype._complete = function () {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nvar ConsumerObserver = (function () {\n function ConsumerObserver(partialObserver) {\n this.partialObserver = partialObserver;\n }\n ConsumerObserver.prototype.next = function (value) {\n var partialObserver = this.partialObserver;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n ConsumerObserver.prototype.error = function (err) {\n var partialObserver = this.partialObserver;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n else {\n handleUnhandledError(err);\n }\n };\n ConsumerObserver.prototype.complete = function () {\n var partialObserver = this.partialObserver;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n return ConsumerObserver;\n}());\nvar SafeSubscriber = (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n var partialObserver;\n if (isFunction(observerOrNext) || !observerOrNext) {\n partialObserver = {\n next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),\n error: error !== null && error !== void 0 ? error : undefined,\n complete: complete !== null && complete !== void 0 ? complete : undefined,\n };\n }\n else {\n var context_1;\n if (_this && config.useDeprecatedNextContext) {\n context_1 = Object.create(observerOrNext);\n context_1.unsubscribe = function () { return _this.unsubscribe(); };\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context_1),\n error: observerOrNext.error && bind(observerOrNext.error, context_1),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n _this.destination = new ConsumerObserver(partialObserver);\n return _this;\n }\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\nfunction handleUnhandledError(error) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n }\n else {\n reportUnhandledError(error);\n }\n}\nfunction defaultErrorHandler(err) {\n throw err;\n}\nfunction handleStoppedNotification(notification, subscriber) {\n var onStoppedNotification = config.onStoppedNotification;\n onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });\n}\nexport var EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n//# sourceMappingURL=Subscriber.js.map","export var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();\n//# sourceMappingURL=observable.js.map","export function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map","import { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map","import { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription } from './Subscription';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\nvar Observable = (function () {\n function Observable(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var _this = this;\n var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(function () {\n var _a = _this, operator = _a.operator, source = _a.source;\n subscriber.add(operator\n ?\n operator.call(subscriber, source)\n : source\n ?\n _this._subscribe(subscriber)\n :\n _this._trySubscribe(subscriber));\n });\n return subscriber;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscriber = new SafeSubscriber({\n next: function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n _this.subscribe(subscriber);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n var _a;\n return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;\n}\nfunction isObserver(value) {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\nfunction isSubscriber(value) {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n//# sourceMappingURL=Observable.js.map","import { isFunction } from './isFunction';\nexport function hasLift(source) {\n return isFunction(source === null || source === void 0 ? void 0 : source.lift);\n}\nexport function operate(init) {\n return function (source) {\n if (hasLift(source)) {\n return source.lift(function (liftedSource) {\n try {\n return init(liftedSource, this);\n }\n catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n//# sourceMappingURL=lift.js.map","import { __extends } from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\nvar OperatorSubscriber = (function (_super) {\n __extends(OperatorSubscriber, _super);\n function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {\n var _this = _super.call(this, destination) || this;\n _this.onFinalize = onFinalize;\n _this.shouldUnsubscribe = shouldUnsubscribe;\n _this._next = onNext\n ? function (value) {\n try {\n onNext(value);\n }\n catch (err) {\n destination.error(err);\n }\n }\n : _super.prototype._next;\n _this._error = onError\n ? function (err) {\n try {\n onError(err);\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._error;\n _this._complete = onComplete\n ? function () {\n try {\n onComplete();\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._complete;\n return _this;\n }\n OperatorSubscriber.prototype.unsubscribe = function () {\n var _a;\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n var closed_1 = this.closed;\n _super.prototype.unsubscribe.call(this);\n !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));\n }\n };\n return OperatorSubscriber;\n}(Subscriber));\nexport { OperatorSubscriber };\n//# sourceMappingURL=OperatorSubscriber.js.map","import { createErrorClass } from './createErrorClass';\nexport var ObjectUnsubscribedError = createErrorClass(function (_super) {\n return function ObjectUnsubscribedErrorImpl() {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n };\n});\n//# sourceMappingURL=ObjectUnsubscribedError.js.map","import { __extends, __values } from \"tslib\";\nimport { Observable } from './Observable';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\nvar Subject = (function (_super) {\n __extends(Subject, _super);\n function Subject() {\n var _this = _super.call(this) || this;\n _this.closed = false;\n _this.currentObservers = null;\n _this.observers = [];\n _this.isStopped = false;\n _this.hasError = false;\n _this.thrownError = null;\n return _this;\n }\n Subject.prototype.lift = function (operator) {\n var subject = new AnonymousSubject(this, this);\n subject.operator = operator;\n return subject;\n };\n Subject.prototype._throwIfClosed = function () {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n };\n Subject.prototype.next = function (value) {\n var _this = this;\n errorContext(function () {\n var e_1, _a;\n _this._throwIfClosed();\n if (!_this.isStopped) {\n if (!_this.currentObservers) {\n _this.currentObservers = Array.from(_this.observers);\n }\n try {\n for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {\n var observer = _c.value;\n observer.next(value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n });\n };\n Subject.prototype.error = function (err) {\n var _this = this;\n errorContext(function () {\n _this._throwIfClosed();\n if (!_this.isStopped) {\n _this.hasError = _this.isStopped = true;\n _this.thrownError = err;\n var observers = _this.observers;\n while (observers.length) {\n observers.shift().error(err);\n }\n }\n });\n };\n Subject.prototype.complete = function () {\n var _this = this;\n errorContext(function () {\n _this._throwIfClosed();\n if (!_this.isStopped) {\n _this.isStopped = true;\n var observers = _this.observers;\n while (observers.length) {\n observers.shift().complete();\n }\n }\n });\n };\n Subject.prototype.unsubscribe = function () {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null;\n };\n Object.defineProperty(Subject.prototype, \"observed\", {\n get: function () {\n var _a;\n return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;\n },\n enumerable: false,\n configurable: true\n });\n Subject.prototype._trySubscribe = function (subscriber) {\n this._throwIfClosed();\n return _super.prototype._trySubscribe.call(this, subscriber);\n };\n Subject.prototype._subscribe = function (subscriber) {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n };\n Subject.prototype._innerSubscribe = function (subscriber) {\n var _this = this;\n var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(function () {\n _this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n };\n Subject.prototype._checkFinalizedStatuses = function (subscriber) {\n var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;\n if (hasError) {\n subscriber.error(thrownError);\n }\n else if (isStopped) {\n subscriber.complete();\n }\n };\n Subject.prototype.asObservable = function () {\n var observable = new Observable();\n observable.source = this;\n return observable;\n };\n Subject.create = function (destination, source) {\n return new AnonymousSubject(destination, source);\n };\n return Subject;\n}(Observable));\nexport { Subject };\nvar AnonymousSubject = (function (_super) {\n __extends(AnonymousSubject, _super);\n function AnonymousSubject(destination, source) {\n var _this = _super.call(this) || this;\n _this.destination = destination;\n _this.source = source;\n return _this;\n }\n AnonymousSubject.prototype.next = function (value) {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);\n };\n AnonymousSubject.prototype.error = function (err) {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);\n };\n AnonymousSubject.prototype.complete = function () {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);\n };\n AnonymousSubject.prototype._subscribe = function (subscriber) {\n var _a, _b;\n return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;\n };\n return AnonymousSubject;\n}(Subject));\nexport { AnonymousSubject };\n//# sourceMappingURL=Subject.js.map","import { __extends } from \"tslib\";\nimport { Subject } from './Subject';\nvar BehaviorSubject = (function (_super) {\n __extends(BehaviorSubject, _super);\n function BehaviorSubject(_value) {\n var _this = _super.call(this) || this;\n _this._value = _value;\n return _this;\n }\n Object.defineProperty(BehaviorSubject.prototype, \"value\", {\n get: function () {\n return this.getValue();\n },\n enumerable: false,\n configurable: true\n });\n BehaviorSubject.prototype._subscribe = function (subscriber) {\n var subscription = _super.prototype._subscribe.call(this, subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n };\n BehaviorSubject.prototype.getValue = function () {\n var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n };\n BehaviorSubject.prototype.next = function (value) {\n _super.prototype.next.call(this, (this._value = value));\n };\n return BehaviorSubject;\n}(Subject));\nexport { BehaviorSubject };\n//# sourceMappingURL=BehaviorSubject.js.map","import { isFunction } from './isFunction';\nexport function isScheduler(value) {\n return value && isFunction(value.schedule);\n}\n//# sourceMappingURL=isScheduler.js.map","import { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\nfunction last(arr) {\n return arr[arr.length - 1];\n}\nexport function popResultSelector(args) {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\nexport function popScheduler(args) {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\nexport function popNumber(args, defaultValue) {\n return typeof last(args) === 'number' ? args.pop() : defaultValue;\n}\n//# sourceMappingURL=args.js.map","export var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n//# sourceMappingURL=isArrayLike.js.map","import { isFunction } from \"./isFunction\";\nexport function isPromise(value) {\n return isFunction(value === null || value === void 0 ? void 0 : value.then);\n}\n//# sourceMappingURL=isPromise.js.map","import { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\nexport function isInteropObservable(input) {\n return isFunction(input[Symbol_observable]);\n}\n//# sourceMappingURL=isInteropObservable.js.map","import { isFunction } from './isFunction';\nexport function isAsyncIterable(obj) {\n return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);\n}\n//# sourceMappingURL=isAsyncIterable.js.map","export function createInvalidObservableTypeError(input) {\n return new TypeError(\"You provided \" + (input !== null && typeof input === 'object' ? 'an invalid object' : \"'\" + input + \"'\") + \" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.\");\n}\n//# sourceMappingURL=throwUnobservableError.js.map","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport var iterator = getSymbolIterator();\n//# sourceMappingURL=iterator.js.map","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\nexport function isIterable(input) {\n return isFunction(input === null || input === void 0 ? void 0 : input[Symbol_iterator]);\n}\n//# sourceMappingURL=isIterable.js.map","import { __asyncGenerator, __await, __generator } from \"tslib\";\nimport { isFunction } from './isFunction';\nexport function readableStreamLikeToAsyncGenerator(readableStream) {\n return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {\n var reader, _a, value, done;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n reader = readableStream.getReader();\n _b.label = 1;\n case 1:\n _b.trys.push([1, , 9, 10]);\n _b.label = 2;\n case 2:\n if (!true) return [3, 8];\n return [4, __await(reader.read())];\n case 3:\n _a = _b.sent(), value = _a.value, done = _a.done;\n if (!done) return [3, 5];\n return [4, __await(void 0)];\n case 4: return [2, _b.sent()];\n case 5: return [4, __await(value)];\n case 6: return [4, _b.sent()];\n case 7:\n _b.sent();\n return [3, 2];\n case 8: return [3, 10];\n case 9:\n reader.releaseLock();\n return [7];\n case 10: return [2];\n }\n });\n });\n}\nexport function isReadableStreamLike(obj) {\n return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);\n}\n//# sourceMappingURL=isReadableStreamLike.js.map","import { __asyncValues, __awaiter, __generator, __values } from \"tslib\";\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function innerFrom(input) {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\nexport function fromInteropObservable(obj) {\n return new Observable(function (subscriber) {\n var obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\nexport function fromArrayLike(array) {\n return new Observable(function (subscriber) {\n for (var i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\nexport function fromPromise(promise) {\n return new Observable(function (subscriber) {\n promise\n .then(function (value) {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, function (err) { return subscriber.error(err); })\n .then(null, reportUnhandledError);\n });\n}\nexport function fromIterable(iterable) {\n return new Observable(function (subscriber) {\n var e_1, _a;\n try {\n for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {\n var value = iterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n subscriber.complete();\n });\n}\nexport function fromAsyncIterable(asyncIterable) {\n return new Observable(function (subscriber) {\n process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });\n });\n}\nexport function fromReadableStreamLike(readableStream) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\nfunction process(asyncIterable, subscriber) {\n var asyncIterable_1, asyncIterable_1_1;\n var e_2, _a;\n return __awaiter(this, void 0, void 0, function () {\n var value, e_2_1;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, 6, 11]);\n asyncIterable_1 = __asyncValues(asyncIterable);\n _b.label = 1;\n case 1: return [4, asyncIterable_1.next()];\n case 2:\n if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];\n value = asyncIterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return [2];\n }\n _b.label = 3;\n case 3: return [3, 1];\n case 4: return [3, 11];\n case 5:\n e_2_1 = _b.sent();\n e_2 = { error: e_2_1 };\n return [3, 11];\n case 6:\n _b.trys.push([6, , 9, 10]);\n if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];\n return [4, _a.call(asyncIterable_1)];\n case 7:\n _b.sent();\n _b.label = 8;\n case 8: return [3, 10];\n case 9:\n if (e_2) throw e_2.error;\n return [7];\n case 10: return [7];\n case 11:\n subscriber.complete();\n return [2];\n }\n });\n });\n}\n//# sourceMappingURL=innerFrom.js.map","export function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {\n if (delay === void 0) { delay = 0; }\n if (repeat === void 0) { repeat = false; }\n var scheduleSubscription = scheduler.schedule(function () {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n }\n else {\n this.unsubscribe();\n }\n }, delay);\n parentSubscription.add(scheduleSubscription);\n if (!repeat) {\n return scheduleSubscription;\n }\n}\n//# sourceMappingURL=executeSchedule.js.map","import { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function observeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));\n });\n}\n//# sourceMappingURL=observeOn.js.map","import { operate } from '../util/lift';\nexport function subscribeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));\n });\n}\n//# sourceMappingURL=subscribeOn.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function scheduleObservable(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=scheduleObservable.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function schedulePromise(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=schedulePromise.js.map","import { Observable } from '../Observable';\nexport function scheduleArray(input, scheduler) {\n return new Observable(function (subscriber) {\n var i = 0;\n return scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n }\n else {\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n//# sourceMappingURL=scheduleArray.js.map","import { Observable } from '../Observable';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleIterable(input, scheduler) {\n return new Observable(function (subscriber) {\n var iterator;\n executeSchedule(subscriber, scheduler, function () {\n iterator = input[Symbol_iterator]();\n executeSchedule(subscriber, scheduler, function () {\n var _a;\n var value;\n var done;\n try {\n (_a = iterator.next(), value = _a.value, done = _a.done);\n }\n catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n }\n else {\n subscriber.next(value);\n }\n }, 0, true);\n });\n return function () { return isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); };\n });\n}\n//# sourceMappingURL=scheduleIterable.js.map","import { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleAsyncIterable(input, scheduler) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(function (subscriber) {\n executeSchedule(subscriber, scheduler, function () {\n var iterator = input[Symbol.asyncIterator]();\n executeSchedule(subscriber, scheduler, function () {\n iterator.next().then(function (result) {\n if (result.done) {\n subscriber.complete();\n }\n else {\n subscriber.next(result.value);\n }\n });\n }, 0, true);\n });\n });\n}\n//# sourceMappingURL=scheduleAsyncIterable.js.map","import { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nexport function scheduleReadableStreamLike(input, scheduler) {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n//# sourceMappingURL=scheduleReadableStreamLike.js.map","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\nexport function scheduled(input, scheduler) {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n//# sourceMappingURL=scheduled.js.map","import { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\nexport function from(input, scheduler) {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n//# sourceMappingURL=from.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function map(project, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n subscriber.next(project.call(thisArg, value, index++));\n }));\n });\n}\n//# sourceMappingURL=map.js.map","import { __read, __spreadArray } from \"tslib\";\nimport { map } from \"../operators/map\";\nvar isArray = Array.isArray;\nfunction callOrApply(fn, args) {\n return isArray(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);\n}\nexport function mapOneOrManyArgs(fn) {\n return map(function (args) { return callOrApply(fn, args); });\n}\n//# sourceMappingURL=mapOneOrManyArgs.js.map","var isArray = Array.isArray;\nvar getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;\nexport function argsArgArrayOrObject(args) {\n if (args.length === 1) {\n var first_1 = args[0];\n if (isArray(first_1)) {\n return { args: first_1, keys: null };\n }\n if (isPOJO(first_1)) {\n var keys = getKeys(first_1);\n return {\n args: keys.map(function (key) { return first_1[key]; }),\n keys: keys,\n };\n }\n }\n return { args: args, keys: null };\n}\nfunction isPOJO(obj) {\n return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;\n}\n//# sourceMappingURL=argsArgArrayOrObject.js.map","export function createObject(keys, values) {\n return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});\n}\n//# sourceMappingURL=createObject.js.map","import { Observable } from '../Observable';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { from } from './from';\nimport { identity } from '../util/identity';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { popResultSelector, popScheduler } from '../util/args';\nimport { createObject } from '../util/createObject';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function combineLatest() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var scheduler = popScheduler(args);\n var resultSelector = popResultSelector(args);\n var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;\n if (observables.length === 0) {\n return from([], scheduler);\n }\n var result = new Observable(combineLatestInit(observables, scheduler, keys\n ?\n function (values) { return createObject(keys, values); }\n :\n identity));\n return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;\n}\nexport function combineLatestInit(observables, scheduler, valueTransform) {\n if (valueTransform === void 0) { valueTransform = identity; }\n return function (subscriber) {\n maybeSchedule(scheduler, function () {\n var length = observables.length;\n var values = new Array(length);\n var active = length;\n var remainingFirstValues = length;\n var _loop_1 = function (i) {\n maybeSchedule(scheduler, function () {\n var source = from(observables[i], scheduler);\n var hasFirstValue = false;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n values[i] = value;\n if (!hasFirstValue) {\n hasFirstValue = true;\n remainingFirstValues--;\n }\n if (!remainingFirstValues) {\n subscriber.next(valueTransform(values.slice()));\n }\n }, function () {\n if (!--active) {\n subscriber.complete();\n }\n }));\n }, subscriber);\n };\n for (var i = 0; i < length; i++) {\n _loop_1(i);\n }\n }, subscriber);\n };\n}\nfunction maybeSchedule(scheduler, execute, subscription) {\n if (scheduler) {\n executeSchedule(subscription, scheduler, execute);\n }\n else {\n execute();\n }\n}\n//# sourceMappingURL=combineLatest.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {\n var buffer = [];\n var active = 0;\n var index = 0;\n var isComplete = false;\n var checkComplete = function () {\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };\n var doInnerSub = function (value) {\n expand && subscriber.next(value);\n active++;\n var innerComplete = false;\n innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {\n onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);\n if (expand) {\n outerNext(innerValue);\n }\n else {\n subscriber.next(innerValue);\n }\n }, function () {\n innerComplete = true;\n }, undefined, function () {\n if (innerComplete) {\n try {\n active--;\n var _loop_1 = function () {\n var bufferedValue = buffer.shift();\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });\n }\n else {\n doInnerSub(bufferedValue);\n }\n };\n while (buffer.length && active < concurrent) {\n _loop_1();\n }\n checkComplete();\n }\n catch (err) {\n subscriber.error(err);\n }\n }\n }));\n };\n source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {\n isComplete = true;\n checkComplete();\n }));\n return function () {\n additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();\n };\n}\n//# sourceMappingURL=mergeInternals.js.map","import { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\nexport function mergeMap(project, resultSelector, concurrent) {\n if (concurrent === void 0) { concurrent = Infinity; }\n if (isFunction(resultSelector)) {\n return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);\n }\n else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });\n}\n//# sourceMappingURL=mergeMap.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function filter(predicate, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));\n });\n}\n//# sourceMappingURL=filter.js.map","import { createOperatorSubscriber } from './OperatorSubscriber';\nexport function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {\n return function (source, subscriber) {\n var hasState = hasSeed;\n var state = seed;\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n var i = index++;\n state = hasState\n ?\n accumulator(state, value, i)\n :\n ((hasState = true), value);\n emitOnNext && subscriber.next(state);\n }, emitBeforeComplete &&\n (function () {\n hasState && subscriber.next(state);\n subscriber.complete();\n })));\n };\n}\n//# sourceMappingURL=scanInternals.js.map","import { scanInternals } from './scanInternals';\nimport { operate } from '../util/lift';\nexport function reduce(accumulator, seed) {\n return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));\n}\n//# sourceMappingURL=reduce.js.map","import { reduce } from './reduce';\nimport { operate } from '../util/lift';\nvar arrReducer = function (arr, value) { return (arr.push(value), arr); };\nexport function toArray() {\n return operate(function (source, subscriber) {\n reduce(arrReducer, [])(source).subscribe(subscriber);\n });\n}\n//# sourceMappingURL=toArray.js.map","import { operate } from '../util/lift';\nexport function finalize(callback) {\n return operate(function (source, subscriber) {\n try {\n source.subscribe(subscriber);\n }\n finally {\n subscriber.add(callback);\n }\n });\n}\n//# sourceMappingURL=finalize.js.map","import { __read, __spreadArray } from \"tslib\";\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { SafeSubscriber } from '../Subscriber';\nimport { operate } from '../util/lift';\nexport function share(options) {\n if (options === void 0) { options = {}; }\n var _a = options.connector, connector = _a === void 0 ? function () { return new Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d;\n return function (wrapperSource) {\n var connection;\n var resetConnection;\n var subject;\n var refCount = 0;\n var hasCompleted = false;\n var hasErrored = false;\n var cancelReset = function () {\n resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();\n resetConnection = undefined;\n };\n var reset = function () {\n cancelReset();\n connection = subject = undefined;\n hasCompleted = hasErrored = false;\n };\n var resetAndUnsubscribe = function () {\n var conn = connection;\n reset();\n conn === null || conn === void 0 ? void 0 : conn.unsubscribe();\n };\n return operate(function (source, subscriber) {\n refCount++;\n if (!hasErrored && !hasCompleted) {\n cancelReset();\n }\n var dest = (subject = subject !== null && subject !== void 0 ? subject : connector());\n subscriber.add(function () {\n refCount--;\n if (refCount === 0 && !hasErrored && !hasCompleted) {\n resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);\n }\n });\n dest.subscribe(subscriber);\n if (!connection &&\n refCount > 0) {\n connection = new SafeSubscriber({\n next: function (value) { return dest.next(value); },\n error: function (err) {\n hasErrored = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnError, err);\n dest.error(err);\n },\n complete: function () {\n hasCompleted = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnComplete);\n dest.complete();\n },\n });\n innerFrom(source).subscribe(connection);\n }\n })(wrapperSource);\n };\n}\nfunction handleReset(reset, on) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (on === true) {\n reset();\n return;\n }\n if (on === false) {\n return;\n }\n var onSubscriber = new SafeSubscriber({\n next: function () {\n onSubscriber.unsubscribe();\n reset();\n },\n });\n return innerFrom(on.apply(void 0, __spreadArray([], __read(args)))).subscribe(onSubscriber);\n}\n//# sourceMappingURL=share.js.map","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\n// src/ArraySubject.ts\nimport { BehaviorSubject } from \"rxjs\";\nvar ArraySubject = class extends BehaviorSubject {\n static {\n __name(this, \"ArraySubject\");\n }\n _items = [];\n constructor(items = []) {\n super({\n type: \"init\",\n items\n });\n this.createProxy(items);\n }\n createProxy(items) {\n this._items = new Proxy(items, {\n get: /* @__PURE__ */ __name((target, prop, receiver) => {\n const origMethod = target[prop];\n if (typeof origMethod === \"function\") {\n return (...args) => {\n let changeType = \"update\";\n let index = void 0;\n let isMutateFn = false;\n let itemsToEmit = [];\n let changeSplice = true;\n switch (prop) {\n case \"push\":\n index = target.length;\n changeType = \"add\";\n isMutateFn = true;\n break;\n case \"pop\":\n index = target.length - 1;\n changeType = \"remove\";\n isMutateFn = true;\n break;\n case \"unshift\":\n index = 0;\n changeType = \"add\";\n isMutateFn = true;\n break;\n case \"shift\":\n index = 0;\n changeType = \"remove\";\n isMutateFn = true;\n break;\n case \"splice\":\n index = args[0];\n const deleteCount = args[1];\n const newItems = args.slice(2);\n itemsToEmit = newItems;\n if (deleteCount > 0 && newItems.length === 0) {\n changeType = \"remove\";\n } else if (deleteCount === 0 && newItems.length > 0) {\n changeType = \"add\";\n } else if (deleteCount === 0 && newItems.length === 0) {\n changeSplice = false;\n } else {\n changeType = \"update\";\n }\n isMutateFn = true;\n break;\n }\n const result = origMethod.apply(target, args);\n if (isMutateFn && changeSplice) {\n if (prop === \"splice\") {\n this.next({\n type: changeType,\n index,\n items: itemsToEmit\n });\n } else {\n this.next({\n type: changeType,\n index,\n items: args\n });\n }\n }\n return result;\n };\n }\n return Reflect.get(target, prop, receiver);\n }, \"get\"),\n set: /* @__PURE__ */ __name((target, prop, value) => {\n const index = !isNaN(Number(prop)) ? Number(prop) : void 0;\n target[prop] = value;\n this.next({\n type: \"update\",\n index,\n items: [\n value\n ]\n });\n return true;\n }, \"set\")\n });\n }\n get items() {\n return this._items;\n }\n set items(newItems) {\n this.createProxy(newItems);\n this.next({\n type: \"reset\",\n items: newItems\n });\n }\n};\nvar isArraySubject = /* @__PURE__ */ __name((value) => {\n return \"_items\" in value;\n}, \"isArraySubject\");\n\n// src/ObjectSubject.ts\nimport { BehaviorSubject as BehaviorSubject2 } from \"rxjs\";\nvar ObjectSubject = class extends BehaviorSubject2 {\n static {\n __name(this, \"ObjectSubject\");\n }\n _obj;\n constructor(obj = {}) {\n super({\n type: \"init\",\n value: obj\n });\n this.createProxy(obj);\n }\n createProxy(obj) {\n this._obj = new Proxy(obj, {\n get: /* @__PURE__ */ __name((target, prop, receiver) => {\n return Reflect.get(target, prop, receiver);\n }, \"get\"),\n set: /* @__PURE__ */ __name((target, prop, value, receiver) => {\n const key = prop;\n const changeType = key in target ? \"update\" : \"add\";\n target[key] = value;\n this.next({\n type: changeType,\n key,\n value\n });\n return true;\n }, \"set\"),\n deleteProperty: /* @__PURE__ */ __name((target, prop) => {\n const key = prop;\n if (key in target) {\n const value = target[key];\n delete target[key];\n this.next({\n type: \"remove\",\n key,\n value\n });\n return true;\n }\n return false;\n }, \"deleteProperty\")\n });\n }\n get obj() {\n return this._obj;\n }\n set obj(newObj) {\n this.createProxy(newObj);\n this.next({\n type: \"reset\",\n value: newObj\n });\n }\n};\nvar isObjectSubject = /* @__PURE__ */ __name((value) => {\n return \"_obj\" in value;\n}, \"isObjectSubject\");\n\n// src/signal.ts\nimport { BehaviorSubject as BehaviorSubject3, combineLatest, filter, finalize, map, Observable } from \"rxjs\";\nvar getGlobalReactiveStore = /* @__PURE__ */ __name(() => {\n const globalKey = \"__REACTIVE_STORE__\";\n if (typeof globalThis !== \"undefined\") {\n if (!globalThis[globalKey]) {\n globalThis[globalKey] = {\n currentDependencyTracker: null,\n currentSubscriptionsTracker: null\n };\n }\n return globalThis[globalKey];\n }\n let globalObj;\n if (typeof window !== \"undefined\") {\n globalObj = window;\n } else if (typeof process !== \"undefined\" && process.versions && process.versions.node) {\n globalObj = Function(\"return this\")();\n } else if (typeof self !== \"undefined\") {\n globalObj = self;\n } else {\n console.warn(\"Unable to find global object, using local instance\");\n return {\n currentDependencyTracker: null,\n currentSubscriptionsTracker: null\n };\n }\n if (!globalObj[globalKey]) {\n globalObj[globalKey] = {\n currentDependencyTracker: null,\n currentSubscriptionsTracker: null\n };\n }\n return globalObj[globalKey];\n}, \"getGlobalReactiveStore\");\nvar reactiveStore = getGlobalReactiveStore();\nvar trackDependency = /* @__PURE__ */ __name((signal2) => {\n if (reactiveStore.currentDependencyTracker) {\n reactiveStore.currentDependencyTracker(signal2);\n }\n}, \"trackDependency\");\nfunction signal(defaultValue, options) {\n let subject;\n if (Array.isArray(defaultValue)) {\n subject = new ArraySubject(defaultValue);\n } else if (typeof defaultValue === \"object\" && defaultValue !== null) {\n subject = new ObjectSubject(defaultValue);\n } else {\n subject = new BehaviorSubject3(defaultValue);\n }\n const getValue = /* @__PURE__ */ __name(() => {\n if (subject instanceof ArraySubject) {\n return subject.items;\n } else if (subject instanceof ObjectSubject) {\n return subject.obj;\n }\n return subject.value;\n }, \"getValue\");\n const fn = /* @__PURE__ */ __name(function() {\n trackDependency(fn);\n return getValue();\n }, \"fn\");\n fn.set = (value) => {\n const currentValue = getValue();\n let shouldEmit = true;\n if (options?.equal) {\n shouldEmit = !options.equal(currentValue, value);\n } else {\n shouldEmit = currentValue !== value;\n }\n if (shouldEmit) {\n if (subject instanceof ArraySubject) {\n subject.items = value;\n } else if (subject instanceof ObjectSubject) {\n subject.obj = value;\n } else {\n subject.next(value);\n }\n }\n };\n fn._isFrozen = false;\n fn.freeze = () => {\n fn._isFrozen = true;\n };\n fn.unfreeze = () => {\n fn._isFrozen = false;\n if (subject instanceof ArraySubject) {\n subject.next({\n type: \"init\",\n items: subject.items\n });\n } else if (subject instanceof ObjectSubject) {\n subject.next({\n type: \"init\",\n value: subject.obj\n });\n } else {\n subject.next(subject.value);\n }\n };\n fn.mutate = (mutateFn) => {\n const value = getValue();\n mutateFn(value);\n };\n fn.update = (updateFn) => {\n const updatedValue = updateFn(getValue());\n fn.set(updatedValue);\n };\n fn.observable = subject.asObservable().pipe(filter(() => !fn._isFrozen));\n fn._subject = subject;\n return fn;\n}\n__name(signal, \"signal\");\nfunction isSignal(value) {\n return !!(value && value.observable);\n}\n__name(isSignal, \"isSignal\");\nfunction isComputed(value) {\n return isSignal(value) && !!value.dependencies;\n}\n__name(isComputed, \"isComputed\");\nfunction computed(computeFunction, disposableFn) {\n const dependencies = /* @__PURE__ */ new Set();\n let init = true;\n let lastComputedValue;\n const previousTracker = reactiveStore.currentDependencyTracker;\n reactiveStore.currentDependencyTracker = (signal2) => {\n dependencies.add(signal2);\n };\n lastComputedValue = computeFunction();\n if (computeFunction[\"isEffect\"]) {\n disposableFn = lastComputedValue;\n }\n reactiveStore.currentDependencyTracker = previousTracker;\n const observables = [\n ...dependencies\n ].map((dep) => {\n if (isComputed(dep) && \"dependencies\" in dep) {\n const computedDep = dep;\n if (computedDep.dependencies.size === 0) {\n return new BehaviorSubject3(computedDep()).asObservable();\n }\n }\n return dep.observable;\n });\n const computedObservable = combineLatest(observables).pipe(filter(() => !init), map(() => computeFunction()), finalize(() => disposableFn?.()));\n const fn = /* @__PURE__ */ __name(function() {\n trackDependency(fn);\n return lastComputedValue;\n }, \"fn\");\n fn.observable = computedObservable;\n fn.subscription = computedObservable.subscribe((value) => {\n lastComputedValue = value;\n });\n fn.dependencies = dependencies;\n reactiveStore.currentSubscriptionsTracker?.(fn.subscription);\n init = false;\n return fn;\n}\n__name(computed, \"computed\");\nfunction linkedSignal(computationOrOptions, simpleOptions) {\n const dependencies = /* @__PURE__ */ new Set();\n let init = true;\n let lastComputedValue;\n let computeFunction;\n let sourceSignal;\n let computationFn;\n let equalFn;\n let previousValue;\n let isOverridden = false;\n let overriddenValue;\n let lastComputedBeforeOverride;\n let depVersion = 0;\n let overrideDepVersion = null;\n if (typeof computationOrOptions === \"function\") {\n computeFunction = computationOrOptions;\n equalFn = simpleOptions?.equal;\n } else {\n const options = computationOrOptions;\n sourceSignal = options.source;\n computationFn = options.computation;\n equalFn = options.equal;\n if (typeof sourceSignal === \"function\" && !isSignal(sourceSignal)) {\n const sourceFn = sourceSignal;\n computeFunction = /* @__PURE__ */ __name(() => {\n const sourceValue = sourceFn();\n if (computationFn.length > 1) {\n const result = computationFn(sourceValue, previousValue);\n previousValue = {\n source: sourceValue,\n value: result\n };\n return result;\n } else {\n const result = computationFn(sourceValue);\n previousValue = {\n source: sourceValue,\n value: result\n };\n return result;\n }\n }, \"computeFunction\");\n } else {\n const source = typeof sourceSignal === \"function\" ? sourceSignal : sourceSignal;\n computeFunction = /* @__PURE__ */ __name(() => {\n const sourceValue = source();\n if (computationFn.length > 1) {\n const result = computationFn(sourceValue, previousValue);\n previousValue = {\n source: sourceValue,\n value: result\n };\n return result;\n } else {\n const result = computationFn(sourceValue);\n previousValue = {\n source: sourceValue,\n value: result\n };\n return result;\n }\n }, \"computeFunction\");\n }\n }\n const previousTracker = reactiveStore.currentDependencyTracker;\n reactiveStore.currentDependencyTracker = (signal2) => {\n dependencies.add(signal2);\n };\n if (sourceSignal && typeof sourceSignal === \"function\" && !isSignal(sourceSignal)) {\n lastComputedValue = computeFunction();\n lastComputedBeforeOverride = lastComputedValue;\n } else if (sourceSignal && isSignal(sourceSignal)) {\n dependencies.add(sourceSignal);\n lastComputedValue = computeFunction();\n lastComputedBeforeOverride = lastComputedValue;\n } else {\n lastComputedValue = computeFunction();\n lastComputedBeforeOverride = lastComputedValue;\n }\n reactiveStore.currentDependencyTracker = previousTracker;\n const subject = new BehaviorSubject3(lastComputedValue);\n const observables = [\n ...dependencies\n ].map((dep) => {\n if (isComputed(dep) && \"dependencies\" in dep) {\n const computedDep = dep;\n if (computedDep.dependencies.size === 0) {\n return new BehaviorSubject3(computedDep()).asObservable();\n }\n }\n return dep.observable;\n });\n let linkedObservable;\n if (observables.length > 0) {\n linkedObservable = combineLatest(observables).pipe(filter(() => !init), map(() => {\n const computed2 = computeFunction();\n if (equalFn) {\n if (!equalFn(lastComputedValue, computed2)) {\n lastComputedValue = computed2;\n isOverridden = false;\n }\n } else {\n if (lastComputedValue !== computed2) {\n lastComputedValue = computed2;\n isOverridden = false;\n }\n }\n return lastComputedValue;\n }));\n } else {\n linkedObservable = subject.asObservable().pipe(filter(() => !init));\n }\n const fn = /* @__PURE__ */ __name(function() {\n trackDependency(fn);\n if (isOverridden && dependencies.size > 0) {\n if (overrideDepVersion !== depVersion) {\n const computed2 = computeFunction();\n isOverridden = false;\n overriddenValue = void 0;\n lastComputedValue = computed2;\n lastComputedBeforeOverride = computed2;\n overrideDepVersion = null;\n return computed2;\n }\n return overriddenValue;\n }\n if (isOverridden) {\n return overriddenValue;\n }\n if (dependencies.size === 0) {\n const computed2 = computeFunction();\n lastComputedValue = computed2;\n lastComputedBeforeOverride = computed2;\n }\n return lastComputedValue;\n }, \"fn\");\n fn.observable = new Observable((observer) => {\n const depSubscription = linkedObservable.subscribe((value) => {\n if (dependencies.size > 0) {\n depVersion++;\n isOverridden = false;\n overrideDepVersion = null;\n lastComputedValue = value;\n lastComputedBeforeOverride = value;\n } else {\n lastComputedValue = value;\n lastComputedBeforeOverride = value;\n }\n observer.next(value);\n });\n let subjectSubscription;\n if (dependencies.size === 0) {\n subjectSubscription = subject.pipe(filter(() => !init)).subscribe((value) => {\n observer.next(value);\n });\n }\n observer.next(lastComputedValue);\n return () => {\n depSubscription.unsubscribe();\n if (subjectSubscription) {\n subjectSubscription.unsubscribe();\n }\n };\n });\n fn.subscription = fn.observable.subscribe(() => {\n });\n fn.dependencies = dependencies;\n fn._subject = subject;\n fn.set = (value) => {\n if (!isOverridden) {\n lastComputedBeforeOverride = lastComputedValue;\n overrideDepVersion = depVersion;\n if (computationFn && sourceSignal) {\n const sourceValue = untracked(() => {\n if (typeof sourceSignal === \"function\") {\n const source = sourceSignal;\n return isSignal(source) ? source() : sourceSignal();\n }\n return sourceSignal();\n });\n previousValue = {\n source: sourceValue,\n value\n };\n }\n }\n isOverridden = true;\n overriddenValue = value;\n lastComputedValue = value;\n subject.next(value);\n };\n reactiveStore.currentSubscriptionsTracker?.(fn.subscription);\n init = false;\n return fn;\n}\n__name(linkedSignal, \"linkedSignal\");\nfunction untracked(fn) {\n const prevDepTracker = reactiveStore.currentDependencyTracker;\n const prevSubTracker = reactiveStore.currentSubscriptionsTracker;\n reactiveStore.currentDependencyTracker = null;\n reactiveStore.currentSubscriptionsTracker = null;\n try {\n return fn();\n } finally {\n reactiveStore.currentDependencyTracker = prevDepTracker;\n reactiveStore.currentSubscriptionsTracker = prevSubTracker;\n }\n}\n__name(untracked, \"untracked\");\n\n// src/effect.ts\nfunction effect(fn) {\n fn[\"isEffect\"] = true;\n return computed(fn);\n}\n__name(effect, \"effect\");\nexport {\n ArraySubject,\n ObjectSubject,\n computed,\n effect,\n isArraySubject,\n isComputed,\n isObjectSubject,\n isSignal,\n linkedSignal,\n signal,\n untracked\n};\n//# sourceMappingURL=index.js.map","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport {\n __name\n};\n//# sourceMappingURL=chunk-7QVYU63E.js.map","import {\n __name\n} from \"./chunk-7QVYU63E.js\";\n\n// src/core.ts\nimport { isArraySubject, isObjectSubject, isSignal, isComputed } from \"@signe/reactive\";\n\n// src/utils.ts\nfunction isFunction(val) {\n return {}.toString.call(val) === \"[object Function]\";\n}\n__name(isFunction, \"isFunction\");\nfunction isClass(obj) {\n return typeof obj === \"function\" && obj.prototype && obj.prototype.constructor === obj;\n}\n__name(isClass, \"isClass\");\nvar isObject = /* @__PURE__ */ __name((item) => item && typeof item === \"object\" && !Array.isArray(item) && item !== null, \"isObject\");\nfunction isInstanceOfClass(value) {\n if (value === null || typeof value !== \"object\" || value === void 0 || Array.isArray(value)) {\n return false;\n }\n return Object.getPrototypeOf(value) !== Object.prototype;\n}\n__name(isInstanceOfClass, \"isInstanceOfClass\");\nfunction generateShortUUID() {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n let uuid = \"\";\n for (let i = 0; i < 8; i++) {\n const randomIndex = Math.floor(Math.random() * chars.length);\n uuid += chars[randomIndex];\n }\n return uuid;\n}\n__name(generateShortUUID, \"generateShortUUID\");\n\n// src/core.ts\nvar DELETE_TOKEN = \"$delete\";\nvar syncClass = /* @__PURE__ */ __name((instance, options = {}) => {\n const cacheSync = /* @__PURE__ */ new Map();\n const cachePersist = /* @__PURE__ */ new Map();\n instance.$valuesChanges = {\n set: /* @__PURE__ */ __name((path, value) => {\n cacheSync.set(path, value);\n options.onSync?.(cacheSync);\n }, \"set\"),\n setPersist: /* @__PURE__ */ __name((path, value) => {\n if (path == \"\") path = \".\";\n cachePersist.set(path, value);\n options.onPersist?.(cachePersist);\n }, \"setPersist\"),\n has: /* @__PURE__ */ __name((path) => {\n return cacheSync.has(path);\n }, \"has\"),\n get: /* @__PURE__ */ __name((path) => {\n return cacheSync.get(path);\n }, \"get\")\n };\n createSyncClass(instance);\n}, \"syncClass\");\nfunction createStatesSnapshot(instance) {\n let persistObject = {};\n if (instance?.$snapshot) {\n for (const key of instance.$snapshot.keys()) {\n const signal = instance.$snapshot.get(key);\n const persist2 = signal.options.persist ?? true;\n let value = signal();\n if (isObject(value) || Array.isArray(value)) {\n continue;\n }\n if (persist2) {\n persistObject[key] = value;\n }\n }\n }\n return persistObject;\n}\n__name(createStatesSnapshot, \"createStatesSnapshot\");\nvar SNAPSHOT_SKIP = Symbol(\"snapshot-skip\");\nvar serializeSnapshotDeep = /* @__PURE__ */ __name((value, path, options, seen) => {\n if (isSignal(value)) {\n return serializeSnapshotDeep(value(), path, options, seen);\n }\n if (value instanceof Map) {\n return SNAPSHOT_SKIP;\n }\n if (options.filter && !options.filter(value, path)) {\n return SNAPSHOT_SKIP;\n }\n if (value instanceof Date) {\n return options.dateToString ? options.dateToString(value) : value.toISOString();\n }\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n return SNAPSHOT_SKIP;\n }\n seen.add(value);\n if (Array.isArray(value)) {\n const result2 = [];\n value.forEach((item, index) => {\n const itemPath = path ? `${path}.${index}` : String(index);\n const serialized = serializeSnapshotDeep(item, itemPath, options, seen);\n if (serialized !== SNAPSHOT_SKIP) {\n result2.push(serialized);\n }\n });\n return result2;\n }\n const result = {};\n const idKey = isInstanceOfClass(value) ? value.constructor?._propertyMetadata?.get(\"id\") : void 0;\n const entries = Object.entries(value).filter(([key]) => isInstanceOfClass(value) ? key.startsWith(\"__\") || (idKey ? key === idKey : false) : true);\n for (const [key, childValue] of entries) {\n const normalizedKey = key.startsWith(\"__\") ? key.slice(2) : key;\n const childPath = path ? `${path}.${normalizedKey}` : normalizedKey;\n const serialized = serializeSnapshotDeep(childValue, childPath, options, seen);\n if (serialized !== SNAPSHOT_SKIP) {\n result[normalizedKey] = serialized;\n }\n }\n return result;\n }\n return value;\n}, \"serializeSnapshotDeep\");\nfunction createStatesSnapshotDeep(instance, options = {}) {\n const persistObject = {};\n if (instance?.$snapshot) {\n for (const key of instance.$snapshot.keys()) {\n const signal = instance.$snapshot.get(key);\n const persist2 = signal.options.persist ?? true;\n if (!persist2) {\n continue;\n }\n const value = signal();\n const serialized = serializeSnapshotDeep(value, key, options, /* @__PURE__ */ new WeakSet());\n if (serialized !== SNAPSHOT_SKIP) {\n persistObject[key] = serialized;\n }\n }\n }\n return persistObject;\n}\n__name(createStatesSnapshotDeep, \"createStatesSnapshotDeep\");\nfunction setMetadata(target, key, value) {\n const meta = target.constructor._propertyMetadata;\n const propId = meta?.get(key);\n if (propId) {\n if (isSignal(target[propId])) {\n target[propId].set(value);\n } else {\n target[propId] = value;\n }\n }\n}\n__name(setMetadata, \"setMetadata\");\nvar createSyncClass = /* @__PURE__ */ __name((currentClass, parentKey = null, parentClass = null, path = \"\") => {\n currentClass.$path = path;\n if (parentClass) {\n currentClass.$valuesChanges = parentClass.$valuesChanges;\n }\n if (parentKey) {\n setMetadata(currentClass, \"id\", parentKey);\n }\n if (currentClass.$snapshot) {\n for (const key of currentClass.$snapshot.keys()) {\n const signal = currentClass.$snapshot.get(key);\n const syncToClient = signal.options?.syncToClient ?? true;\n const persist2 = signal.options?.persist ?? true;\n const transform = signal.options?.transform;\n let signalValue = signal();\n if (transform) {\n signalValue = transform(signalValue);\n }\n if (isObject(signalValue) || Array.isArray(signalValue)) {\n signalValue = {\n ...signalValue\n };\n }\n const transformedValue = signalValue;\n const newPath = (path ? path + \".\" : \"\") + key;\n if (syncToClient) {\n currentClass.$valuesChanges.set(newPath, transformedValue);\n }\n if (persist2) {\n if (parentClass) currentClass.$valuesChanges.setPersist(path, transformedValue);\n }\n if (isComputed(signal)) {\n signal.observable.subscribe((newValue) => {\n if (syncToClient) {\n const transformedNewValue = transform ? transform(newValue) : newValue;\n currentClass.$valuesChanges.set(newPath, transformedNewValue);\n }\n });\n }\n }\n }\n}, \"createSyncClass\");\nvar type = /* @__PURE__ */ __name((_signal, path, options = {}, currentInstance) => {\n const { syncToClient = true, persist: persist2 = true, transform } = options;\n let init = true;\n const handleObjectSubject = /* @__PURE__ */ __name((value, propPath) => {\n const newPath = `${propPath}${value.key ? `.${value.key}` : \"\"}`;\n if ([\n \"add\",\n \"reset\",\n \"update\"\n ].includes(value.type)) {\n if (isInstanceOfClass(value.value)) {\n createSyncClass(value.value, value.key, currentInstance, newPath);\n } else if (value.type === \"update\" && (isObject(value.value) || Array.isArray(value.value))) {\n createSyncClass(value.value, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, value.value);\n }\n } else if (value.type === \"remove\") {\n savePath(newPath, DELETE_TOKEN);\n }\n }, \"handleObjectSubject\");\n const handleArraySubject = /* @__PURE__ */ __name((value, propPath) => {\n if (value.type === \"reset\" && Array.isArray(value.items)) {\n value.items.forEach((item, index) => {\n const newPath2 = `${propPath}.${index}`;\n if (isInstanceOfClass(item)) {\n createSyncClass(item, value.key, currentInstance, newPath2);\n } else {\n savePath(newPath2, item);\n }\n });\n return;\n }\n const newPath = `${propPath}.${value.index}`;\n const firstItem = value.items?.[0];\n if ([\n \"add\",\n \"update\"\n ].includes(value.type) && firstItem !== void 0) {\n if (isInstanceOfClass(firstItem)) {\n createSyncClass(firstItem, value.key, currentInstance, newPath);\n } else if (value.type === \"update\" && (isObject(firstItem) || Array.isArray(firstItem))) {\n createSyncClass(firstItem, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, firstItem);\n }\n } else if (value.type === \"remove\") {\n savePath(newPath, DELETE_TOKEN);\n }\n }, \"handleArraySubject\");\n const savePath = /* @__PURE__ */ __name((propPath, value) => {\n const transformedValue = transform && value !== DELETE_TOKEN ? transform(value) : value;\n if (syncToClient) {\n currentInstance.$valuesChanges.set(propPath, transformedValue);\n }\n if (persist2 && currentInstance.$path !== void 0) {\n currentInstance.$valuesChanges.setPersist(transformedValue == DELETE_TOKEN ? propPath : currentInstance.$path, transformedValue);\n }\n }, \"savePath\");\n const setupSubscription = /* @__PURE__ */ __name((signal, signalPath) => {\n if (!isSignal(signal)) return;\n if (syncToClient && currentInstance.$valuesChanges) {\n const initialValue = signal();\n const transformedInitialValue = transform ? transform(initialValue) : initialValue;\n currentInstance.$valuesChanges.set(signalPath, transformedInitialValue);\n }\n signal.options = options;\n signal.observable.subscribe((value) => {\n if (init) return;\n if (currentInstance.$path !== void 0) {\n const fullPath = `${currentInstance.$path ? currentInstance.$path + \".\" : \"\"}${signalPath}`;\n if (isComputed(signal)) {\n savePath(fullPath, value);\n } else if (isObjectSubject(signal._subject)) {\n handleObjectSubject(value, fullPath);\n } else if (isArraySubject(signal._subject)) {\n handleArraySubject(value, fullPath);\n } else {\n savePath(fullPath, value);\n }\n }\n });\n if (!currentInstance.$snapshot) {\n currentInstance.$snapshot = /* @__PURE__ */ new Map();\n }\n currentInstance.$snapshot.set(path, signal);\n }, \"setupSubscription\");\n if (!isSignal(_signal)) {\n if (_signal && typeof _signal === \"object\" && !Array.isArray(_signal)) {\n for (const key in _signal) {\n if (Object.prototype.hasOwnProperty.call(_signal, key)) {\n const value = _signal[key];\n const propertyPath = `${path}.${key}`;\n if (isSignal(value)) {\n setupSubscription(value, propertyPath);\n } else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n type(value, propertyPath, options, currentInstance);\n }\n }\n }\n init = false;\n }\n return _signal;\n }\n setupSubscription(_signal, path);\n init = false;\n return _signal;\n}, \"type\");\n\n// src/decorators.ts\nfunction sync(options) {\n let classType;\n let persist2 = true;\n let syncToClient = true;\n let transform;\n if (typeof options === \"function\") {\n classType = options;\n } else if (typeof options === \"object\") {\n classType = options.classType;\n if (options.hasOwnProperty(\"persist\")) {\n persist2 = options.persist;\n }\n if (options.hasOwnProperty(\"syncToClient\")) {\n syncToClient = options.syncToClient;\n }\n if (options.hasOwnProperty(\"transform\")) {\n transform = options.transform;\n }\n }\n return function(target, propertyKey) {\n const privatePropertyKey = `__${propertyKey}`;\n const getter = /* @__PURE__ */ __name(function() {\n return this[privatePropertyKey];\n }, \"getter\");\n const setter = /* @__PURE__ */ __name(function(newVal) {\n this[privatePropertyKey] = type(newVal, propertyKey, {\n classType,\n persist: persist2,\n syncToClient,\n transform\n }, this);\n }, \"setter\");\n Object.defineProperty(target, propertyKey, {\n get: getter,\n set: setter,\n enumerable: true,\n configurable: true\n });\n };\n}\n__name(sync, \"sync\");\nfunction id() {\n return function(target, propertyKey) {\n if (!target.constructor._propertyMetadata) {\n target.constructor._propertyMetadata = /* @__PURE__ */ new Map();\n }\n target.constructor._propertyMetadata.set(\"id\", propertyKey);\n };\n}\n__name(id, \"id\");\nfunction users(options) {\n return function(target, propertyKey) {\n if (!target.constructor._propertyMetadata) {\n target.constructor._propertyMetadata = /* @__PURE__ */ new Map();\n }\n target.constructor._propertyMetadata.set(\"users\", propertyKey);\n sync(options)(target, propertyKey);\n };\n}\n__name(users, \"users\");\nfunction persist() {\n return sync({\n persist: true,\n syncToClient: false\n });\n}\n__name(persist, \"persist\");\nfunction connected() {\n return function(target, propertyKey) {\n if (!target.constructor._propertyMetadata) {\n target.constructor._propertyMetadata = /* @__PURE__ */ new Map();\n }\n target.constructor._propertyMetadata.set(\"connected\", propertyKey);\n sync({\n persist: false\n })(target, propertyKey);\n };\n}\n__name(connected, \"connected\");\n\n// src/load.ts\nimport { isSignal as isSignal2 } from \"@signe/reactive\";\nfunction load(rootInstance, values, valueIsObject) {\n if (valueIsObject) {\n loadFromObject(rootInstance, values);\n } else {\n loadFromPaths(rootInstance, values);\n }\n}\n__name(load, \"load\");\nfunction loadFromPaths(rootInstance, values) {\n for (const [path, value] of Object.entries(values)) {\n const parts = path.split(\".\");\n loadValue(rootInstance, parts, value);\n }\n}\n__name(loadFromPaths, \"loadFromPaths\");\nfunction loadFromObject(rootInstance, values, currentPath = \"\") {\n for (let key in values) {\n const value = values[key];\n const newPath = currentPath ? `${currentPath}.${key}` : key;\n if (typeof value === \"object\" && !Array.isArray(value) && value !== null) {\n loadFromObject(rootInstance, value, newPath);\n } else {\n const parts = newPath.split(\".\");\n loadValue(rootInstance, parts, value);\n }\n }\n}\n__name(loadFromObject, \"loadFromObject\");\nfunction loadValue(rootInstance, parts, value) {\n let current = rootInstance;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n if (value == DELETE_TOKEN) {\n if (isSignal2(current)) {\n current = current();\n }\n Reflect.deleteProperty(current, part);\n } else if (current[part]?._subject) {\n current[part].set(value);\n } else if (isSignal2(current) && Array.isArray(current()) && !isNaN(Number(part))) {\n current()[Number(part)] = value;\n } else {\n current[part] = value;\n }\n } else {\n if (isSignal2(current)) {\n current = current();\n }\n const currentValue = current[part];\n if (currentValue === void 0) {\n const parentInstance = getByPath(rootInstance, parts.slice(0, i).join(\".\"));\n const classType = parentInstance?.options?.classType;\n if (classType) {\n current[part] = !isClass(classType) ? classType(part) : new classType();\n setMetadata(current[part], \"id\", part);\n } else {\n current[part] = {};\n }\n }\n current = current[part];\n }\n }\n}\n__name(loadValue, \"loadValue\");\nfunction getByPath(root, path) {\n const parts = path.split(\".\");\n let current = root;\n for (const part of parts) {\n if (isSignal2(current)) {\n current = current();\n }\n if (current[part]) {\n current = current[part];\n } else {\n return void 0;\n }\n }\n return current;\n}\n__name(getByPath, \"getByPath\");\nexport {\n DELETE_TOKEN,\n connected,\n createStatesSnapshot,\n createStatesSnapshotDeep,\n createSyncClass,\n generateShortUUID,\n getByPath,\n id,\n isClass,\n isFunction,\n isInstanceOfClass,\n isObject,\n load,\n persist,\n setMetadata,\n sync,\n syncClass,\n type,\n users\n};\n//# sourceMappingURL=index.js.map","import { signal } from \"@signe/reactive\";\nimport { id, sync } from \"@signe/sync\";\nimport { RpgCommonPlayer } from \"../Player\";\n\ninterface ItemData {\n name: string;\n description: string;\n price: number;\n quantity: number;\n atk: number;\n pdef: number;\n sdef: number;\n icon: string\n onAdd: (player: RpgCommonPlayer) => void;\n}\n\nexport class Item {\n @id() id = signal('');\n @sync() name = signal('');\n description = signal('');\n price = signal(0);\n atk = signal(0);\n pdef = signal(0);\n sdef = signal(0);\n @sync() icon = signal('')\n @sync() quantity = signal(1);\n\n onAdd: (player: RpgCommonPlayer) => void = () => {};\n\n constructor(data?: ItemData) {\n this.description.set(data?.description ?? '');\n this.price.set(data?.price ?? 0);\n this.name.set(data?.name ?? '');\n this.atk.set(data?.atk ?? 0);\n this.pdef.set(data?.pdef ?? 0);\n this.sdef.set(data?.sdef ?? 0);\n this.icon.set(data?.icon ?? '')\n this.onAdd = data?.onAdd?.bind(this) ?? (() => {});\n }\n}\n","import { signal } from \"@signe/reactive\";\nimport { id, sync } from \"@signe/sync\";\n\nexport interface SkillData {\n id: string;\n name: string;\n description: string;\n spCost: number;\n hitRate: number;\n power: number;\n coefficient: Record<string, number>;\n icon: string\n}\n\nexport class Skill {\n @id() id = signal('');\n @sync() name = signal('');\n description = signal('');\n @sync() spCost = signal(0);\n @sync() icon = signal('')\n hitRate = signal(0);\n power = signal(0);\n coefficient = signal({});\n\n constructor(data?: SkillData) {\n this.id.set(data?.id ?? '');\n this.name.set(data?.name ?? '');\n this.description.set(data?.description ?? '');\n this.spCost.set(data?.spCost ?? 0);\n this.hitRate.set(data?.hitRate ?? 0);\n this.power.set(data?.power ?? 0);\n this.coefficient.set(data?.coefficient ?? {});\n this.icon.set(data?.icon ?? '')\n }\n}","import { signal } from \"@signe/reactive\";\nimport { connected, id, persist, sync, users } from \"@signe/sync\";\nimport { Item, Skill } from \"./database\";\nimport { Constructor } from \"./Utils\";\n\nexport enum Control {\n Action = 'action',\n Attack = 'attack',\n Defense = 'defense',\n Skill = 'skill',\n Back = 'back',\n Up = 1,\n Down = 3,\n Right = 2,\n Left = 4\n}\n\nexport enum Direction {\n Up = \"up\",\n Down = \"down\",\n Left = \"left\",\n Right = \"right\",\n}\n\nexport enum Animation {\n Stand = \"stand\",\n Walk = \"walk\",\n Attack = \"attack\",\n Defense = \"defense\",\n Skill = \"skill\",\n}\n\nexport interface Hitbox {\n w: number;\n h: number;\n}\n\nexport interface ShowAnimationParams {\n graphic?: string | string[];\n animationName: string;\n loop?: boolean;\n}\n\nexport interface AttachShapeOptions {\n /** Width of the shape in pixels */\n width: number;\n /** Height of the shape in pixels */\n height: number;\n /** Circle radius in pixels (for zone shapes) */\n radius?: number;\n /** Vision aperture in degrees. 360 = full circle, <360 = cone */\n angle?: number;\n /** Facing direction used when angle < 360 */\n direction?: Direction;\n /** If true, walls (static hitboxes) stop vision */\n limitedByWalls?: boolean;\n /** Indicate where the shape is placed relative to the player */\n positioning?: \"center\" | \"top\" | \"bottom\" | \"left\" | \"right\";\n /** The name of the shape */\n name?: string;\n /** An object to retrieve information when interacting with the shape */\n properties?: object;\n}\n\nexport abstract class RpgCommonPlayer {\n @id() id: string;\n @sync() name = signal(\"\");\n @sync() type = signal(\"\");\n // x and y must be @sync() to ensure initial positions are sent to client\n // The positions represent TOP-LEFT coordinates of the character's hitbox\n // @persist() only persists server-side but doesn't sync to client\n @sync() x = signal(0);\n @sync() y = signal(0);\n @sync() z = signal(0);\n @sync() tint = signal(\"white\");\n @sync() direction = signal(Direction.Down);\n @sync() speed = signal(4);\n @sync() graphics = signal<any>([]);\n @sync({\n persist: false\n }) canMove = signal(true);\n @sync() hitbox = signal<Hitbox>({\n w: 32,\n h: 32,\n });\n @sync() _gold = signal(0);\n @sync() animationName = signal(\"stand\");\n @sync() hpSignal = signal(0);\n @sync() spSignal = signal(0);\n @sync() _exp = signal(0);\n @sync() _level = signal(1);\n @sync() _class = signal({});\n @sync(Item) items = signal<Item[]>([]);\n @sync() equipments = signal<any[]>([]);\n @sync() states = signal<any[]>([]);\n @sync(Skill) skills = signal<Skill[]>([]);\n @sync() _effects = signal<any[]>([]);\n @sync() _through = signal(false);\n @sync() _throughOtherPlayer = signal(true);\n @sync() _throughEvent = signal(false);\n @sync() _frequency = signal(0);\n @sync() _frames = signal<{ x: number; y: number; ts: number }[]>([]);\n @sync() componentsTop = signal<string | null>(null);\n @sync() componentsBottom = signal<string | null>(null);\n @sync() componentsCenter = signal<string | null>(null);\n @sync() componentsLeft = signal<string | null>(null);\n @sync() componentsRight = signal<string | null>(null);\n @connected() isConnected = signal(false)\n\n // Store intended movement direction (not synced, only used locally)\n private _intendedDirection: Direction | null = null;\n\n // Direction and animation locking (server-side only, not synced)\n private _directionFixed = signal(false);\n private _animationFixed = signal(false);\n\n /**\n * Get whether direction changes are locked\n * \n * @returns True if direction is locked and cannot be changed automatically\n * \n * @example\n * ```ts\n * if (player.directionFixed) {\n * // Direction is locked, won't change automatically\n * }\n * ```\n */\n get directionFixed(): boolean {\n return this._directionFixed();\n }\n\n /**\n * Set whether direction changes are locked\n * \n * When set to true, the player's direction will not change automatically\n * during movement or from physics engine callbacks.\n * \n * @param value - True to lock direction, false to allow automatic changes\n * \n * @example\n * ```ts\n * // Lock direction during a special animation\n * player.directionFixed = true;\n * player.setAnimation('attack');\n * // ... later\n * player.directionFixed = false;\n * ```\n */\n set directionFixed(value: boolean) {\n this._directionFixed.set(value);\n }\n\n /**\n * Get whether animation changes are locked\n * \n * @returns True if animation is locked and cannot be changed automatically\n * \n * @example\n * ```ts\n * if (player.animationFixed) {\n * // Animation is locked, won't change automatically\n * }\n * ```\n */\n get animationFixed(): boolean {\n return this._animationFixed();\n }\n\n /**\n * Set whether animation changes are locked\n * \n * When set to true, the player's animation will not change automatically\n * during movement or from physics engine callbacks.\n * \n * @param value - True to lock animation, false to allow automatic changes\n * \n * @example\n * ```ts\n * // Lock animation during a special skill\n * player.animationFixed = true;\n * player.setAnimation('skill');\n * // ... later\n * player.animationFixed = false;\n * ```\n */\n set animationFixed(value: boolean) {\n this._animationFixed.set(value);\n }\n\n pendingInputs: any[] = [];\n\n /**\n * Change the player's facing direction\n *\n * Updates the direction the player is facing, which affects animations\n * and directional abilities. This should be called when the player\n * intends to move in a specific direction, not when they are pushed\n * by physics or sliding.\n * \n * If `directionFixed` is true, this method will not change the direction.\n *\n * @param direction - The new direction to face\n *\n * @example\n * ```ts\n * // Player presses right arrow key\n * player.changeDirection(Direction.Right);\n * \n * // Lock direction to prevent automatic changes\n * player.directionFixed = true;\n * player.changeDirection(Direction.Up); // This will be ignored\n * ```\n */\n changeDirection(direction: Direction) {\n // Don't change direction if it's locked\n if (this._directionFixed()) {\n return;\n }\n this.direction.set(direction);\n }\n\n /**\n * Get the current facing direction\n *\n * @returns Current direction the player is facing\n *\n * @example\n * ```ts\n * const currentDirection = player.getDirection();\n * if (currentDirection === Direction.Up) {\n * // Player is facing up\n * }\n * ```\n */\n getDirection() {\n return this.direction();\n }\n\n abstract isEvent(): boolean;\n}\n\nexport type PlayerCtor<T extends RpgCommonPlayer = RpgCommonPlayer> = Constructor<T>","import { RpgCommonPlayer } from \"./Player\";\n\n/**\n * Shape positioning relative to the player\n */\nexport type ShapePositioning = \"center\" | \"top\" | \"bottom\" | \"left\" | \"right\" | \"default\";\n\n/**\n * Represents a zone shape attached to a player or event\n * \n * Shapes are used for detection zones, vision cones, and area-of-effect abilities.\n * They are backed by the physic engine's zone system for accurate detection.\n * \n * @example\n * ```ts\n * // Create a shape attached to a player\n * const visionShape = player.attachShape(\"vision\", {\n * radius: 150,\n * angle: 120,\n * direction: Direction.Right,\n * name: \"Vision Zone\",\n * properties: { type: \"detection\" }\n * });\n * \n * // Check if a player is in the shape\n * if (visionShape.playerIsIn(otherPlayer)) {\n * console.log(\"Player detected!\");\n * }\n * \n * // Get the owner of the shape\n * const owner = visionShape.getPlayerOwner();\n * ```\n */\nexport class RpgShape {\n /** Name of the shape */\n public name: string;\n \n /** Positioning relative to the player */\n public positioning: ShapePositioning;\n \n /** Width of the shape in pixels */\n public width: number;\n \n /** Height of the shape in pixels */\n public height: number;\n \n /** X position of the shape center */\n public x: number;\n \n /** Y position of the shape center */\n public y: number;\n \n /** Custom properties attached to the shape */\n public properties: object;\n \n /** Internal: Player that owns this shape */\n private _playerOwner?: RpgCommonPlayer;\n \n /** Internal: Zone ID in the physic engine */\n private _physicZoneId: string;\n \n /** Internal: Map reference for zone queries */\n private _map: any;\n \n /**\n * Creates a new RpgShape instance\n * \n * @param config - Shape configuration\n */\n constructor(config: {\n name: string;\n positioning: ShapePositioning;\n width: number;\n height: number;\n x: number;\n y: number;\n properties: object;\n playerOwner?: RpgCommonPlayer;\n physicZoneId: string;\n map: any;\n }) {\n this.name = config.name;\n this.positioning = config.positioning;\n this.width = config.width;\n this.height = config.height;\n this.x = config.x;\n this.y = config.y;\n this.properties = config.properties;\n this._playerOwner = config.playerOwner;\n this._physicZoneId = config.physicZoneId;\n this._map = config.map;\n }\n \n /**\n * Checks if a player is currently inside this shape\n * \n * @param player - The player to check\n * @returns True if the player is inside the shape\n * \n * @example\n * ```ts\n * const shape = player.attachShape(\"detection\", { radius: 100 });\n * if (shape.playerIsIn(otherPlayer)) {\n * console.log(\"Player detected in zone\");\n * }\n * ```\n */\n playerIsIn(player: RpgCommonPlayer): boolean {\n if (!this._map) return false;\n \n const zoneManager = this._map.physic.getZoneManager();\n const entities = zoneManager.getEntitiesInZone(this._physicZoneId);\n \n if (!entities || entities.length === 0) return false;\n \n const playerEntity = this._map.physic.getEntityByUUID(player.id);\n if (!playerEntity) return false;\n \n return entities.some(entity => entity.uuid === playerEntity.uuid);\n }\n \n /**\n * Gets the player that owns this shape\n * \n * Returns the player on which `attachShape()` was called to create this shape.\n * \n * @returns The player owner or undefined if not available\n * \n * @example\n * ```ts\n * const shape = player.attachShape(\"vision\", { radius: 150 });\n * const owner = shape.getPlayerOwner();\n * console.log(owner?.name); // Player's name\n * ```\n */\n getPlayerOwner(): RpgCommonPlayer | undefined {\n return this._playerOwner;\n }\n \n /**\n * Updates the shape's position\n * \n * @internal\n */\n public _updatePosition(x: number, y: number): void {\n this.x = x;\n this.y = y;\n }\n}\n","/**\n * 2D Vector class with deterministic operations\n * \n * All operations are designed to be deterministic and avoid floating-point\n * precision issues. Methods support both in-place mutations and immutable operations.\n * \n * @example\n * ```typescript\n * const v1 = new Vector2(1, 2);\n * const v2 = new Vector2(3, 4);\n * const sum = v1.add(v2); // Returns new vector (4, 6)\n * v1.addInPlace(v2); // Mutates v1 to (4, 6)\n * ```\n */\nexport class Vector2 {\n /**\n * X component\n */\n public x: number;\n\n /**\n * Y component\n */\n public y: number;\n\n /**\n * Creates a new Vector2\n * \n * @param x - X component (default: 0)\n * @param y - Y component (default: 0)\n */\n constructor(x = 0, y = 0) {\n this.x = x;\n this.y = y;\n }\n\n /**\n * Creates a copy of this vector\n * \n * @returns A new Vector2 with the same values\n */\n public clone(): Vector2 {\n return new Vector2(this.x, this.y);\n }\n\n /**\n * Sets the components of this vector\n * \n * @param x - X component\n * @param y - Y component\n * @returns This vector for chaining\n */\n public set(x: number, y: number): Vector2 {\n this.x = x;\n this.y = y;\n return this;\n }\n\n /**\n * Copies values from another vector\n * \n * @param other - Vector to copy from\n * @returns This vector for chaining\n */\n public copyFrom(other: Vector2): Vector2 {\n this.x = other.x;\n this.y = other.y;\n return this;\n }\n\n /**\n * Adds another vector to this vector (immutable)\n * \n * @param other - Vector to add\n * @returns New vector with the result\n */\n public add(other: Vector2): Vector2 {\n return new Vector2(this.x + other.x, this.y + other.y);\n }\n\n /**\n * Adds another vector to this vector (in-place)\n * \n * @param other - Vector to add\n * @returns This vector for chaining\n */\n public addInPlace(other: Vector2): Vector2 {\n this.x += other.x;\n this.y += other.y;\n return this;\n }\n\n /**\n * Subtracts another vector from this vector (immutable)\n * \n * @param other - Vector to subtract\n * @returns New vector with the result\n */\n public sub(other: Vector2): Vector2 {\n return new Vector2(this.x - other.x, this.y - other.y);\n }\n\n /**\n * Subtracts another vector from this vector (in-place)\n * \n * @param other - Vector to subtract\n * @returns This vector for chaining\n */\n public subInPlace(other: Vector2): Vector2 {\n this.x -= other.x;\n this.y -= other.y;\n return this;\n }\n\n /**\n * Multiplies this vector by a scalar (immutable)\n * \n * @param scalar - Scalar value\n * @returns New vector with the result\n */\n public mul(scalar: number): Vector2 {\n return new Vector2(this.x * scalar, this.y * scalar);\n }\n\n /**\n * Multiplies this vector by a scalar (in-place)\n * \n * @param scalar - Scalar value\n * @returns This vector for chaining\n */\n public mulInPlace(scalar: number): Vector2 {\n this.x *= scalar;\n this.y *= scalar;\n return this;\n }\n\n /**\n * Divides this vector by a scalar (immutable)\n * \n * @param scalar - Scalar value (must not be zero)\n * @returns New vector with the result\n */\n public div(scalar: number): Vector2 {\n return new Vector2(this.x / scalar, this.y / scalar);\n }\n\n /**\n * Divides this vector by a scalar (in-place)\n * \n * @param scalar - Scalar value (must not be zero)\n * @returns This vector for chaining\n */\n public divInPlace(scalar: number): Vector2 {\n this.x /= scalar;\n this.y /= scalar;\n return this;\n }\n\n /**\n * Calculates the dot product with another vector\n * \n * @param other - Vector to dot with\n * @returns Dot product value\n */\n public dot(other: Vector2): number {\n return this.x * other.x + this.y * other.y;\n }\n\n /**\n * Calculates the 2D cross product (scalar result)\n * \n * @param other - Vector to cross with\n * @returns Cross product value (z-component of 3D cross product)\n */\n public cross(other: Vector2): number {\n return this.x * other.y - this.y * other.x;\n }\n\n /**\n * Calculates the squared length (faster than length, avoids sqrt)\n * \n * @returns Squared length\n */\n public lengthSquared(): number {\n return this.x * this.x + this.y * this.y;\n }\n\n /**\n * Calculates the length (magnitude) of the vector\n * \n * @returns Length\n */\n public length(): number {\n return Math.sqrt(this.lengthSquared());\n }\n\n /**\n * Normalizes this vector to unit length (immutable)\n * \n * @returns New normalized vector\n */\n public normalize(): Vector2 {\n const len = this.length();\n if (len === 0) {\n return new Vector2(0, 0);\n }\n return this.div(len);\n }\n\n /**\n * Normalizes this vector to unit length (in-place)\n * \n * @returns This vector for chaining\n */\n public normalizeInPlace(): Vector2 {\n const len = this.length();\n if (len === 0) {\n this.x = 0;\n this.y = 0;\n } else {\n this.divInPlace(len);\n }\n return this;\n }\n\n /**\n * Calculates the distance to another vector\n * \n * @param other - Target vector\n * @returns Distance\n */\n public distanceTo(other: Vector2): number {\n return this.sub(other).length();\n }\n\n /**\n * Calculates the squared distance to another vector (faster)\n * \n * @param other - Target vector\n * @returns Squared distance\n */\n public distanceToSquared(other: Vector2): number {\n return this.sub(other).lengthSquared();\n }\n\n /**\n * Rotates this vector by an angle in radians (immutable)\n * \n * @param angle - Angle in radians\n * @returns New rotated vector\n */\n public rotate(angle: number): Vector2 {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return new Vector2(\n this.x * cos - this.y * sin,\n this.x * sin + this.y * cos\n );\n }\n\n /**\n * Rotates this vector by an angle in radians (in-place)\n * \n * @param angle - Angle in radians\n * @returns This vector for chaining\n */\n public rotateInPlace(angle: number): Vector2 {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const x = this.x * cos - this.y * sin;\n const y = this.x * sin + this.y * cos;\n this.x = x;\n this.y = y;\n return this;\n }\n\n /**\n * Calculates the angle of this vector in radians\n * \n * @returns Angle in radians (range: -π to π)\n */\n public angle(): number {\n return Math.atan2(this.y, this.x);\n }\n\n /**\n * Linearly interpolates between this vector and another\n * \n * @param other - Target vector\n * @param t - Interpolation factor (0 to 1)\n * @returns New interpolated vector\n */\n public lerp(other: Vector2, t: number): Vector2 {\n return new Vector2(\n this.x + (other.x - this.x) * t,\n this.y + (other.y - this.y) * t\n );\n }\n\n /**\n * Checks if this vector equals another (with epsilon tolerance)\n * \n * @param other - Vector to compare\n * @param epsilon - Tolerance for comparison (default: 1e-5)\n * @returns True if vectors are approximately equal\n */\n public equals(other: Vector2, epsilon = 1e-5): boolean {\n return (\n Math.abs(this.x - other.x) < epsilon &&\n Math.abs(this.y - other.y) < epsilon\n );\n }\n\n /**\n * Returns a string representation of this vector\n * \n * @returns String representation\n */\n public toString(): string {\n return `Vector2(${this.x}, ${this.y})`;\n }\n\n /**\n * Static zero vector\n */\n static readonly ZERO = new Vector2(0, 0);\n\n /**\n * Static unit X vector\n */\n static readonly UNIT_X = new Vector2(1, 0);\n\n /**\n * Static unit Y vector\n */\n static readonly UNIT_Y = new Vector2(0, 1);\n}\n\n","import { Vector2 } from './Vector2';\n\n/**\n * Axis-Aligned Bounding Box (AABB)\n * \n * Represents a rectangular bounding box aligned with the coordinate axes.\n * Used for fast collision detection and spatial queries.\n * \n * @example\n * ```typescript\n * const box = new AABB(0, 0, 10, 10);\n * const point = new Vector2(5, 5);\n * if (box.contains(point)) {\n * // Point is inside the box\n * }\n * ```\n */\nexport class AABB {\n /**\n * Minimum X coordinate (left edge)\n */\n public minX: number;\n\n /**\n * Minimum Y coordinate (bottom edge)\n */\n public minY: number;\n\n /**\n * Maximum X coordinate (right edge)\n */\n public maxX: number;\n\n /**\n * Maximum Y coordinate (top edge)\n */\n public maxY: number;\n\n /**\n * Creates a new AABB\n * \n * @param minX - Minimum X coordinate\n * @param minY - Minimum Y coordinate\n * @param maxX - Maximum X coordinate\n * @param maxY - Maximum Y coordinate\n */\n constructor(minX: number, minY: number, maxX: number, maxY: number) {\n this.minX = minX;\n this.minY = minY;\n this.maxX = maxX;\n this.maxY = maxY;\n }\n\n /**\n * Creates an AABB from center and size\n * \n * @param centerX - Center X coordinate\n * @param centerY - Center Y coordinate\n * @param width - Width of the box\n * @param height - Height of the box\n * @returns New AABB\n */\n static fromCenterSize(\n centerX: number,\n centerY: number,\n width: number,\n height: number\n ): AABB {\n const halfWidth = width / 2;\n const halfHeight = height / 2;\n return new AABB(\n centerX - halfWidth,\n centerY - halfHeight,\n centerX + halfWidth,\n centerY + halfHeight\n );\n }\n\n /**\n * Creates an AABB from a center point and size\n * \n * @param center - Center point\n * @param width - Width of the box\n * @param height - Height of the box\n * @returns New AABB\n */\n static fromCenterSizeVector(center: Vector2, width: number, height: number): AABB {\n return AABB.fromCenterSize(center.x, center.y, width, height);\n }\n\n /**\n * Creates a copy of this AABB\n * \n * @returns New AABB with the same values\n */\n public clone(): AABB {\n return new AABB(this.minX, this.minY, this.maxX, this.maxY);\n }\n\n /**\n * Copies values from another AABB\n * \n * @param other - AABB to copy from\n * @returns This AABB for chaining\n */\n public copyFrom(other: AABB): AABB {\n this.minX = other.minX;\n this.minY = other.minY;\n this.maxX = other.maxX;\n this.maxY = other.maxY;\n return this;\n }\n\n /**\n * Gets the width of the AABB\n * \n * @returns Width\n */\n public getWidth(): number {\n return this.maxX - this.minX;\n }\n\n /**\n * Gets the height of the AABB\n * \n * @returns Height\n */\n public getHeight(): number {\n return this.maxY - this.minY;\n }\n\n /**\n * Gets the center point of the AABB\n * \n * @returns Center point\n */\n public getCenter(): Vector2 {\n return new Vector2(\n (this.minX + this.maxX) / 2,\n (this.minY + this.maxY) / 2\n );\n }\n\n /**\n * Gets the center X coordinate\n * \n * @returns Center X\n */\n public getCenterX(): number {\n return (this.minX + this.maxX) / 2;\n }\n\n /**\n * Gets the center Y coordinate\n * \n * @returns Center Y\n */\n public getCenterY(): number {\n return (this.minY + this.maxY) / 2;\n }\n\n /**\n * Gets the area of the AABB\n * \n * @returns Area\n */\n public getArea(): number {\n return this.getWidth() * this.getHeight();\n }\n\n /**\n * Checks if a point is inside this AABB\n * \n * @param x - Point X coordinate\n * @param y - Point Y coordinate\n * @returns True if point is inside\n */\n public containsPoint(x: number, y: number): boolean {\n return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;\n }\n\n /**\n * Checks if a vector point is inside this AABB\n * \n * @param point - Point to check\n * @returns True if point is inside\n */\n public contains(point: Vector2): boolean {\n return this.containsPoint(point.x, point.y);\n }\n\n /**\n * Checks if another AABB is completely inside this AABB\n * \n * @param other - AABB to check\n * @returns True if other AABB is inside\n */\n public containsAABB(other: AABB): boolean {\n return (\n this.minX <= other.minX &&\n this.minY <= other.minY &&\n this.maxX >= other.maxX &&\n this.maxY >= other.maxY\n );\n }\n\n /**\n * Checks if this AABB intersects with another AABB\n * \n * @param other - AABB to check intersection with\n * @returns True if AABBs intersect\n */\n public intersects(other: AABB): boolean {\n return !(\n this.maxX < other.minX ||\n this.minX > other.maxX ||\n this.maxY < other.minY ||\n this.minY > other.maxY\n );\n }\n\n /**\n * Calculates the intersection AABB with another AABB\n * \n * @param other - AABB to intersect with\n * @returns Intersection AABB, or null if no intersection\n */\n public intersection(other: AABB): AABB | null {\n if (!this.intersects(other)) {\n return null;\n }\n return new AABB(\n Math.max(this.minX, other.minX),\n Math.max(this.minY, other.minY),\n Math.min(this.maxX, other.maxX),\n Math.min(this.maxY, other.maxY)\n );\n }\n\n /**\n * Calculates the union AABB with another AABB\n * \n * @param other - AABB to union with\n * @returns Union AABB\n */\n public union(other: AABB): AABB {\n return new AABB(\n Math.min(this.minX, other.minX),\n Math.min(this.minY, other.minY),\n Math.max(this.maxX, other.maxX),\n Math.max(this.maxY, other.maxY)\n );\n }\n\n /**\n * Expands this AABB by a given amount in all directions\n * \n * @param amount - Amount to expand by\n * @returns New expanded AABB\n */\n public expand(amount: number): AABB {\n return new AABB(\n this.minX - amount,\n this.minY - amount,\n this.maxX + amount,\n this.maxY + amount\n );\n }\n\n /**\n * Expands this AABB by a given amount (in-place)\n * \n * @param amount - Amount to expand by\n * @returns This AABB for chaining\n */\n public expandInPlace(amount: number): AABB {\n this.minX -= amount;\n this.minY -= amount;\n this.maxX += amount;\n this.maxY += amount;\n return this;\n }\n\n /**\n * Translates this AABB by a given offset\n * \n * @param dx - X offset\n * @param dy - Y offset\n * @returns New translated AABB\n */\n public translate(dx: number, dy: number): AABB {\n return new AABB(\n this.minX + dx,\n this.minY + dy,\n this.maxX + dx,\n this.maxY + dy\n );\n }\n\n /**\n * Translates this AABB by a given offset (in-place)\n * \n * @param dx - X offset\n * @param dy - Y offset\n * @returns This AABB for chaining\n */\n public translateInPlace(dx: number, dy: number): AABB {\n this.minX += dx;\n this.minY += dy;\n this.maxX += dx;\n this.maxY += dy;\n return this;\n }\n\n /**\n * Checks if this AABB equals another (with epsilon tolerance)\n * \n * @param other - AABB to compare\n * @param epsilon - Tolerance for comparison (default: 1e-5)\n * @returns True if AABBs are approximately equal\n */\n public equals(other: AABB, epsilon = 1e-5): boolean {\n return (\n Math.abs(this.minX - other.minX) < epsilon &&\n Math.abs(this.minY - other.minY) < epsilon &&\n Math.abs(this.maxX - other.maxX) < epsilon &&\n Math.abs(this.maxY - other.maxY) < epsilon\n );\n }\n\n /**\n * Returns a string representation of this AABB\n * \n * @returns String representation\n */\n public toString(): string {\n return `AABB(${this.minX}, ${this.minY}, ${this.maxX}, ${this.maxY})`;\n }\n /**\n * Clamps a point to be inside the AABB\n * \n * @param point - Point to clamp\n * @returns Clamped point\n */\n public clamp(point: Vector2): Vector2 {\n return new Vector2(\n Math.max(this.minX, Math.min(this.maxX, point.x)),\n Math.max(this.minY, Math.min(this.maxY, point.y))\n );\n }\n}\n\n","/**\n * Core types and identifiers\n */\n\n/**\n * Unique identifier for entities (UUID v4 format)\n */\nexport type UUID = string;\n\n/**\n * Numeric identifier for entities (for performance)\n */\nexport type EntityId = number;\n\n/**\n * Entity state flags\n */\nexport enum EntityState {\n /** Static entity (does not move) */\n Static = 1 << 0,\n /** Dynamic entity (affected by forces) */\n Dynamic = 1 << 1,\n /** Sleeping entity (inactive, not updated) */\n Sleeping = 1 << 2,\n /** Kinematic entity (moved manually, but can collide) */\n Kinematic = 1 << 3,\n}\n\n","/**\n * UUID generation utilities\n * \n * Generates UUID v4 for entity identification.\n * Deterministic version can be used for testing.\n */\n\n/**\n * Generates a random UUID v4\n * \n * @returns UUID string\n * \n * @example\n * ```typescript\n * const id = generateUUID(); // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateUUID(): string {\n // UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generates a deterministic UUID from a seed\n * \n * Simple hash-based UUID for testing and deterministic scenarios.\n * Not cryptographically secure.\n * \n * @param seed - Seed value for generation\n * @returns Deterministic UUID string\n */\nexport function generateDeterministicUUID(seed: number): string {\n // Simple hash function for deterministic UUIDs\n let hash = seed;\n hash = ((hash << 5) - hash) + seed;\n hash = hash & hash; // Convert to 32-bit integer\n \n const hex = Math.abs(hash).toString(16).padStart(8, '0');\n return `00000000-0000-4000-8000-${hex.padStart(12, '0')}`;\n}\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { UUID, EntityState } from '../core/types';\nimport { generateUUID } from '../utils/uuid';\nimport { CollisionInfo } from '../collision/Collider';\n\nconst MOVEMENT_EPSILON = 1e-3;\nconst MOVEMENT_EPSILON_SQ = MOVEMENT_EPSILON * MOVEMENT_EPSILON;\nconst DIRECTION_CHANGE_THRESHOLD = 1.0;\nconst DIRECTION_CHANGE_THRESHOLD_SQ = DIRECTION_CHANGE_THRESHOLD * DIRECTION_CHANGE_THRESHOLD;\n\nexport type CardinalDirection = 'idle' | 'up' | 'down' | 'left' | 'right';\n\n/**\n * Collision filter function type\n * \n * A filter that determines whether a collision should be processed between two entities.\n * Return `true` to allow the collision, `false` to ignore it.\n * \n * @param self - The entity that owns this filter\n * @param other - The other entity in the collision\n * @returns `true` if collision should occur, `false` to ignore\n * \n * @example\n * ```typescript\n * // Filter that ignores collisions with entities tagged as \"ghost\"\n * const ghostFilter: CollisionFilter = (self, other) => {\n * return !(other as any).isGhost;\n * };\n * ```\n */\nexport type CollisionFilter = (self: Entity, other: Entity) => boolean;\n\n/**\n * Resolution filter function type\n * \n * A filter that determines whether a collision should be **resolved** (blocking) \n * or just **detected** (notification only).\n * \n * Unlike CollisionFilter which prevents detection entirely, ResolutionFilter\n * allows collision events to fire while optionally skipping the physical blocking.\n * \n * Return `true` to resolve the collision (entities block each other),\n * `false` to skip resolution (entities pass through but events still fire).\n * \n * @param self - The entity that owns this filter\n * @param other - The other entity in the collision\n * @returns `true` to resolve (block), `false` to skip resolution (pass through)\n * \n * @example\n * ```typescript\n * // Filter that allows passing through players but still triggers events\n * const throughPlayerFilter: ResolutionFilter = (self, other) => {\n * const otherOwner = (other as any).owner;\n * if (otherOwner?.type === 'player') {\n * return false; // Pass through but events still fire\n * }\n * return true; // Block other entities\n * };\n * ```\n */\nexport type ResolutionFilter = (self: Entity, other: Entity) => boolean;\n\n/**\n * Configuration options for creating an entity\n */\nexport interface EntityConfig {\n /** Initial position */\n position?: Vector2 | { x: number; y: number };\n /** Initial velocity */\n velocity?: Vector2 | { x: number; y: number };\n /** Initial rotation in radians */\n rotation?: number;\n /** Initial angular velocity in radians per second */\n angularVelocity?: number;\n /** Mass of the entity (0 or Infinity for static/immovable entities) */\n mass?: number;\n /** Radius for circular collider */\n radius?: number;\n /** Width for AABB collider */\n width?: number;\n /** Height for AABB collider */\n height?: number;\n /** Capsule collider configuration (if used) */\n capsule?: {\n radius: number;\n height: number;\n };\n /** Enable continuous collision detection (CCD) */\n continuous?: boolean;\n /** Entity state flags */\n state?: EntityState;\n /** Restitution (bounciness) coefficient (0-1) */\n restitution?: number;\n /** Friction coefficient */\n friction?: number;\n /** Linear damping (0-1, higher = more damping) */\n linearDamping?: number;\n /** Angular damping (0-1, higher = more damping) */\n angularDamping?: number;\n /** Maximum linear velocity */\n maxLinearVelocity?: number;\n /** Maximum angular velocity */\n maxAngularVelocity?: number;\n /** Custom UUID (auto-generated if not provided) */\n uuid?: UUID;\n /** Collision mask (bitmask for collision filtering) */\n collisionMask?: number;\n /** Collision category (bitmask) */\n collisionCategory?: number;\n}\n\n/**\n * Physical entity in the physics world\n * \n * Represents a dynamic or static object that can be affected by forces,\n * collisions, and other physical interactions.\n * \n * ## Creating Static Obstacles\n * \n * To create immovable obstacles (walls, decorations), set `mass` to `0` or `Infinity`.\n * This makes the entity static - it will block other entities but cannot be pushed.\n * \n * @example\n * ```typescript\n * // Dynamic entity (player, movable object)\n * const player = new Entity({\n * position: { x: 0, y: 0 },\n * radius: 10,\n * mass: 1,\n * velocity: { x: 5, y: 0 }\n * });\n * \n * // Static obstacle (wall, tree, decoration)\n * const wall = new Entity({\n * position: { x: 100, y: 0 },\n * width: 20,\n * height: 100,\n * mass: Infinity // or mass: 0\n * });\n * \n * player.applyForce(new Vector2(10, 0));\n * ```\n */\nexport class Entity {\n /**\n * Unique identifier (UUID)\n */\n public readonly uuid: UUID;\n\n /**\n * Position in world space\n */\n public position: Vector2;\n\n /**\n * Linear velocity\n */\n public velocity: Vector2;\n\n /**\n * Rotation in radians\n */\n public rotation: number;\n\n /**\n * Angular velocity in radians per second\n */\n public angularVelocity: number;\n\n /**\n * Mass (0 or Infinity means infinite mass / static)\n */\n public mass: number;\n\n /**\n * Inverse mass (cached for performance, 0 if mass is 0 or Infinity)\n */\n public invMass: number;\n\n /**\n * Radius for circular collider (if used)\n */\n public radius: number;\n\n /**\n * Width for AABB collider (if used)\n */\n public width: number;\n\n /**\n * Height for AABB collider (if used)\n */\n public height: number;\n\n /**\n * Capsule collider configuration (if used)\n */\n public capsule?: {\n radius: number;\n height: number;\n };\n\n /**\n * Enable continuous collision detection (CCD)\n */\n public continuous: boolean;\n\n /**\n * Entity state flags\n */\n public state: EntityState;\n\n /**\n * Restitution (bounciness) coefficient (0-1)\n */\n public restitution: number;\n\n /**\n * Friction coefficient\n */\n public friction: number;\n\n /**\n * Linear damping (0-1)\n */\n public linearDamping: number;\n\n /**\n * Angular damping (0-1)\n */\n public angularDamping: number;\n\n /**\n * Maximum linear velocity\n */\n public maxLinearVelocity: number;\n\n /**\n * Maximum angular velocity\n */\n public maxAngularVelocity: number;\n\n /**\n * Accumulated force for this frame\n */\n public force: Vector2;\n\n /**\n * Accumulated torque for this frame\n */\n public torque: number;\n\n /**\n * Collision mask (bitmask)\n */\n public collisionMask: number;\n\n /**\n * Collision category (bitmask)\n */\n public collisionCategory: number;\n\n /**\n * Time since last movement (for sleep detection)\n */\n public timeSinceMovement: number;\n\n /**\n * Threshold for sleep detection (seconds of inactivity)\n */\n public sleepThreshold: number;\n\n /**\n * Current tile coordinates (x, y)\n */\n public currentTile: Vector2;\n\n private collisionEnterHandlers: Set<EntityCollisionHandler>;\n private collisionExitHandlers: Set<EntityCollisionHandler>;\n private positionSyncHandlers: Set<EntityPositionSyncHandler>;\n private directionSyncHandlers: Set<EntityDirectionSyncHandler>;\n private movementChangeHandlers: Set<EntityMovementChangeHandler>;\n private enterTileHandlers: Set<EntityTileHandler>;\n private leaveTileHandlers: Set<EntityTileHandler>;\n private canEnterTileHandlers: Set<EntityCanEnterTileHandler>;\n private collisionFilterHandlers: Set<CollisionFilter>;\n private resolutionFilterHandlers: Set<ResolutionFilter>;\n private wasMoving: boolean;\n private lastCardinalDirection: CardinalDirection = 'idle';\n\n /**\n * Creates a new entity\n * \n * @param config - Entity configuration\n */\n constructor(config: EntityConfig = {}) {\n // Generate UUID if not provided\n this.uuid = config.uuid ?? generateUUID();\n\n // Position and velocity\n if (config.position instanceof Vector2) {\n this.position = config.position.clone();\n } else if (config.position) {\n this.position = new Vector2(config.position.x, config.position.y);\n } else {\n this.position = new Vector2(0, 0);\n }\n\n this.currentTile = new Vector2(0, 0); // Will be updated by World\n\n if (config.velocity instanceof Vector2) {\n this.velocity = config.velocity.clone();\n } else if (config.velocity) {\n this.velocity = new Vector2(config.velocity.x, config.velocity.y);\n } else {\n this.velocity = new Vector2(0, 0);\n }\n\n // Rotation\n this.rotation = config.rotation ?? 0;\n this.angularVelocity = config.angularVelocity ?? 0;\n\n // Mass\n this.mass = config.mass ?? 1;\n this.invMass = this.mass > 0 ? 1 / this.mass : 0;\n\n // Collider dimensions\n this.radius = config.radius ?? 0;\n this.width = config.width ?? 0;\n this.height = config.height ?? 0;\n if (config.capsule !== undefined) {\n this.capsule = config.capsule;\n }\n this.continuous = config.continuous ?? false;\n\n // State\n this.state = config.state ?? EntityState.Dynamic;\n\n // Material properties\n this.restitution = config.restitution ?? 0.2;\n this.friction = config.friction ?? 0.3;\n this.linearDamping = config.linearDamping ?? 0.01;\n this.angularDamping = config.angularDamping ?? 0.01;\n\n // Velocity limits\n this.maxLinearVelocity = config.maxLinearVelocity ?? Infinity;\n this.maxAngularVelocity = config.maxAngularVelocity ?? Infinity;\n\n // Forces\n this.force = new Vector2(0, 0);\n this.torque = 0;\n\n // Collision filtering\n this.collisionMask = config.collisionMask ?? 0xffffffff;\n this.collisionCategory = config.collisionCategory ?? 0x00000001;\n\n // Sleep detection\n this.timeSinceMovement = 0;\n this.sleepThreshold = 0.5; // 0.5 seconds of inactivity\n\n // Event handlers\n this.collisionEnterHandlers = new Set();\n this.collisionExitHandlers = new Set();\n this.positionSyncHandlers = new Set();\n this.directionSyncHandlers = new Set();\n this.positionSyncHandlers = new Set();\n this.directionSyncHandlers = new Set();\n this.movementChangeHandlers = new Set();\n this.enterTileHandlers = new Set();\n this.leaveTileHandlers = new Set();\n this.canEnterTileHandlers = new Set();\n this.collisionFilterHandlers = new Set();\n this.resolutionFilterHandlers = new Set();\n\n // Initialize movement state\n this.wasMoving = this.velocity.lengthSquared() > MOVEMENT_EPSILON_SQ;\n }\n\n /**\n * Registers a handler fired when this entity starts colliding with another one.\n *\n * - **Purpose:** offer per-entity collision hooks without subscribing to the global event system.\n * - **Design:** lightweight Set-based listeners returning an unsubscribe closure to keep GC pressure low.\n *\n * @param handler - Collision enter listener\n * @returns Unsubscribe closure\n * @example\n * ```typescript\n * const unsubscribe = entity.onCollisionEnter(({ other }) => {\n * console.log('Started colliding with', other.uuid);\n * });\n * ```\n */\n public onCollisionEnter(handler: EntityCollisionHandler): () => void {\n this.collisionEnterHandlers.add(handler);\n return () => this.collisionEnterHandlers.delete(handler);\n }\n\n /**\n * Registers a handler fired when this entity stops colliding with another one.\n *\n * - **Purpose:** detect collision separation at the entity level for local gameplay reactions.\n * - **Design:** mirrors `onCollisionEnter` with identical lifecycle management semantics.\n *\n * @param handler - Collision exit listener\n * @returns Unsubscribe closure\n * @example\n * ```typescript\n * const unsubscribe = entity.onCollisionExit(({ other }) => {\n * console.log('Stopped colliding with', other.uuid);\n * });\n * ```\n */\n public onCollisionExit(handler: EntityCollisionHandler): () => void {\n this.collisionExitHandlers.add(handler);\n return () => this.collisionExitHandlers.delete(handler);\n }\n\n /**\n * Registers a handler fired when the entity position changes (x, y).\n *\n * - **Purpose:** synchronize position changes for logging, rendering, network sync, etc.\n * - **Design:** lightweight Set-based listeners returning an unsubscribe closure to keep GC pressure low.\n *\n * @param handler - Position change listener\n * @returns Unsubscribe closure\n * @example\n * ```typescript\n * const unsubscribe = entity.onPositionChange(({ x, y }) => {\n * console.log('Position changed to', x, y);\n * // Update rendering, sync network, etc.\n * });\n * ```\n */\n public onPositionChange(handler: EntityPositionSyncHandler): () => void {\n this.positionSyncHandlers.add(handler);\n return () => this.positionSyncHandlers.delete(handler);\n }\n\n /**\n * Registers a handler fired when the entity direction changes.\n *\n * - **Purpose:** synchronize direction changes for logging, rendering, network sync, etc.\n * - **Design:** lightweight Set-based listeners returning an unsubscribe closure to keep GC pressure low.\n *\n * @param handler - Direction change listener\n * @returns Unsubscribe closure\n * @example\n * ```typescript\n * const unsubscribe = entity.onDirectionChange(({ direction, cardinalDirection }) => {\n * console.log('Direction changed to', cardinalDirection);\n * // Update rendering, sync network, etc.\n * });\n * ```\n */\n public onDirectionChange(handler: EntityDirectionSyncHandler): () => void {\n this.directionSyncHandlers.add(handler);\n return () => this.directionSyncHandlers.delete(handler);\n }\n\n /**\n * Manually notifies that the position has changed.\n *\n * - **Purpose:** allow external code to trigger position sync hooks when position is modified directly.\n * - **Design:** can be called after direct position modifications (e.g., `entity.position.set()`).\n *\n * @example\n * ```typescript\n * entity.position.set(100, 200);\n * entity.notifyPositionChange(); // Trigger sync hooks\n * ```\n */\n public notifyPositionChange(): void {\n if (this.positionSyncHandlers.size === 0) {\n return;\n }\n\n const payload: EntityPositionSyncEvent = {\n entity: this,\n x: this.position.x,\n y: this.position.y,\n };\n\n for (const handler of this.positionSyncHandlers) {\n handler(payload);\n }\n }\n\n /**\n * Manually notifies that the direction has changed.\n *\n * - **Purpose:** allow external code to trigger direction sync hooks when direction is modified directly.\n * - **Design:** computes direction from velocity and cardinal direction.\n *\n * @example\n * ```typescript\n * entity.velocity.set(5, 0);\n * entity.notifyDirectionChange(); // Trigger sync hooks\n * ```\n */\n public notifyDirectionChange(): void {\n const isMoving = this.velocity.lengthSquared() > DIRECTION_CHANGE_THRESHOLD_SQ;\n const direction = isMoving ? this.velocity.clone().normalize() : new Vector2(0, 0);\n const cardinalDirection = this.computeCardinalDirection(direction);\n\n // Update state to support hysteresis\n if (cardinalDirection !== 'idle') {\n this.lastCardinalDirection = cardinalDirection;\n }\n\n if (this.directionSyncHandlers.size === 0) {\n return;\n }\n\n const payload: EntityDirectionSyncEvent = {\n entity: this,\n direction,\n cardinalDirection,\n };\n\n for (const handler of this.directionSyncHandlers) {\n handler(payload);\n }\n }\n\n /**\n * Gets the current cardinal direction.\n * \n * This value is updated whenever `notifyDirectionChange()` is called (e.g. by `setVelocity`).\n * It includes hysteresis logic to prevent rapid direction flipping during collisions.\n * \n * @returns The current cardinal direction ('up', 'down', 'left', 'right', 'idle')\n * \n * @example\n * ```typescript\n * const dir = entity.cardinalDirection;\n * if (dir === 'left') {\n * // Render left-facing sprite\n * }\n * ```\n */\n public get cardinalDirection(): CardinalDirection {\n return this.lastCardinalDirection;\n }\n\n /**\n * Registers a handler fired when the entity movement state changes (moving/stopped).\n *\n * - **Purpose:** detect when an entity starts or stops moving for gameplay reactions, animations, or network sync.\n * - **Design:** lightweight Set-based listeners returning an unsubscribe closure to keep GC pressure low.\n * - **Movement detection:** uses `MOVEMENT_EPSILON` threshold to determine if entity is moving.\n * - **Intensity:** provides the movement speed magnitude to allow fine-grained animation control (e.g., walk vs run).\n *\n * @param handler - Movement state change listener\n * @returns Unsubscribe closure\n * @example\n * ```typescript\n * const unsubscribe = entity.onMovementChange(({ isMoving, intensity }) => {\n * console.log('Entity is', isMoving ? 'moving' : 'stopped', 'at speed', intensity);\n * // Update animations based on intensity\n * if (isMoving && intensity > 100) {\n * // Fast movement - use run animation\n * } else if (isMoving) {\n * // Slow movement - use walk animation\n * }\n * });\n * ```\n */\n public onMovementChange(handler: EntityMovementChangeHandler): () => void {\n this.movementChangeHandlers.add(handler);\n return () => this.movementChangeHandlers.delete(handler);\n }\n\n /**\n * Manually notifies that the movement state has changed.\n *\n * - **Purpose:** allow external code to trigger movement state sync hooks when velocity is modified directly.\n * - **Design:** checks if movement state (moving/stopped) has changed and notifies handlers with movement intensity.\n * - **Intensity:** calculated as the magnitude of the velocity vector (speed in pixels per second).\n *\n * @example\n * ```typescript\n * entity.velocity.set(5, 0);\n * entity.notifyMovementChange(); // Trigger sync hooks if state changed\n * ```\n */\n public notifyMovementChange(): void {\n const isMoving = this.velocity.lengthSquared() > MOVEMENT_EPSILON_SQ;\n const intensity = this.velocity.length(); // Movement speed magnitude\n\n if (this.movementChangeHandlers.size === 0) {\n // Still update wasMoving even if no handlers to track state correctly\n this.wasMoving = isMoving;\n return;\n }\n\n // Only notify if state actually changed\n if (isMoving !== this.wasMoving) {\n this.wasMoving = isMoving;\n\n const payload: EntityMovementChangeEvent = {\n entity: this,\n isMoving,\n intensity,\n };\n\n for (const handler of this.movementChangeHandlers) {\n handler(payload);\n }\n } else {\n // Update wasMoving even if state didn't change to keep it in sync\n this.wasMoving = isMoving;\n }\n }\n\n /**\n * Registers a handler fired when the entity enters a new tile.\n * \n * @param handler - Tile enter listener\n * @returns Unsubscribe closure\n */\n public onEnterTile(handler: EntityTileHandler): () => void {\n this.enterTileHandlers.add(handler);\n return () => this.enterTileHandlers.delete(handler);\n }\n\n /**\n * Registers a handler fired when the entity leaves a tile.\n * \n * @param handler - Tile leave listener\n * @returns Unsubscribe closure\n */\n public onLeaveTile(handler: EntityTileHandler): () => void {\n this.leaveTileHandlers.add(handler);\n return () => this.leaveTileHandlers.delete(handler);\n }\n\n /**\n * Registers a handler to check if the entity can enter a tile.\n * If any handler returns false, the entity cannot enter.\n * \n * @param handler - Can enter tile listener\n * @returns Unsubscribe closure\n */\n public canEnterTile(handler: EntityCanEnterTileHandler): () => void {\n this.canEnterTileHandlers.add(handler);\n return () => this.canEnterTileHandlers.delete(handler);\n }\n\n /**\n * @internal\n * Notifies that the entity has entered a tile.\n */\n public notifyEnterTile(x: number, y: number): void {\n if (this.enterTileHandlers.size === 0) return;\n const event: EntityTileEvent = { entity: this, x, y };\n for (const handler of this.enterTileHandlers) {\n handler(event);\n }\n }\n\n /**\n * @internal\n * Notifies that the entity has left a tile.\n */\n public notifyLeaveTile(x: number, y: number): void {\n if (this.leaveTileHandlers.size === 0) return;\n const event: EntityTileEvent = { entity: this, x, y };\n for (const handler of this.leaveTileHandlers) {\n handler(event);\n }\n }\n\n /**\n * @internal\n * Checks if the entity can enter a tile.\n */\n public checkCanEnterTile(x: number, y: number): boolean {\n if (this.canEnterTileHandlers.size === 0) return true;\n const event: EntityTileEvent = { entity: this, x, y };\n for (const handler of this.canEnterTileHandlers) {\n if (handler(event) === false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Applies a force to the entity\n * \n * Force is accumulated and applied during integration.\n * \n * @param force - Force vector to apply\n * @returns This entity for chaining\n * \n * @example\n * ```typescript\n * entity.applyForce(new Vector2(10, 0)); // Push right\n * ```\n */\n public applyForce(force: Vector2): Entity {\n if (this.isStatic() || this.isSleeping()) {\n return this;\n }\n this.force.addInPlace(force);\n return this;\n }\n\n /**\n * Applies a force at a specific point (creates torque)\n * \n * @param force - Force vector to apply\n * @param point - Point of application in world space\n * @returns This entity for chaining\n */\n public applyForceAtPoint(force: Vector2, point: Vector2): Entity {\n if (this.isStatic() || this.isSleeping()) {\n return this;\n }\n this.force.addInPlace(force);\n\n // Calculate torque: r × F\n const r = point.sub(this.position);\n this.torque += r.cross(force);\n\n return this;\n }\n\n /**\n * Applies an impulse (instantaneous change in velocity)\n * \n * @param impulse - Impulse vector\n * @returns This entity for chaining\n * \n * @example\n * ```typescript\n * entity.applyImpulse(new Vector2(5, 0)); // Instant push\n * ```\n */\n public applyImpulse(impulse: Vector2): Entity {\n if (this.isStatic() || this.isSleeping()) {\n return this;\n }\n this.velocity.addInPlace(impulse.mul(this.invMass));\n this.notifyMovementChange();\n this.notifyDirectionChange();\n return this;\n }\n\n /**\n * Applies an angular impulse (instantaneous change in angular velocity)\n * \n * @param impulse - Angular impulse value\n * @returns This entity for chaining\n */\n public applyAngularImpulse(impulse: number): Entity {\n if (this.isStatic() || this.isSleeping()) {\n return this;\n }\n // Simplified: assume moment of inertia = mass * radius^2\n const momentOfInertia = this.mass * this.radius * this.radius;\n if (momentOfInertia > 0) {\n this.angularVelocity += impulse / momentOfInertia;\n }\n return this;\n }\n\n /**\n * Teleports the entity to a new position\n * \n * @param position - New position\n * @returns This entity for chaining\n */\n public teleport(position: Vector2 | { x: number; y: number }): Entity {\n if (position instanceof Vector2) {\n this.position.copyFrom(position);\n } else {\n this.position.set(position.x, position.y);\n }\n this.wakeUp();\n this.notifyPositionChange();\n return this;\n }\n\n /**\n * Sets the velocity directly\n * \n * @param velocity - New velocity\n * @returns This entity for chaining\n */\n public setVelocity(velocity: Vector2 | { x: number; y: number }): Entity {\n const oldVelocity = this.velocity.clone();\n\n if (velocity instanceof Vector2) {\n this.velocity.copyFrom(velocity);\n } else {\n this.velocity.set(velocity.x, velocity.y);\n }\n this.wakeUp();\n\n // Check if direction changed\n const oldDirection = oldVelocity.lengthSquared() > MOVEMENT_EPSILON_SQ\n ? oldVelocity.clone().normalize()\n : new Vector2(0, 0);\n const newDirection = this.velocity.lengthSquared() > MOVEMENT_EPSILON_SQ\n ? this.velocity.clone().normalize()\n : new Vector2(0, 0);\n\n const oldCardinal = this.computeCardinalDirection(oldDirection);\n const newCardinal = this.computeCardinalDirection(newDirection);\n\n if (oldCardinal !== newCardinal || Math.abs(oldDirection.dot(newDirection) - 1) > 0.01) {\n this.notifyDirectionChange();\n }\n\n // Check if movement state changed\n this.notifyMovementChange();\n\n return this;\n }\n\n /**\n * Freezes the entity (makes it static)\n * \n * @returns This entity for chaining\n */\n public freeze(): Entity {\n this.state = EntityState.Static;\n this.velocity.set(0, 0);\n this.angularVelocity = 0;\n this.force.set(0, 0);\n this.torque = 0;\n this.notifyMovementChange();\n return this;\n }\n\n /**\n * Unfreezes the entity (makes it dynamic)\n * \n * @returns This entity for chaining\n */\n public unfreeze(): Entity {\n if (this.mass > 0) {\n this.state = EntityState.Dynamic;\n }\n return this;\n }\n\n /**\n * Puts the entity to sleep (stops updating)\n * \n * @returns This entity for chaining\n */\n public sleep(): Entity {\n if (!this.isStatic()) {\n this.state |= EntityState.Sleeping;\n this.velocity.set(0, 0);\n this.angularVelocity = 0;\n this.force.set(0, 0);\n this.torque = 0;\n this.notifyMovementChange();\n }\n return this;\n }\n\n /**\n * Wakes up the entity (resumes updating)\n * \n * @returns This entity for chaining\n */\n public wakeUp(): Entity {\n this.state &= ~EntityState.Sleeping;\n this.timeSinceMovement = 0;\n return this;\n }\n\n /**\n * Checks if the entity is static\n * \n * An entity is considered static if:\n * - It has the Static state flag, OR\n * - It has infinite mass (mass = Infinity), OR\n * - It has zero inverse mass (invMass = 0)\n * \n * @returns True if static\n */\n public isStatic(): boolean {\n return (this.state & EntityState.Static) !== 0 || this.invMass === 0;\n }\n\n /**\n * Checks if the entity is dynamic\n * \n * @returns True if dynamic\n */\n public isDynamic(): boolean {\n return (this.state & EntityState.Dynamic) !== 0 && this.mass > 0;\n }\n\n /**\n * Checks if the entity is sleeping\n * \n * @returns True if sleeping\n */\n public isSleeping(): boolean {\n return (this.state & EntityState.Sleeping) !== 0;\n }\n\n /**\n * Checks if the entity is kinematic\n * \n * @returns True if kinematic\n */\n public isKinematic(): boolean {\n return (this.state & EntityState.Kinematic) !== 0;\n }\n\n /**\n * Resets accumulated forces and torques\n * \n * Called at the start of each physics step.\n */\n public clearForces(): void {\n this.force.set(0, 0);\n this.torque = 0;\n }\n\n /**\n * Stops all movement immediately\n * \n * Completely stops the entity's movement by:\n * - Setting velocity to zero\n * - Setting angular velocity to zero\n * - Clearing accumulated forces and torques\n * - Waking up the entity if it was sleeping\n * - Notifying movement state change\n * \n * Unlike `freeze()`, this method keeps the entity dynamic and does not\n * change its state. It's useful for stopping movement when changing maps,\n * teleporting, or when you need to halt an entity without making it static.\n * \n * @returns This entity for chaining\n * \n * @example\n * ```ts\n * // Stop movement when changing maps\n * if (mapChanged) {\n * entity.stopMovement();\n * }\n * \n * // Stop movement after teleporting\n * entity.position.set(100, 200);\n * entity.stopMovement();\n * \n * // Stop movement when player dies\n * if (player.isDead()) {\n * playerEntity.stopMovement();\n * }\n * ```\n */\n public stopMovement(): Entity {\n this.velocity.set(0, 0);\n this.angularVelocity = 0;\n this.clearForces();\n this.wakeUp();\n this.notifyMovementChange();\n this.notifyDirectionChange();\n return this;\n }\n\n /**\n * Clamps velocities to maximum values\n */\n public clampVelocities(): void {\n const speed = this.velocity.length();\n if (speed > this.maxLinearVelocity) {\n this.velocity.normalizeInPlace().mulInPlace(this.maxLinearVelocity);\n }\n\n if (Math.abs(this.angularVelocity) > this.maxAngularVelocity) {\n this.angularVelocity = Math.sign(this.angularVelocity) * this.maxAngularVelocity;\n }\n }\n\n /**\n * Adds a collision filter to this entity\n * \n * Collision filters allow dynamic, conditional collision filtering beyond static bitmasks.\n * Each filter is called when checking if this entity can collide with another.\n * If any filter returns `false`, the collision is ignored.\n * \n * This enables scenarios like:\n * - Players passing through other players (`throughOtherPlayer`)\n * - Entities passing through all characters (`through`)\n * - Custom game-specific collision rules\n * \n * @param filter - Function that returns `true` to allow collision, `false` to ignore\n * @returns Unsubscribe function to remove the filter\n * \n * @example\n * ```typescript\n * // Allow entity to pass through other players\n * const unsubscribe = entity.addCollisionFilter((self, other) => {\n * const otherOwner = (other as any).owner;\n * if (otherOwner?.type === 'player') {\n * return false; // No collision with players\n * }\n * return true; // Collide with everything else\n * });\n * \n * // Later, remove the filter\n * unsubscribe();\n * ```\n */\n public addCollisionFilter(filter: CollisionFilter): () => void {\n this.collisionFilterHandlers.add(filter);\n return () => this.collisionFilterHandlers.delete(filter);\n }\n\n /**\n * Checks if this entity can collide with another entity\n * \n * First checks collision masks (bitmask filtering), then executes all registered\n * collision filters. If any filter returns `false`, the collision is ignored.\n * \n * @param other - Other entity to check\n * @returns True if collision is possible\n */\n public canCollideWith(other: Entity): boolean {\n // Check collision masks first (fast path)\n const categoryA = this.collisionCategory;\n const maskA = this.collisionMask;\n const categoryB = other.collisionCategory;\n const maskB = other.collisionMask;\n\n if ((categoryA & maskB) === 0 || (categoryB & maskA) === 0) {\n return false;\n }\n\n // Check collision filters on this entity\n for (const filter of this.collisionFilterHandlers) {\n if (!filter(this, other)) {\n return false;\n }\n }\n\n // Check collision filters on the other entity\n for (const filter of other.collisionFilterHandlers) {\n if (!filter(other, this)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Adds a resolution filter to this entity\n * \n * Resolution filters determine whether a collision should be **resolved** (blocking)\n * or just **detected** (notification only). Unlike collision filters which prevent\n * detection entirely, resolution filters allow collision events to fire while\n * optionally skipping the physical blocking.\n * \n * This enables scenarios like:\n * - Players passing through other players but still triggering touch events\n * - Entities passing through characters but still calling onPlayerTouch hooks\n * - Ghost mode where collisions are detected but not resolved\n * \n * @param filter - Function that returns `true` to resolve (block), `false` to skip\n * @returns Unsubscribe function to remove the filter\n * \n * @example\n * ```typescript\n * // Allow entity to pass through players but still trigger events\n * const unsubscribe = entity.addResolutionFilter((self, other) => {\n * const otherOwner = (other as any).owner;\n * if (otherOwner?.type === 'player') {\n * return false; // Pass through but events still fire\n * }\n * return true; // Block other entities\n * });\n * \n * // Later, remove the filter\n * unsubscribe();\n * ```\n */\n public addResolutionFilter(filter: ResolutionFilter): () => void {\n this.resolutionFilterHandlers.add(filter);\n return () => this.resolutionFilterHandlers.delete(filter);\n }\n\n /**\n * Checks if this entity should resolve (block) a collision with another entity\n * \n * This is called by the CollisionResolver to determine if the collision should\n * result in physical blocking or just notification.\n * \n * @param other - Other entity to check\n * @returns True if collision should be resolved (blocking), false to pass through\n */\n public shouldResolveCollisionWith(other: Entity): boolean {\n // Check resolution filters on this entity\n for (const filter of this.resolutionFilterHandlers) {\n if (!filter(this, other)) {\n return false;\n }\n }\n\n // Check resolution filters on the other entity\n for (const filter of other.resolutionFilterHandlers) {\n if (!filter(other, this)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @internal\n *\n * Notifies the entity that a collision has started.\n *\n * @param collision - Collision information shared by the world\n * @param other - The counterpart entity\n */\n public notifyCollisionEnter(collision: CollisionInfo, other: Entity): void {\n if (this.collisionEnterHandlers.size === 0) {\n return;\n }\n\n const payload: EntityCollisionEvent = {\n entity: this,\n other,\n collision,\n };\n\n for (const handler of this.collisionEnterHandlers) {\n handler(payload);\n }\n }\n\n /**\n * @internal\n *\n * Notifies the entity that a collision has ended.\n *\n * @param collision - Collision information stored before separation\n * @param other - The counterpart entity\n */\n public notifyCollisionExit(collision: CollisionInfo, other: Entity): void {\n if (this.collisionExitHandlers.size === 0) {\n return;\n }\n\n const payload: EntityCollisionEvent = {\n entity: this,\n other,\n collision,\n };\n\n for (const handler of this.collisionExitHandlers) {\n handler(payload);\n }\n }\n\n\n private computeCardinalDirection(direction: Vector2): CardinalDirection {\n if (direction.lengthSquared() <= MOVEMENT_EPSILON_SQ) {\n return 'idle';\n }\n\n // If we were idle, just return the strongest direction without bias\n if (this.lastCardinalDirection === 'idle') {\n const absX = Math.abs(direction.x);\n const absY = Math.abs(direction.y);\n if (absX >= absY) {\n return direction.x >= 0 ? 'right' : 'left';\n }\n return direction.y >= 0 ? 'down' : 'up';\n }\n\n // Check for 180-degree flips (Bounce protection)\n // If the new direction is strictly opposite to the last one, we require a higher velocity\n // to accept the change. This filters out collision rebounds.\n const isOpposite =\n (this.lastCardinalDirection === 'left' && direction.x > 0.5) ||\n (this.lastCardinalDirection === 'right' && direction.x < -0.5) ||\n (this.lastCardinalDirection === 'up' && direction.y > 0.5) ||\n (this.lastCardinalDirection === 'down' && direction.y < -0.5);\n\n const speedSq = this.velocity.lengthSquared();\n\n // Threshold to accept a 180-degree turn (avoid jitter on bounce)\n // We expect a \"real\" turn to have some acceleration or accumulated velocity\n if (isOpposite && speedSq < 100.0) { // Speed < 10\n return this.lastCardinalDirection;\n }\n\n const absX = Math.abs(direction.x);\n const absY = Math.abs(direction.y);\n const bias = 2.0; // Strong bias to keep current direction\n\n // Hysteresis: favor current axis if we have a valid last direction\n if (['left', 'right'].includes(this.lastCardinalDirection)) {\n // Currently horizontal: stick to it unless vertical is significantly stronger\n // AND vertical component has meaningful speed (prevents slide when blocked)\n if (absY > absX * bias) {\n // Check if the \"new\" vertical movement is actually significant\n // e.g. if we are blocked Horizontally (x=0), absY will win even if it's 0.0001 without this check\n if (Math.abs(this.velocity.y) > 5.0) {\n return direction.y >= 0 ? 'down' : 'up';\n }\n }\n // Default: keep horizontal orientation, just update sign if needed (and not filtered by opposite check)\n // If we are here, it means we didn't switch axis, and we didn't trigger the \"Opposite\" guard above.\n // However, if we are \"blocked\" (velocity very low), we should probably not even flip sign.\n if (speedSq > 1.0) {\n return direction.x >= 0 ? 'right' : 'left';\n }\n return this.lastCardinalDirection;\n } else {\n // Currently vertical: stick to it unless horizontal is significantly stronger\n if (absX > absY * bias) {\n if (Math.abs(this.velocity.x) > 5.0) {\n return direction.x >= 0 ? 'right' : 'left';\n }\n }\n if (speedSq > 1.0) {\n return direction.y >= 0 ? 'down' : 'up';\n }\n return this.lastCardinalDirection;\n }\n }\n\n /**\n * Creates a copy of this entity\n * \n * @returns New entity with copied properties\n */\n public clone(): Entity {\n const entity = new Entity({\n position: this.position.clone(),\n velocity: this.velocity.clone(),\n rotation: this.rotation,\n angularVelocity: this.angularVelocity,\n mass: this.mass,\n radius: this.radius,\n width: this.width,\n height: this.height,\n state: this.state,\n restitution: this.restitution,\n friction: this.friction,\n linearDamping: this.linearDamping,\n angularDamping: this.angularDamping,\n maxLinearVelocity: this.maxLinearVelocity,\n maxAngularVelocity: this.maxAngularVelocity,\n collisionMask: this.collisionMask,\n collisionCategory: this.collisionCategory,\n uuid: this.uuid,\n });\n return entity;\n }\n}\n\nexport interface EntityCollisionEvent {\n entity: Entity;\n other: Entity;\n collision: CollisionInfo;\n}\n\nexport type EntityCollisionHandler = (event: EntityCollisionEvent) => void;\n\n\nexport interface EntityPositionSyncEvent {\n entity: Entity;\n x: number;\n y: number;\n}\n\nexport type EntityPositionSyncHandler = (event: EntityPositionSyncEvent) => void;\n\nexport interface EntityDirectionSyncEvent {\n entity: Entity;\n direction: Vector2;\n cardinalDirection: CardinalDirection;\n}\n\nexport type EntityDirectionSyncHandler = (event: EntityDirectionSyncEvent) => void;\n\nexport interface EntityMovementChangeEvent {\n entity: Entity;\n isMoving: boolean;\n /** Movement intensity (speed magnitude) */\n intensity: number;\n}\n\nexport type EntityMovementChangeHandler = (event: EntityMovementChangeEvent) => void;\n\nexport interface EntityTileEvent {\n entity: Entity;\n x: number;\n y: number;\n}\n\nexport type EntityTileHandler = (event: EntityTileEvent) => void;\nexport type EntityCanEnterTileHandler = (event: EntityTileEvent) => boolean;\n\n\n","import { Entity } from './Entity';\nimport { Vector2 } from '../core/math/Vector2';\n\n/**\n * Integration method type\n */\nexport enum IntegrationMethod {\n /** Semi-implicit Euler (default, stable and fast) */\n Euler = 'euler',\n /** Verlet integration (more stable, better energy conservation) */\n Verlet = 'verlet',\n}\n\n/**\n * Configuration for physics integration\n */\nexport interface IntegratorConfig {\n /** Integration method to use */\n method?: IntegrationMethod;\n /** Time step (usually 1/60 for 60 FPS) */\n deltaTime: number;\n /** Gravity vector (optional, for top-down usually zero) */\n gravity?: Vector2;\n}\n\n/**\n * Physics integrator\n * \n * Handles numerical integration of physical entities.\n * Supports multiple integration methods for different stability requirements.\n * \n * @example\n * ```typescript\n * const integrator = new Integrator({ deltaTime: 1/60 });\n * integrator.integrate(entity);\n * ```\n */\nexport class Integrator {\n private config: IntegratorConfig;\n private gravity: Vector2;\n\n /**\n * Creates a new integrator\n * \n * @param config - Integrator configuration\n */\n constructor(config: IntegratorConfig) {\n this.config = config;\n this.gravity = config.gravity?.clone() ?? new Vector2(0, 0);\n }\n\n /**\n * Integrates an entity's motion\n * \n * Updates position, velocity, and rotation based on forces and torques.\n * \n * @param entity - Entity to integrate\n */\n public integrate(entity: Entity): void {\n if (entity.isStatic() || entity.isSleeping()) {\n return;\n }\n\n switch (this.config.method ?? IntegrationMethod.Euler) {\n case IntegrationMethod.Euler:\n this.integrateEuler(entity);\n break;\n case IntegrationMethod.Verlet:\n this.integrateVerlet(entity);\n break;\n }\n }\n\n /**\n * Semi-implicit Euler integration\n * \n * Updates velocity first, then position. More stable than explicit Euler.\n * \n * @param entity - Entity to integrate\n */\n private integrateEuler(entity: Entity): void {\n const dt = this.config.deltaTime;\n const invMass = entity.invMass;\n\n // Apply gravity if entity has mass\n if (invMass > 0) {\n entity.force.addInPlace(this.gravity.mul(entity.mass));\n }\n\n // Update linear velocity: v = v + a * dt\n // a = F / m\n const acceleration = entity.force.mul(invMass);\n entity.velocity.addInPlace(acceleration.mul(dt));\n\n // Apply linear damping\n const linearDampingFactor = 1 - entity.linearDamping;\n entity.velocity.mulInPlace(linearDampingFactor);\n\n // Clamp velocity\n entity.clampVelocities();\n\n // Check if movement state changed (after damping/clamping)\n entity.notifyMovementChange();\n\n // Note: We don't call notifyDirectionChange() here because direction changes\n // should only be triggered by intentional velocity changes (setVelocity, applyImpulse),\n // not by physics integration steps which include collision corrections.\n\n // Update position: x = x + v * dt\n const oldPosition = entity.position.clone();\n entity.position.addInPlace(entity.velocity.mul(dt));\n\n // Notify position change if position actually changed\n const delta = entity.position.sub(oldPosition);\n if (delta.lengthSquared() > 1e-6) {\n entity.notifyPositionChange();\n }\n\n // Update angular velocity: ω = ω + α * dt\n // α = τ / I (simplified: I = m * r²)\n const momentOfInertia = entity.mass * entity.radius * entity.radius;\n if (momentOfInertia > 0) {\n const angularAcceleration = entity.torque / momentOfInertia;\n entity.angularVelocity += angularAcceleration * dt;\n }\n\n // Apply angular damping\n const angularDampingFactor = 1 - entity.angularDamping;\n entity.angularVelocity *= angularDampingFactor;\n\n // Clamp angular velocity\n if (Math.abs(entity.angularVelocity) > entity.maxAngularVelocity) {\n entity.angularVelocity = Math.sign(entity.angularVelocity) * entity.maxAngularVelocity;\n }\n\n // Update rotation: θ = θ + ω * dt\n entity.rotation += entity.angularVelocity * dt;\n\n // Normalize rotation to [-π, π]\n while (entity.rotation > Math.PI) {\n entity.rotation -= 2 * Math.PI;\n }\n while (entity.rotation < -Math.PI) {\n entity.rotation += 2 * Math.PI;\n }\n\n // Clear forces for next frame\n entity.clearForces();\n }\n\n /**\n * Verlet integration\n * \n * More stable than Euler, better energy conservation.\n * Requires storing previous position.\n * \n * @param entity - Entity to integrate\n */\n private integrateVerlet(entity: Entity): void {\n const dt = this.config.deltaTime;\n const dt2 = dt * dt;\n const invMass = entity.invMass;\n\n // Apply gravity\n if (invMass > 0) {\n entity.force.addInPlace(this.gravity.mul(entity.mass));\n }\n\n // Calculate acceleration\n const acceleration = entity.force.mul(invMass);\n\n // Verlet: x(t+dt) = 2*x(t) - x(t-dt) + a*dt²\n // For first step, we need previous position (stored in a temporary property)\n // Since we don't store previous position, we use velocity-based approximation:\n // x(t+dt) = x(t) + v(t)*dt + 0.5*a*dt²\n const newPosition = entity.position\n .add(entity.velocity.mul(dt))\n .add(acceleration.mul(0.5 * dt2));\n\n // Update velocity: v(t+dt) = (x(t+dt) - x(t)) / dt\n const newVelocity = newPosition.sub(entity.position).div(dt);\n\n // Apply damping\n const linearDampingFactor = 1 - entity.linearDamping;\n newVelocity.mulInPlace(linearDampingFactor);\n\n // Update entity\n const oldPosition = entity.position.clone();\n entity.position = newPosition;\n entity.velocity = newVelocity;\n\n // Clamp velocity\n entity.clampVelocities();\n\n // Check if movement state changed (after damping/clamping)\n entity.notifyMovementChange();\n\n // Note: We don't call notifyDirectionChange() here because direction changes\n // should only be triggered by intentional velocity changes (setVelocity, applyImpulse),\n // not by physics integration steps which include collision corrections.\n\n // Notify position change if position actually changed\n const delta = entity.position.sub(oldPosition);\n if (delta.lengthSquared() > 1e-6) {\n entity.notifyPositionChange();\n }\n\n // Angular motion (simplified, using Euler for angular)\n const momentOfInertia = entity.mass * entity.radius * entity.radius;\n if (momentOfInertia > 0) {\n const angularAcceleration = entity.torque / momentOfInertia;\n entity.angularVelocity += angularAcceleration * dt;\n }\n\n const angularDampingFactor = 1 - entity.angularDamping;\n entity.angularVelocity *= angularDampingFactor;\n\n if (Math.abs(entity.angularVelocity) > entity.maxAngularVelocity) {\n entity.angularVelocity = Math.sign(entity.angularVelocity) * entity.maxAngularVelocity;\n }\n\n entity.rotation += entity.angularVelocity * dt;\n\n // Normalize rotation\n while (entity.rotation > Math.PI) {\n entity.rotation -= 2 * Math.PI;\n }\n while (entity.rotation < -Math.PI) {\n entity.rotation += 2 * Math.PI;\n }\n\n // Clear forces\n entity.clearForces();\n }\n\n /**\n * Updates the gravity vector\n * \n * @param gravity - New gravity vector\n */\n public setGravity(gravity: Vector2): void {\n this.gravity.copyFrom(gravity);\n }\n\n /**\n * Gets the current gravity vector\n * \n * @returns Gravity vector\n */\n public getGravity(): Vector2 {\n return this.gravity.clone();\n }\n}\n\n","import { AABB } from '../core/math/AABB';\nimport { Vector2 } from '../core/math/Vector2';\nimport { Entity } from '../physics/Entity';\nimport { Collider, CollisionInfo, ContactPoint } from './Collider';\nimport { CircleCollider } from './CircleCollider';\nimport { Ray, RaycastHit } from './Ray';\n\n/**\n * AABB (Axis-Aligned Bounding Box) collider implementation\n * \n * Represents a rectangular collision shape aligned with the axes.\n * \n * @example\n * ```typescript\n * const entity = new Entity({ position: { x: 0, y: 0 }, width: 10, height: 10 });\n * const collider = new AABBCollider(entity);\n * ```\n */\nexport class AABBCollider implements Collider {\n private entity: Entity;\n\n /**\n * Creates a new AABB collider\n * \n * @param entity - Entity this collider belongs to\n */\n constructor(entity: Entity) {\n this.entity = entity;\n }\n\n /**\n * Gets the AABB bounds\n * \n * @returns AABB\n */\n public getBounds(): AABB {\n const center = this.entity.position;\n const halfWidth = this.entity.width / 2;\n const halfHeight = this.entity.height / 2;\n\n return new AABB(\n center.x - halfWidth,\n center.y - halfHeight,\n center.x + halfWidth,\n center.y + halfHeight\n );\n }\n\n /**\n * @inheritdoc\n */\n public testCollision(other: Collider): CollisionInfo | null {\n if (other instanceof CircleCollider) {\n // Circle-AABB collision is handled by CircleCollider\n const collision = other.testCollision(this);\n if (collision) {\n // Swap entities and reverse normal\n return {\n entityA: collision.entityB,\n entityB: collision.entityA,\n contacts: collision.contacts.map((c) => ({\n point: c.point,\n normal: c.normal.mul(-1),\n depth: c.depth,\n })),\n normal: collision.normal.mul(-1),\n depth: collision.depth,\n };\n }\n return null;\n } else if (other instanceof AABBCollider) {\n return this.testAABBAABB(other);\n }\n return null;\n }\n\n /**\n * Tests collision with another AABB\n * \n * @param other - Other AABB collider\n * @returns Collision info or null\n */\n private testAABBAABB(other: AABBCollider): CollisionInfo | null {\n const aabbA = this.getBounds();\n const aabbB = other.getBounds();\n\n if (!aabbA.intersects(aabbB)) {\n return null;\n }\n\n // Calculate intersection\n const intersection = aabbA.intersection(aabbB);\n if (!intersection) {\n return null;\n }\n\n // Calculate penetration depth and normal\n const overlapX = Math.min(\n aabbA.maxX - aabbB.minX,\n aabbB.maxX - aabbA.minX\n );\n const overlapY = Math.min(\n aabbA.maxY - aabbB.minY,\n aabbB.maxY - aabbA.minY\n );\n\n let normal: Vector2;\n let depth: number;\n\n if (overlapX < overlapY) {\n // Collision on X axis\n depth = overlapX;\n normal = aabbA.getCenterX() < aabbB.getCenterX()\n ? new Vector2(1, 0)\n : new Vector2(-1, 0);\n } else {\n // Collision on Y axis\n depth = overlapY;\n normal = aabbA.getCenterY() < aabbB.getCenterY()\n ? new Vector2(0, 1)\n : new Vector2(0, -1);\n }\n\n const contactPoint = intersection.getCenter();\n\n return {\n entityA: this.entity,\n entityB: other.entity,\n contacts: [\n {\n point: contactPoint,\n normal,\n depth,\n },\n ],\n normal,\n depth,\n };\n }\n\n /**\n * @inheritdoc\n */\n public getContactPoints(other: Collider): ContactPoint[] {\n const collision = this.testCollision(other);\n return collision?.contacts ?? [];\n }\n\n /**\n * @inheritdoc\n */\n public getEntity(): Entity {\n return this.entity;\n }\n\n /**\n * @inheritdoc\n */\n public raycast(ray: Ray): RaycastHit | null {\n const bounds = this.getBounds();\n const tMin = (bounds.minX - ray.origin.x) / ray.direction.x;\n const tMax = (bounds.maxX - ray.origin.x) / ray.direction.x;\n const tymin = (bounds.minY - ray.origin.y) / ray.direction.y;\n const tymax = (bounds.maxY - ray.origin.y) / ray.direction.y;\n\n const t1 = Math.min(tMin, tMax);\n const t2 = Math.max(tMin, tMax);\n const t3 = Math.min(tymin, tymax);\n const t4 = Math.max(tymin, tymax);\n\n const tNear = Math.max(t1, t3);\n const tFar = Math.min(t2, t4);\n\n if (tNear > tFar || tFar < 0) {\n return null;\n }\n\n if (tNear > ray.length) {\n return null;\n }\n\n const t = tNear < 0 ? tFar : tNear;\n if (t < 0) return null; // Should be covered by tFar < 0 check but safe\n\n const point = ray.getPoint(t);\n\n // Calculate normal\n let normal = new Vector2(0, 0);\n if (Math.abs(point.x - bounds.minX) < 1e-5) normal.set(-1, 0);\n else if (Math.abs(point.x - bounds.maxX) < 1e-5) normal.set(1, 0);\n else if (Math.abs(point.y - bounds.minY) < 1e-5) normal.set(0, -1);\n else if (Math.abs(point.y - bounds.maxY) < 1e-5) normal.set(0, 1);\n\n return {\n entity: this.entity,\n point,\n normal,\n distance: t,\n };\n }\n}\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport { Entity } from '../physics/Entity';\nimport { Collider, CollisionInfo, ContactPoint } from './Collider';\nimport { AABBCollider } from './AABBCollider';\nimport { Ray, RaycastHit } from './Ray';\n\n/**\n * Circle collider implementation\n * \n * Represents a circular collision shape.\n * \n * @example\n * ```typescript\n * const entity = new Entity({ position: { x: 0, y: 0 }, radius: 10 });\n * const collider = new CircleCollider(entity);\n * ```\n */\nexport class CircleCollider implements Collider {\n private entity: Entity;\n\n /**\n * Creates a new circle collider\n * \n * @param entity - Entity this collider belongs to\n */\n constructor(entity: Entity) {\n this.entity = entity;\n }\n\n /**\n * Gets the radius of the circle\n * \n * @returns Radius\n */\n public getRadius(): number {\n return this.entity.radius;\n }\n\n /**\n * Gets the center position of the circle\n * \n * @returns Center position\n */\n public getCenter(): Vector2 {\n return this.entity.position;\n }\n\n /**\n * @inheritdoc\n */\n public getBounds(): AABB {\n const radius = this.entity.radius;\n const center = this.entity.position;\n return new AABB(\n center.x - radius,\n center.y - radius,\n center.x + radius,\n center.y + radius\n );\n }\n\n /**\n * @inheritdoc\n */\n public testCollision(other: Collider): CollisionInfo | null {\n if (other instanceof CircleCollider) {\n return this.testCircleCircle(other);\n } else if (other instanceof AABBCollider) {\n return this.testCircleAABB(other);\n }\n return null;\n }\n\n /**\n * Tests collision with another circle\n * \n * @param other - Other circle collider\n * @returns Collision info or null\n */\n private testCircleCircle(other: CircleCollider): CollisionInfo | null {\n const centerA = this.getCenter();\n const centerB = other.getCenter();\n const radiusA = this.getRadius();\n const radiusB = other.getRadius();\n\n const distance = centerA.distanceTo(centerB);\n const minDistance = radiusA + radiusB;\n\n if (distance >= minDistance) {\n return null; // No collision\n }\n\n const depth = minDistance - distance;\n let normal: Vector2;\n\n if (distance < 1e-5) {\n // Circles are at the same position, use arbitrary normal\n normal = new Vector2(1, 0);\n } else {\n normal = centerB.sub(centerA).normalize();\n }\n\n const contactPoint = centerA.add(normal.mul(radiusA));\n\n return {\n entityA: this.entity,\n entityB: other.entity,\n contacts: [\n {\n point: contactPoint,\n normal,\n depth,\n },\n ],\n normal,\n depth,\n };\n }\n\n /**\n * Tests collision with an AABB\n * \n * @param other - AABB collider\n * @returns Collision info or null\n */\n private testCircleAABB(other: AABBCollider): CollisionInfo | null {\n const circleCenter = this.getCenter();\n const circleRadius = this.getRadius();\n const aabb = other.getBounds();\n\n // Find closest point on AABB to circle center\n const closestX = Math.max(aabb.minX, Math.min(circleCenter.x, aabb.maxX));\n const closestY = Math.max(aabb.minY, Math.min(circleCenter.y, aabb.maxY));\n\n const distanceSq = (circleCenter.x - closestX) ** 2 + (circleCenter.y - closestY) ** 2;\n\n if (distanceSq > circleRadius * circleRadius) {\n return null; // No collision\n }\n\n const distance = Math.sqrt(distanceSq);\n const depth = circleRadius - distance;\n\n let normal: Vector2;\n if (distance < 1e-5) {\n // Circle center is inside AABB\n // Find the closest edge\n const distToLeft = circleCenter.x - aabb.minX;\n const distToRight = aabb.maxX - circleCenter.x;\n const distToBottom = circleCenter.y - aabb.minY;\n const distToTop = aabb.maxY - circleCenter.y;\n\n const minDist = Math.min(distToLeft, distToRight, distToBottom, distToTop);\n\n if (minDist === distToLeft) {\n normal = new Vector2(-1, 0);\n } else if (minDist === distToRight) {\n normal = new Vector2(1, 0);\n } else if (minDist === distToBottom) {\n normal = new Vector2(0, -1);\n } else {\n normal = new Vector2(0, 1);\n }\n } else {\n normal = new Vector2(closestX - circleCenter.x, closestY - circleCenter.y).normalize();\n }\n\n const contactPoint = new Vector2(closestX, closestY);\n\n return {\n entityA: this.entity,\n entityB: other.getEntity(),\n contacts: [\n {\n point: contactPoint,\n normal,\n depth,\n },\n ],\n normal,\n depth,\n };\n }\n\n /**\n * @inheritdoc\n */\n public getContactPoints(other: Collider): ContactPoint[] {\n const collision = this.testCollision(other);\n return collision?.contacts ?? [];\n }\n\n /**\n * @inheritdoc\n */\n public getEntity(): Entity {\n return this.entity;\n }\n\n /**\n * @inheritdoc\n */\n public raycast(ray: Ray): RaycastHit | null {\n const center = this.getCenter();\n const radius = this.getRadius();\n const m = ray.origin.sub(center);\n const b = m.dot(ray.direction);\n const c = m.dot(m) - radius * radius;\n\n // Exit if ray's origin is outside circle (c > 0) and ray is pointing away from circle (b > 0)\n if (c > 0 && b > 0) return null;\n\n const discr = b * b - c;\n\n // A negative discriminant corresponds to ray missing circle\n if (discr < 0) return null;\n\n // Ray now found to intersect circle, compute smallest t value of intersection\n let t = -b - Math.sqrt(discr);\n\n // If t is negative, ray started inside circle so clamp t to 0\n if (t < 0) t = 0;\n\n if (t > ray.length) return null;\n\n const point = ray.getPoint(t);\n const normal = point.sub(center).normalize();\n\n return {\n entity: this.entity,\n point,\n normal,\n distance: t,\n };\n }\n}\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport { Collider, CollisionInfo, ContactPoint } from './Collider';\nimport { Entity } from '../physics/Entity';\nimport { CircleCollider } from './CircleCollider';\nimport { AABBCollider } from './AABBCollider';\nimport { Ray, RaycastHit } from './Ray';\n\n/**\n * Capsule collider\n * \n * Represents a capsule shape (pill shape) defined by a line segment and a radius.\n * Useful for character controllers as it handles steps and slopes better than AABBs.\n */\nexport class CapsuleCollider implements Collider {\n constructor(private entity: Entity) { }\n\n public getBounds(): AABB {\n const { radius, height } = this.getCapsuleConfig();\n const pos = this.entity.position;\n\n // Vertical capsule for now (can be rotated later if needed)\n // Height is the total height. The line segment length is height - 2 * radius.\n // If height < 2 * radius, it's a sphere.\n\n const halfHeight = Math.max(0, height / 2 - radius);\n\n return new AABB(\n pos.x - radius,\n pos.y - halfHeight - radius,\n pos.x + radius,\n pos.y + halfHeight + radius\n );\n }\n\n public getEntity(): Entity {\n return this.entity;\n }\n\n public raycast(ray: Ray): RaycastHit | null {\n // Simplified: Raycast against the bounding AABB for now\n // A proper ray-capsule intersection is complex and maybe overkill for this task\n // But to be safe, let's check AABB first.\n const bounds = this.getBounds();\n\n // Check AABB intersection\n const tMin = (bounds.minX - ray.origin.x) / ray.direction.x;\n const tMax = (bounds.maxX - ray.origin.x) / ray.direction.x;\n const tymin = (bounds.minY - ray.origin.y) / ray.direction.y;\n const tymax = (bounds.maxY - ray.origin.y) / ray.direction.y;\n\n const t1 = Math.min(tMin, tMax);\n const t2 = Math.max(tMin, tMax);\n const t3 = Math.min(tymin, tymax);\n const t4 = Math.max(tymin, tymax);\n\n const tNear = Math.max(t1, t3);\n const tFar = Math.min(t2, t4);\n\n if (tNear > tFar || tFar < 0) return null;\n if (tNear > ray.length) return null;\n\n // If AABB is hit, we *should* check the capsule shape.\n // For this implementation, I'll return the AABB hit as an approximation.\n // TODO: Implement exact ray-capsule intersection\n\n const t = tNear < 0 ? tFar : tNear;\n if (t < 0) return null;\n\n const point = ray.getPoint(t);\n\n // Calculate normal (AABB normal)\n let normal = new Vector2(0, 0);\n if (Math.abs(point.x - bounds.minX) < 1e-5) normal.set(-1, 0);\n else if (Math.abs(point.x - bounds.maxX) < 1e-5) normal.set(1, 0);\n else if (Math.abs(point.y - bounds.minY) < 1e-5) normal.set(0, -1);\n else if (Math.abs(point.y - bounds.maxY) < 1e-5) normal.set(0, 1);\n\n return {\n entity: this.entity,\n point,\n normal,\n distance: t\n };\n }\n\n public testCollision(other: Collider): CollisionInfo | null {\n if (other instanceof CircleCollider) {\n return this.testCircle(other);\n } else if (other instanceof AABBCollider) {\n return this.testAABB(other);\n } else if (other instanceof CapsuleCollider) {\n return this.testCapsule(other);\n }\n\n // Double dispatch for other types\n return other.testCollision(this);\n }\n\n public getContactPoints(other: Collider): ContactPoint[] {\n // Simplified contact points for now\n const collision = this.testCollision(other);\n return collision ? collision.contacts : [];\n }\n\n private getCapsuleConfig(): { radius: number; height: number } {\n if (this.entity.capsule) {\n return this.entity.capsule;\n }\n // Fallback or error?\n return { radius: this.entity.radius || 10, height: this.entity.height || 30 };\n }\n\n private getSegment(): { a: Vector2; b: Vector2 } {\n const { radius, height } = this.getCapsuleConfig();\n const pos = this.entity.position;\n const halfSegment = Math.max(0, height / 2 - radius);\n\n return {\n a: new Vector2(pos.x, pos.y - halfSegment),\n b: new Vector2(pos.x, pos.y + halfSegment)\n };\n }\n\n private testCircle(circle: CircleCollider): CollisionInfo | null {\n const seg = this.getSegment();\n const circleCenter = circle.getCenter();\n const circleRadius = circle.getRadius();\n const capRadius = this.getCapsuleConfig().radius;\n\n const closest = this.closestPointOnSegment(seg.a, seg.b, circleCenter);\n const distSq = closest.distanceToSquared(circleCenter);\n const minDist = capRadius + circleRadius;\n\n if (distSq > minDist * minDist) {\n return null;\n }\n\n const dist = Math.sqrt(distSq);\n const normal = dist > 0 ? circleCenter.sub(closest).normalize() : new Vector2(1, 0);\n const depth = minDist - dist;\n\n return {\n entityA: this.entity,\n entityB: circle.getEntity(),\n\n // Convention: Normal points from A to B.\n // Here A is Capsule, B is Circle.\n // Vector from closest (on capsule) to center (circle) is B - A.\n // So normal should be (circleCenter - closest).normalized().\n // Wait, if I return normal, it should be the direction to push B out of A?\n // Usually normal points from A to B.\n // Let's stick to: normal points from A to B.\n contacts: [{\n point: closest.add(normal.mul(capRadius)),\n normal: normal,\n depth\n }],\n normal: normal,\n depth\n };\n }\n\n\n private testAABB(box: AABBCollider): CollisionInfo | null {\n const seg = this.getSegment();\n const capRadius = this.getCapsuleConfig().radius;\n const boxBounds = box.getBounds();\n\n // 1. Find closest point on segment to the box (clamped to box bounds)\n // Actually, simpler: closest point on segment to the box is hard.\n // Easier: Closest point on box to the segment.\n\n // We can treat this as: Distance between Segment and AABB.\n // Or: Expand AABB by radius and test against segment?\n // Expanding AABB by radius gives a rounded box.\n\n // Let's use a numerical approach or simplified feature test.\n // Find the closest point on the segment to the AABB center? No.\n\n // Correct approach:\n // The distance between a line segment and an AABB.\n // Clamp segment points to AABB?\n\n // Let's try: Closest point on segment to the AABB.\n // We can clamp the segment endpoints to the AABB, but that's not enough.\n\n // Alternative: Test segment against expanded AABB (Minkowski sum approach).\n // AABB expanded by radius is a rounded rectangle.\n // Test if segment intersects rounded rectangle.\n\n // Let's use a simpler heuristic for now:\n // 1. Clamp segment start/end to box?\n // 2. Find closest point on segment to box center?\n\n // Better:\n // Iterate Voronoi regions?\n\n // Let's go with: Closest point on AABB to the segment.\n // We can sample the segment? No.\n\n // Let's use the \"closest point on segment to point\" for the box center, \n // then clamp that point to the box?\n // Not exact but often close enough for games.\n\n const closestOnSeg = this.closestPointOnSegment(seg.a, seg.b, box.getBounds().getCenter());\n const closestOnBox = boxBounds.clamp(closestOnSeg);\n\n const distSq = closestOnSeg.distanceToSquared(closestOnBox);\n\n if (distSq > capRadius * capRadius) {\n return null;\n }\n\n const dist = Math.sqrt(distSq);\n const normal = dist > 0 ? closestOnBox.sub(closestOnSeg).normalize() : new Vector2(0, 1); // Fallback\n const depth = capRadius - dist;\n\n return {\n entityA: this.entity,\n entityB: box.getEntity(),\n contacts: [{\n point: closestOnBox,\n normal: normal,\n depth\n }],\n normal: normal,\n depth\n };\n }\n\n private testCapsule(other: CapsuleCollider): CollisionInfo | null {\n // Segment vs Segment distance\n const segA = this.getSegment();\n const segB = other.getSegment();\n const rA = this.getCapsuleConfig().radius;\n const rB = other.getCapsuleConfig().radius;\n\n // Closest points between two segments\n const { p1, p2 } = this.closestPointsSegmentSegment(segA.a, segA.b, segB.a, segB.b);\n\n const distSq = p1.distanceToSquared(p2);\n const minDist = rA + rB;\n\n if (distSq > minDist * minDist) {\n return null;\n }\n\n const dist = Math.sqrt(distSq);\n const normal = dist > 0 ? p2.sub(p1).normalize() : new Vector2(1, 0);\n const depth = minDist - dist;\n\n return {\n entityA: this.entity,\n entityB: other.getEntity(),\n contacts: [{\n point: p1.add(normal.mul(rA)),\n normal: normal,\n depth\n }],\n normal: normal,\n depth\n };\n }\n\n private closestPointOnSegment(a: Vector2, b: Vector2, p: Vector2): Vector2 {\n const ab = b.sub(a);\n const t = p.sub(a).dot(ab) / ab.dot(ab);\n return a.add(ab.mul(Math.max(0, Math.min(1, t))));\n }\n\n // http://geomalgorithms.com/a07-_distance.html\n private closestPointsSegmentSegment(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2): { p1: Vector2, p2: Vector2 } {\n const u = p2.sub(p1);\n const v = p4.sub(p3);\n const w = p1.sub(p3);\n const a = u.dot(u);\n const b = u.dot(v);\n const c = v.dot(v);\n const d = u.dot(w);\n const e = v.dot(w);\n const D = a * c - b * b;\n\n let sc, sN, sD = D;\n let tc, tN, tD = D;\n\n if (D < 1e-8) { // Parallel\n sN = 0.0;\n sD = 1.0;\n tN = e;\n tD = c;\n } else {\n sN = (b * e - c * d);\n tN = (a * e - b * d);\n if (sN < 0.0) {\n sN = 0.0;\n tN = e;\n tD = c;\n } else if (sN > sD) {\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n\n if (tN < 0.0) {\n tN = 0.0;\n if (-d < 0.0) sN = 0.0;\n else if (-d > a) sN = sD;\n else {\n sN = -d;\n sD = a;\n }\n } else if (tN > tD) {\n tN = tD;\n if ((-d + b) < 0.0) sN = 0;\n else if ((-d + b) > a) sN = sD;\n else {\n sN = (-d + b);\n sD = a;\n }\n }\n\n sc = (Math.abs(sN) < 1e-8 ? 0.0 : sN / sD);\n tc = (Math.abs(tN) < 1e-8 ? 0.0 : tN / tD);\n\n return {\n p1: p1.add(u.mul(sc)),\n p2: p3.add(v.mul(tc))\n };\n }\n}\n","import { AABB } from '../core/math/AABB';\nimport { Vector2 } from '../core/math/Vector2';\nimport { Entity } from '../physics/Entity';\nimport { Collider, CollisionInfo, ContactPoint } from './Collider';\nimport { AABBCollider } from './AABBCollider';\nimport { CircleCollider } from './CircleCollider';\nimport { Ray, RaycastHit } from './Ray';\n\n/**\n * Configuration for polygon colliders\n */\nexport interface PolygonConfig {\n /** Vertices for a single convex polygon (local space) */\n vertices?: Vector2[];\n /** If true, `vertices` are guaranteed convex and counter-clockwise */\n isConvex?: boolean;\n /**\n * Convex parts for concave shapes (list of convex polygons, local space)\n * If provided, `vertices` is ignored.\n */\n parts?: Vector2[][];\n}\n\n/**\n * Weak registry to attach polygon configurations to entities\n */\nexport const entityToPolygonConfig: WeakMap<Entity, PolygonConfig> = new WeakMap();\n\n/**\n * Assigns a polygon collider configuration to an existing entity.\n * The entity will use this collider when `createCollider` is invoked.\n *\n * @param entity - Target entity\n * @param config - Polygon configuration\n * @example\n * ```typescript\n * const e = new Entity({ position: { x: 0, y: 0 } });\n * assignPolygonCollider(e, { vertices: [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], isConvex: true });\n * ```\n */\nexport function assignPolygonCollider(entity: Entity, config: PolygonConfig): void {\n entityToPolygonConfig.set(entity, config);\n}\n\n/**\n * Polygon collider implementation (convex via SAT; concave via convex parts)\n *\n * Design notes (in English):\n * - Vertices are defined in local space (centered on entity.position) and rotated by entity.rotation at query time.\n * - Concave shapes are supported by providing pre-decomposed convex `parts`. The collider iterates pairs of convex parts.\n * - Narrow-phase uses SAT (Separating Axis Theorem) on all candidate axes from both polygons.\n * - Contact point is approximated from the overlap normal and polygon centroid for performance and stability.\n *\n * @example\n * ```typescript\n * const e = new Entity({ position: { x: 0, y: 0 } });\n * assignPolygonCollider(e, { vertices: [new Vector2(0, 0), new Vector2(2, 0), new Vector2(1, 2)], isConvex: true });\n * const collider = new PolygonCollider(e);\n * ```\n */\nexport class PolygonCollider implements Collider {\n private entity: Entity;\n private convexParts: Vector2[][]; // local-space convex polygons\n\n constructor(entity: Entity) {\n this.entity = entity;\n const cfg = entityToPolygonConfig.get(entity);\n if (!cfg) {\n this.convexParts = [];\n return;\n }\n if (cfg.parts && cfg.parts.length > 0) {\n this.convexParts = cfg.parts.map((p) => p.slice());\n } else if (cfg.vertices && cfg.vertices.length >= 3) {\n this.convexParts = [cfg.vertices.slice()];\n } else {\n this.convexParts = [];\n }\n }\n\n public getEntity(): Entity {\n return this.entity;\n }\n\n public getBounds(): AABB {\n const rotation = this.entity.rotation;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n\n for (const part of this.convexParts) {\n for (const v of part) {\n const x = v.x * cos - v.y * sin + this.entity.position.x;\n const y = v.x * sin + v.y * cos + this.entity.position.y;\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n }\n\n if (minX === Number.POSITIVE_INFINITY) {\n // Empty polygon: return a zero-sized AABB at entity position\n minX = maxX = this.entity.position.x;\n minY = maxY = this.entity.position.y;\n }\n\n return new AABB(minX, minY, maxX, maxY);\n }\n\n public getContactPoints(other: Collider): ContactPoint[] {\n const info = this.testCollision(other);\n return info ? info.contacts : [];\n }\n\n public testCollision(other: Collider): CollisionInfo | null {\n if (other instanceof CircleCollider) {\n return this.testPolygonCircle(other);\n }\n if (other instanceof AABBCollider) {\n return this.testPolygonAABB(other);\n }\n if (other instanceof PolygonCollider) {\n return this.testPolygonPolygon(other);\n }\n return null;\n }\n\n private testPolygonAABB(other: AABBCollider): CollisionInfo | null {\n // Convert AABB to a convex polygon and reuse polygon-polygon SAT\n const b = other.getBounds();\n const halfW = (b.maxX - b.minX) / 2;\n const halfH = (b.maxY - b.minY) / 2;\n const center = new Vector2((b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2);\n const aabbPolyLocal = [\n new Vector2(-halfW, -halfH),\n new Vector2(halfW, -halfH),\n new Vector2(halfW, halfH),\n new Vector2(-halfW, halfH),\n ];\n const tempEntity = new Entity({ position: center, rotation: 0, mass: 0 });\n entityToPolygonConfig.set(tempEntity, { vertices: aabbPolyLocal, isConvex: true });\n const tempPoly = new PolygonCollider(tempEntity);\n const result = this.testPolygonPolygon(tempPoly);\n if (!result) return null;\n // Remap entityB to actual AABB's entity\n return {\n entityA: result.entityA === tempEntity ? this.entity : result.entityA,\n entityB: other.getEntity(),\n contacts: result.contacts,\n normal: result.normal,\n depth: result.depth,\n };\n }\n\n private testPolygonCircle(other: CircleCollider): CollisionInfo | null {\n // For each convex part, find closest distance from circle center to polygon edges\n let bestInfo: CollisionInfo | null = null;\n const center = other.getCenter();\n const r = other.getRadius();\n\n for (const part of this.getWorldParts()) {\n // Find the closest point on polygon to the circle center\n let minDistSq = Number.POSITIVE_INFINITY;\n let closestPoint: Vector2 | null = null;\n\n for (let i = 0; i < part.length; i++) {\n const a = part[i];\n const b = part[(i + 1) % part.length];\n if (!a || !b) continue;\n const cp = closestPointOnSegment(a, b, center);\n const dsq = center.distanceToSquared(cp);\n if (dsq < minDistSq) {\n minDistSq = dsq;\n closestPoint = cp;\n }\n }\n\n if (!closestPoint) continue;\n const dist = Math.sqrt(minDistSq);\n if (dist <= r) {\n const normal = dist > 1e-6 ? center.sub(closestPoint).normalize() : new Vector2(1, 0);\n const depth = r - dist;\n const info: CollisionInfo = {\n entityA: this.entity,\n entityB: other.getEntity(),\n contacts: [{ point: closestPoint, normal, depth }],\n normal,\n depth,\n };\n // Return the deepest collision among parts\n if (!bestInfo || info.depth > bestInfo.depth) bestInfo = info;\n }\n }\n\n return bestInfo;\n }\n\n private testPolygonPolygon(other: PolygonCollider): CollisionInfo | null {\n let bestDepth = Number.POSITIVE_INFINITY;\n let bestAxis: Vector2 | null = null;\n let flipNormal = false;\n\n // Test all pairs of convex parts\n const partsA = this.getWorldParts();\n const partsB = other.getWorldParts();\n\n let collided = false;\n for (const a of partsA) {\n for (const b of partsB) {\n const axes = gatherSATAxes(a, b);\n let overlapDepth = Number.POSITIVE_INFINITY;\n let axisForPair: Vector2 | null = null;\n for (const axis of axes) {\n const projA = projectOntoAxis(a, axis);\n const projB = projectOntoAxis(b, axis);\n const overlap = intervalOverlap(projA.min, projA.max, projB.min, projB.max);\n if (overlap <= 0) {\n // Separating axis found: no collision for this pair\n overlapDepth = -1;\n break;\n }\n if (overlap < overlapDepth) {\n overlapDepth = overlap;\n axisForPair = axis;\n }\n }\n if (overlapDepth > 0 && axisForPair) {\n collided = true;\n if (overlapDepth < bestDepth) {\n bestDepth = overlapDepth;\n bestAxis = axisForPair;\n // Heuristic: direction from centroidA to centroidB\n const cA = polygonCentroid(a);\n const cB = polygonCentroid(b);\n flipNormal = cA.sub(cB).dot(bestAxis) > 0; // if axis points from B->A, flip\n }\n }\n }\n }\n\n if (!collided || !bestAxis) return null;\n\n const normal = flipNormal ? bestAxis.mul(-1) : bestAxis.clone();\n const depth = bestDepth;\n\n // Approximate a contact point at the surface of A along the collision normal\n const centroidA = polygonCentroid(partsA[0]!);\n const contactPoint = centroidA.add(normal.mul(0.0));\n\n return {\n entityA: this.entity,\n entityB: other.getEntity(),\n contacts: [{ point: contactPoint, normal, depth }],\n normal,\n depth,\n };\n }\n\n /**\n * @inheritdoc\n */\n public raycast(ray: Ray): RaycastHit | null {\n // 1. Broad phase: check AABB\n const bounds = this.getBounds();\n // Simple AABB check (can reuse AABB logic or just check if ray intersects AABB)\n // We can create a temp AABB collider or just do the math.\n // Let's do a quick check.\n const tMin = (bounds.minX - ray.origin.x) / ray.direction.x;\n const tMax = (bounds.maxX - ray.origin.x) / ray.direction.x;\n const tymin = (bounds.minY - ray.origin.y) / ray.direction.y;\n const tymax = (bounds.maxY - ray.origin.y) / ray.direction.y;\n\n const t1 = Math.min(tMin, tMax);\n const t2 = Math.max(tMin, tMax);\n const t3 = Math.min(tymin, tymax);\n const t4 = Math.max(tymin, tymax);\n\n const tNear = Math.max(t1, t3);\n const tFar = Math.min(t2, t4);\n\n if (tNear > tFar || tFar < 0) return null;\n if (tNear > ray.length) return null;\n\n let closestHit: RaycastHit | null = null;\n\n // 2. Check all convex parts\n const parts = this.getWorldParts();\n for (const part of parts) {\n for (let i = 0; i < part.length; i++) {\n const p1 = part[i];\n const p2 = part[(i + 1) % part.length];\n\n if (!p1 || !p2) continue;\n\n const hit = this.rayCastSegment(ray, p1, p2);\n if (hit) {\n if (!closestHit || hit.distance < closestHit.distance) {\n closestHit = hit;\n }\n }\n }\n }\n\n return closestHit;\n }\n\n private rayCastSegment(ray: Ray, p1: Vector2, p2: Vector2): RaycastHit | null {\n const v1 = ray.origin;\n const v2 = ray.origin.add(ray.direction);\n const v3 = p1;\n const v4 = p2;\n\n const den = (v1.x - v2.x) * (v3.y - v4.y) - (v1.y - v2.y) * (v3.x - v4.x);\n if (den === 0) return null;\n\n const t = ((v1.x - v3.x) * (v3.y - v4.y) - (v1.y - v3.y) * (v3.x - v4.x)) / den;\n const u = -((v1.x - v2.x) * (v1.y - v3.y) - (v1.y - v2.y) * (v1.x - v3.x)) / den;\n\n if (t >= 0 && t <= ray.length && u >= 0 && u <= 1) {\n const point = new Vector2(\n v1.x + t * (v2.x - v1.x),\n v1.y + t * (v2.y - v1.y)\n );\n\n // Normal is perpendicular to the segment\n const segmentDir = p2.sub(p1).normalize();\n let normal = new Vector2(-segmentDir.y, segmentDir.x);\n\n // Ensure normal points against the ray\n if (normal.dot(ray.direction) > 0) {\n normal = normal.mul(-1);\n }\n\n return {\n entity: this.entity,\n point,\n normal,\n distance: t,\n };\n }\n return null;\n }\n\n private getWorldParts(): Vector2[][] {\n const rotation = this.entity.rotation;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const px = this.entity.position.x;\n const py = this.entity.position.y;\n const worldParts: Vector2[][] = [];\n for (const part of this.convexParts) {\n const w: Vector2[] = new Array(part.length);\n for (let i = 0; i < part.length; i++) {\n const v = part[i];\n if (!v) continue;\n w[i] = new Vector2(v.x * cos - v.y * sin + px, v.x * sin + v.y * cos + py);\n }\n worldParts.push(w);\n }\n return worldParts;\n }\n}\n\nfunction closestPointOnSegment(a: Vector2, b: Vector2, p: Vector2): Vector2 {\n const ab = b.sub(a);\n const ap = p.sub(a);\n const t = Math.max(0, Math.min(1, ap.dot(ab) / ab.dot(ab)));\n return a.add(ab.mul(t));\n}\n\nfunction gatherSATAxes(a: Vector2[], b: Vector2[]): Vector2[] {\n const axes: Vector2[] = [];\n const pushAxis = (p: Vector2[], i: number) => {\n const p0 = p[i];\n const p1 = p[(i + 1) % p.length];\n if (!p0 || !p1) return;\n const edge = p1.sub(p0);\n // Perpendicular (normal)\n const axis = new Vector2(-edge.y, edge.x).normalize();\n axes.push(axis);\n };\n for (let i = 0; i < a.length; i++) pushAxis(a, i);\n for (let i = 0; i < b.length; i++) pushAxis(b, i);\n return axes;\n}\n\nfunction projectOntoAxis(poly: Vector2[], axis: Vector2): { min: number; max: number } {\n let min = Number.POSITIVE_INFINITY;\n let max = Number.NEGATIVE_INFINITY;\n for (const v of poly) {\n const p = v.dot(axis);\n if (p < min) min = p;\n if (p > max) max = p;\n }\n return { min, max };\n}\n\nfunction intervalOverlap(minA: number, maxA: number, minB: number, maxB: number): number {\n return Math.min(maxA, maxB) - Math.max(minA, minB);\n}\n\nfunction polygonCentroid(poly: Vector2[]): Vector2 {\n let cx = 0;\n let cy = 0;\n for (const v of poly) {\n cx += v.x;\n cy += v.y;\n }\n const n = poly.length > 0 ? poly.length : 1;\n return new Vector2(cx / n, cy / n);\n}\n\n\n","import { Entity } from '../physics/Entity';\nimport { Collider, CollisionInfo } from './Collider';\nimport { CircleCollider } from './CircleCollider';\nimport { AABBCollider } from './AABBCollider';\nimport { PolygonCollider, entityToPolygonConfig } from './PolygonCollider';\nimport { CapsuleCollider } from './CapsuleCollider';\n\n// Collider cache to avoid repeated allocations\nconst colliderCache: WeakMap<Entity, Collider> = new WeakMap();\n\n/**\n * Collision detector\n * \n * Handles collision detection between entities using their colliders.\n * Supports efficient broad-phase and narrow-phase detection.\n */\n\n/**\n * Creates a collider for an entity based on its shape\n * \n * @param entity - Entity to create collider for\n * @returns Appropriate collider instance\n */\nexport function createCollider(entity: Entity): Collider | null {\n const cached = colliderCache.get(entity);\n if (cached) {\n return cached;\n }\n let collider: Collider | null = null;\n // 1) Explicit polygon assignment has priority\n if (entityToPolygonConfig.has(entity)) {\n collider = new PolygonCollider(entity);\n } else if (entity.capsule) {\n collider = new CapsuleCollider(entity);\n } else if (entity.radius > 0) {\n collider = new CircleCollider(entity);\n } else if (entity.width > 0 && entity.height > 0) {\n collider = new AABBCollider(entity);\n }\n if (collider) {\n colliderCache.set(entity, collider);\n }\n return collider;\n}\n\n/**\n * Tests collision between two entities\n * \n * @param entityA - First entity\n * @param entityB - Second entity\n * @returns Collision info if collision detected, null otherwise\n */\nexport function testCollision(entityA: Entity, entityB: Entity): CollisionInfo | null {\n // Check collision masks\n if (!entityA.canCollideWith(entityB)) {\n return null;\n }\n\n // Skip static-static collisions\n if (entityA.isStatic() && entityB.isStatic()) {\n return null;\n }\n\n const colliderA = createCollider(entityA);\n const colliderB = createCollider(entityB);\n\n if (!colliderA || !colliderB) {\n return null;\n }\n\n return colliderA.testCollision(colliderB);\n}\n\n/**\n * Finds all collisions between entities\n * \n * @param entities - Array of entities to test\n * @returns Array of collision infos\n */\nexport function findCollisions(entities: Entity[]): CollisionInfo[] {\n const collisions: CollisionInfo[] = [];\n\n for (let i = 0; i < entities.length; i++) {\n const entityA = entities[i];\n if (!entityA) continue;\n\n for (let j = i + 1; j < entities.length; j++) {\n const entityB = entities[j];\n if (!entityB) continue;\n\n const collision = testCollision(entityA, entityB);\n if (collision) {\n collisions.push(collision);\n }\n }\n }\n\n return collisions;\n}\n\n","import { Entity } from '../physics/Entity';\nimport { AABB } from '../core/math/AABB';\nimport { createCollider } from './detector';\nimport { Ray, RaycastHit } from './Ray';\n\n/**\n * Spatial hash cell containing entities\n */\nclass SpatialHashCell {\n // Array is generally faster for iteration than Set for small numbers of items\n public entities: Entity[] = [];\n\n /**\n * Adds an entity to this cell\n * \n * @param entity - Entity to add\n */\n public add(entity: Entity): void {\n if (this.entities.indexOf(entity) === -1) {\n this.entities.push(entity);\n }\n }\n\n /**\n * Removes an entity from this cell\n * \n * @param entity - Entity to remove\n */\n public remove(entity: Entity): void {\n const index = this.entities.indexOf(entity);\n if (index !== -1) {\n // Fast remove: swap with last and pop\n const last = this.entities[this.entities.length - 1];\n if (last) {\n this.entities[index] = last;\n }\n this.entities.pop();\n }\n }\n\n /**\n * Clears all entities from this cell\n */\n public clear(): void {\n this.entities.length = 0;\n }\n}\n\n/**\n * Spatial hash grid for efficient collision detection\n * \n * Divides the world into a grid of cells and stores entities in cells\n * based on their position. This reduces collision checks from O(n²) to O(n).\n * \n * @example\n * ```typescript\n * const spatialHash = new SpatialHash(100, 10); // 100x100 cell size, 10x10 grid\n * spatialHash.insert(entity);\n * const nearby = spatialHash.query(entity);\n * ```\n */\nexport class SpatialHash {\n private cellSize: number;\n private gridWidth: number;\n private gridHeight: number;\n // Use number keys instead of strings to reduce GC pressure\n // Key = (x << 16) | y\n private cells: Map<number, SpatialHashCell>;\n\n // Cache entity cells to avoid recalculating bounds every frame if not needed\n // Stores the list of cell keys the entity is currently in\n private entityCells: WeakMap<Entity, number[]>;\n\n /**\n * Creates a new spatial hash\n * \n * @param cellSize - Size of each cell in world units\n * @param gridWidth - Number of cells horizontally\n * @param gridHeight - Number of cells vertically (default: same as width)\n */\n constructor(cellSize: number, gridWidth: number, gridHeight?: number) {\n this.cellSize = cellSize;\n this.gridWidth = gridWidth;\n this.gridHeight = gridHeight ?? gridWidth;\n this.cells = new Map();\n this.entityCells = new WeakMap();\n }\n\n /**\n * Converts world coordinates to grid coordinates\n * \n * @param x - World X coordinate\n * @param y - World Y coordinate\n * @returns Grid coordinates\n */\n private worldToGrid(x: number, y: number): { x: number; y: number } {\n return {\n x: Math.floor(x / this.cellSize),\n y: Math.floor(y / this.cellSize),\n };\n }\n\n /**\n * Creates a cell key from grid coordinates\n * \n * @param gridX - Grid X coordinate\n * @param gridY - Grid Y coordinate\n * @returns Numeric cell key\n */\n private getKey(gridX: number, gridY: number): number {\n // Simple packing: x in high 16 bits, y in low 16 bits\n // Adjust for negative coordinates by adding offset if needed, \n // but here we assume positive grid or handle wrapping.\n // For wrapping grid:\n return (gridX & 0xFFFF) << 16 | (gridY & 0xFFFF);\n }\n\n /**\n * Gets or creates a cell at grid coordinates\n * \n * @param key - Cell key\n * @returns Cell instance\n */\n private getCell(key: number): SpatialHashCell {\n let cell = this.cells.get(key);\n if (!cell) {\n cell = new SpatialHashCell();\n this.cells.set(key, cell);\n }\n return cell;\n }\n\n /**\n * Gets all cell keys that an entity's AABB overlaps\n * \n * @param entity - Entity to get cells for\n * @param outKeys - Array to store keys in (to avoid allocation)\n * @returns Number of keys added\n */\n private getEntityKeys(entity: Entity, outKeys: number[]): number {\n const collider = createCollider(entity);\n if (!collider) {\n return 0;\n }\n\n const bounds = collider.getBounds();\n const minGrid = this.worldToGrid(bounds.minX, bounds.minY);\n const maxGrid = this.worldToGrid(bounds.maxX, bounds.maxY);\n\n let count = 0;\n outKeys.length = 0;\n\n for (let x = minGrid.x; x <= maxGrid.x; x++) {\n for (let y = minGrid.y; y <= maxGrid.y; y++) {\n // Wrap coordinates for infinite grid\n const wrappedX = ((x % this.gridWidth) + this.gridWidth) % this.gridWidth;\n const wrappedY = ((y % this.gridHeight) + this.gridHeight) % this.gridHeight;\n outKeys.push(this.getKey(wrappedX, wrappedY));\n count++;\n }\n }\n return count;\n }\n\n /**\n * Inserts an entity into the spatial hash\n * \n * @param entity - Entity to insert\n */\n public insert(entity: Entity): void {\n // Calculate new keys\n const newKeys: number[] = [];\n this.getEntityKeys(entity, newKeys);\n\n // Store for next time\n this.entityCells.set(entity, newKeys);\n\n // Add to cells\n for (const key of newKeys) {\n const cell = this.getCell(key);\n cell.add(entity);\n }\n }\n\n /**\n * Removes an entity from the spatial hash\n * \n * @param entity - Entity to remove\n */\n public remove(entity: Entity): void {\n const keys = this.entityCells.get(entity);\n if (!keys) {\n return;\n }\n\n for (const key of keys) {\n const cell = this.cells.get(key);\n if (cell) {\n cell.remove(entity);\n }\n }\n\n this.entityCells.delete(entity);\n }\n\n /**\n * Updates an entity's position in the spatial hash\n * \n * Removes and re-inserts the entity if it moved to different cells.\n * \n * @param entity - Entity to update\n */\n public update(entity: Entity): void {\n const oldKeys = this.entityCells.get(entity);\n\n // We need to check if the entity has actually moved enough to change cells\n // Optimization: Check if AABB grid bounds changed?\n // For now, let's just recalculate keys and compare.\n // To avoid allocation, we could use a static/shared array for temp keys?\n // But we need to store the new keys anyway.\n\n const newKeys: number[] = [];\n this.getEntityKeys(entity, newKeys);\n\n // Check if keys match\n if (oldKeys && oldKeys.length === newKeys.length) {\n let match = true;\n // Since keys are deterministic and we iterate same way, order should match\n for (let i = 0; i < oldKeys.length; i++) {\n if (oldKeys[i] !== newKeys[i]) {\n match = false;\n break;\n }\n }\n if (match) return;\n }\n\n // Remove from old cells\n if (oldKeys) {\n for (const key of oldKeys) {\n const cell = this.cells.get(key);\n if (cell) {\n cell.remove(entity);\n }\n }\n }\n\n // Add to new cells\n this.entityCells.set(entity, newKeys);\n for (const key of newKeys) {\n const cell = this.getCell(key);\n cell.add(entity);\n }\n }\n\n /**\n * Queries entities near a given entity\n * \n * @param entity - Entity to query around\n * @param results - Optional Set to store results in (avoids allocation)\n * @returns Set of nearby entities (excluding the query entity)\n */\n public query(entity: Entity, results: Set<Entity> = new Set()): Set<Entity> {\n // Use cached keys if available, otherwise calculate\n let keys = this.entityCells.get(entity);\n if (!keys) {\n keys = [];\n this.getEntityKeys(entity, keys);\n }\n\n results.clear();\n\n for (const key of keys) {\n const cell = this.cells.get(key);\n if (cell) {\n const entities = cell.entities;\n // Array iteration is fast\n for (let i = 0; i < entities.length; i++) {\n const other = entities[i];\n if (other && other !== entity) {\n results.add(other);\n }\n }\n }\n }\n\n return results;\n }\n\n /**\n * Queries entities in an AABB region\n * \n * @param bounds - AABB to query\n * @returns Set of entities in the region\n */\n public queryAABB(bounds: AABB): Set<Entity> {\n const minGrid = this.worldToGrid(bounds.minX, bounds.minY);\n const maxGrid = this.worldToGrid(bounds.maxX, bounds.maxY);\n const results = new Set<Entity>();\n\n for (let x = minGrid.x; x <= maxGrid.x; x++) {\n for (let y = minGrid.y; y <= maxGrid.y; y++) {\n const wrappedX = ((x % this.gridWidth) + this.gridWidth) % this.gridWidth;\n const wrappedY = ((y % this.gridHeight) + this.gridHeight) % this.gridHeight;\n const key = this.getKey(wrappedX, wrappedY);\n const cell = this.cells.get(key);\n if (cell) {\n for (const entity of cell.entities) {\n results.add(entity);\n }\n }\n }\n }\n\n return results;\n }\n\n /**\n * Clears all entities from the spatial hash\n */\n public clear(): void {\n this.cells.clear();\n // We can't easily clear the WeakMap, but that's fine, it's weak.\n // If we wanted to clear the values in the WeakMap for existing entities,\n // we would need to track them. But usually clear() is used when resetting the world.\n }\n\n /**\n * Gets statistics about the spatial hash\n * \n * @returns Statistics object\n */\n public getStats(): {\n totalCells: number;\n usedCells: number;\n totalEntities: number;\n averageEntitiesPerCell: number;\n } {\n let totalEntities = 0;\n for (const cell of this.cells.values()) {\n totalEntities += cell.entities.length;\n }\n\n return {\n totalCells: this.gridWidth * this.gridHeight,\n usedCells: this.cells.size,\n totalEntities,\n averageEntitiesPerCell: this.cells.size > 0 ? totalEntities / this.cells.size : 0,\n };\n }\n\n /**\n * Casts a ray against entities in the spatial hash\n * \n * @param ray - Ray to cast\n * @param mask - Optional collision mask (layer)\n * @param filter - Optional filter function (return true to include entity)\n * @returns Raycast hit info if hit, null otherwise\n */\n public raycast(ray: Ray, mask?: number, filter?: (entity: Entity) => boolean): RaycastHit | null {\n // DDA Algorithm for grid traversal\n const start = ray.origin;\n const end = ray.getPoint(Math.min(ray.length, 10000)); // Cap length to avoid infinite loops\n\n // console.log('Raycast start:', start, 'end:', end, 'dir:', ray.direction);\n\n let x0 = start.x;\n let y0 = start.y;\n const x1 = end.x;\n const y1 = end.y;\n\n // Grid coordinates\n let gx0 = Math.floor(x0 / this.cellSize);\n let gy0 = Math.floor(y0 / this.cellSize);\n const gx1 = Math.floor(x1 / this.cellSize);\n const gy1 = Math.floor(y1 / this.cellSize);\n\n // const dx = Math.abs(x1 - x0);\n // const dy = Math.abs(y1 - y0);\n\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n\n const visitedEntities = new Set<Entity>();\n let closestHit: RaycastHit | null = null;\n\n // Helper to check cell\n const checkCell = (gx: number, gy: number) => {\n // Wrap coordinates\n const wrappedX = ((gx % this.gridWidth) + this.gridWidth) % this.gridWidth;\n const wrappedY = ((gy % this.gridHeight) + this.gridHeight) % this.gridHeight;\n const key = this.getKey(wrappedX, wrappedY);\n const cell = this.cells.get(key);\n\n if (cell) {\n // console.log('Checking cell:', gx, gy, 'Entities:', cell.entities.length);\n for (const entity of cell.entities) {\n if (visitedEntities.has(entity)) continue;\n visitedEntities.add(entity);\n\n // Check mask if provided\n if (mask !== undefined && (entity.collisionCategory & mask) === 0) continue;\n\n // Check filter if provided\n if (filter && !filter(entity)) {\n continue;\n }\n\n const collider = createCollider(entity);\n if (collider) {\n const hit = collider.raycast(ray);\n if (hit) {\n if (!closestHit || hit.distance < closestHit.distance) {\n closestHit = hit;\n }\n }\n }\n }\n } else {\n }\n };\n\n // Bresenham's line algorithm for grid traversal (simplified DDA)\n // Note: Bresenham is for lines, but here we want to visit all cells touched by the ray.\n // A proper DDA (Amanatides & Woo) is better for ray casting.\n\n // Let's use Amanatides & Woo DDA\n let x = gx0;\n let y = gy0;\n\n const stepX = sx;\n const stepY = sy;\n\n const tDeltaX = this.cellSize / Math.abs(ray.direction.x);\n const tDeltaY = this.cellSize / Math.abs(ray.direction.y);\n\n let tMaxX = (ray.direction.x > 0)\n ? ((x + 1) * this.cellSize - start.x) / ray.direction.x\n : (start.x - x * this.cellSize) / -ray.direction.x; // Handle negative direction carefully\n\n // Fix for negative direction:\n // If dir.x < 0, we want distance to left edge of cell.\n // Left edge is x * cellSize.\n // Distance is (start.x - x * cellSize) / -dir.x\n // Wait, if x is grid index, left edge is x * cellSize.\n // If we are at x, and moving left, the next boundary is x * cellSize.\n if (ray.direction.x < 0) {\n tMaxX = (start.x - x * this.cellSize) / -ray.direction.x;\n } else {\n tMaxX = ((x + 1) * this.cellSize - start.x) / ray.direction.x;\n }\n\n let tMaxY = (ray.direction.y > 0)\n ? ((y + 1) * this.cellSize - start.y) / ray.direction.y\n : (start.y - y * this.cellSize) / -ray.direction.y;\n\n if (ray.direction.y < 0) {\n tMaxY = (start.y - y * this.cellSize) / -ray.direction.y;\n } else {\n tMaxY = ((y + 1) * this.cellSize - start.y) / ray.direction.y;\n }\n\n // Handle division by zero (axis aligned rays)\n if (Math.abs(ray.direction.x) < 1e-9) {\n tMaxX = Infinity;\n }\n if (Math.abs(ray.direction.y) < 1e-9) {\n tMaxY = Infinity;\n }\n\n // Max steps to prevent infinite loop\n let steps = 0;\n const maxSteps = Math.abs(gx1 - gx0) + Math.abs(gy1 - gy0) + 10;\n\n while (steps < maxSteps) {\n checkCell(x, y);\n\n // If we found a hit that is closer than the distance to the next cell, we can potentially stop.\n // However, an entity in the current cell might have a hit point further away than the next cell boundary \n // (e.g. a large entity overlapping multiple cells).\n // But if closestHit.distance < tMaxX and closestHit.distance < tMaxY, then the hit is within the current cell (roughly).\n // To be safe, we should probably continue a bit or just check all cells.\n // Optimization: if closestHit.distance < min(tMaxX, tMaxY), we can stop?\n // tMaxX is distance to next X boundary.\n // If hit is before that, it's in this cell (or previous).\n\n if (closestHit) {\n if ((closestHit as RaycastHit).distance < Math.min(tMaxX, tMaxY)) {\n // We found a hit in this cell (or previous) that is closer than the next cell boundary.\n // We can stop.\n return closestHit;\n }\n }\n\n if (tMaxX < tMaxY) {\n tMaxX += tDeltaX;\n x += stepX;\n } else {\n tMaxY += tDeltaY;\n y += stepY;\n }\n steps++;\n\n // Check if we passed the end point\n // Simple check: if we passed the target grid coordinates\n // But with wrapping, this is tricky.\n // Just rely on maxSteps or distance check.\n if (closestHit && (closestHit as RaycastHit).distance < ray.length) {\n // If we have a hit, and we've gone far enough...\n }\n }\n\n return closestHit;\n }\n}\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { Entity } from '../physics/Entity';\n\n/**\n * Raycast hit information\n */\nexport interface RaycastHit {\n /** Entity hit by the ray */\n entity: Entity;\n /** Point of intersection */\n point: Vector2;\n /** Normal at the point of intersection */\n normal: Vector2;\n /** Distance from ray origin to intersection point */\n distance: number;\n}\n\n/**\n * Ray for raycasting\n */\nexport class Ray {\n /** Ray origin */\n public origin: Vector2;\n /** Ray direction (normalized) */\n public direction: Vector2;\n /** Maximum length of the ray */\n public length: number;\n\n /**\n * Creates a new ray\n * \n * @param origin - Ray origin\n * @param direction - Ray direction\n * @param length - Maximum length (default: Infinity)\n */\n constructor(origin: Vector2, direction: Vector2, length: number = Infinity) {\n this.origin = origin.clone();\n this.direction = direction.clone().normalizeInPlace();\n this.length = length;\n }\n\n /**\n * Gets a point along the ray\n * \n * @param distance - Distance from origin\n * @returns Point at distance\n */\n public getPoint(distance: number): Vector2 {\n return this.origin.add(this.direction.mul(distance));\n }\n}\n","import { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport { SpatialPartition } from '../world/SpatialPartition';\nimport { Ray } from './Ray';\nimport { AABBCollider } from './AABBCollider';\nimport { CircleCollider } from './CircleCollider';\nimport { PolygonCollider } from './PolygonCollider';\nimport { createCollider } from './detector';\nimport { Collider } from './Collider';\n\nexport interface RaycastHit {\n entity: ReturnType<Collider['getEntity']>;\n point: Vector2;\n normal: Vector2;\n distance: number;\n}\n\n/**\n * Casts a ray in the world using the spatial partition for broad-phase, then shape-specific narrow-phase.\n * Direction will be normalized internally.\n *\n * @param partition - Spatial partition to query\n * @param origin - Ray origin\n * @param direction - Ray direction (any length)\n * @param maxDistance - Maximum distance\n * @param mask - Optional collision mask (layer)\n * @param filter - Optional filter function (return true to include entity)\n * @returns Nearest hit or null\n *\n * @example\n * ```typescript\n * const hit = raycast(worldPartition, new Vector2(0,0), new Vector2(1,0), 1000);\n * if (hit) {\n * // handle\n * }\n * ```\n */\nexport function raycast(partition: SpatialPartition, origin: Vector2, direction: Vector2, maxDistance: number, mask?: number, filter?: (entity: any) => boolean): RaycastHit | null {\n const dir = direction.length() > 0 ? direction.normalize() : new Vector2(1, 0);\n const end = origin.add(dir.mul(maxDistance));\n const candidates = partition.raycast(new Ray(origin, dir, maxDistance), mask, filter);\n if (candidates) return candidates;\n\n // Fallback if partition doesn't implement raycast (shouldn't happen with SpatialHash)\n // But for generic SpatialPartition, we might need the old AABB query method\n const bounds = new AABB(\n Math.min(origin.x, end.x),\n Math.min(origin.y, end.y),\n Math.max(origin.x, end.x),\n Math.max(origin.y, end.y)\n );\n\n const entities = partition.queryAABB(bounds);\n let best: RaycastHit | null = null;\n\n for (const e of entities) {\n if (mask !== undefined && (e.collisionCategory & mask) === 0) continue;\n if (filter && !filter(e)) continue;\n const collider = createCollider(e);\n if (!collider) continue;\n const hit = raycastCollider(collider, origin, dir, maxDistance);\n if (!hit) continue;\n if (!best || hit.distance < best.distance) best = hit;\n }\n\n return best;\n}\n\nexport function raycastCollider(collider: Collider, origin: Vector2, dir: Vector2, maxDistance: number): RaycastHit | null {\n if (collider instanceof CircleCollider) return raycastCircle(collider, origin, dir, maxDistance);\n if (collider instanceof AABBCollider) return raycastAABB(collider, origin, dir, maxDistance);\n if (collider instanceof PolygonCollider) return raycastPolygon(collider, origin, dir, maxDistance);\n return null;\n}\n\nfunction raycastCircle(circle: CircleCollider, origin: Vector2, dir: Vector2, maxDistance: number): RaycastHit | null {\n const c = circle.getCenter();\n const r = circle.getRadius();\n const m = origin.sub(c);\n const b = m.dot(dir);\n const cval = m.dot(m) - r * r;\n if (cval > 0 && b > 0) return null; // ray origin outside and pointing away\n const discr = b * b - cval;\n if (discr < 0) return null;\n const t = -b - Math.sqrt(discr);\n if (t < 0) return null;\n if (t > maxDistance) return null;\n const point = origin.add(dir.mul(t));\n const normal = point.sub(c).normalize();\n return { entity: circle.getEntity(), point, normal, distance: t };\n}\n\nfunction raycastAABB(box: AABBCollider, origin: Vector2, dir: Vector2, maxDistance: number): RaycastHit | null {\n const b = box.getBounds();\n let tmin = 0;\n let tmax = maxDistance;\n\n const invDx = 1 / (dir.x === 0 ? 1e-9 : dir.x);\n const invDy = 1 / (dir.y === 0 ? 1e-9 : dir.y);\n\n let tx1 = (b.minX - origin.x) * invDx;\n let tx2 = (b.maxX - origin.x) * invDx;\n let ty1 = (b.minY - origin.y) * invDy;\n let ty2 = (b.maxY - origin.y) * invDy;\n\n const tminX = Math.min(tx1, tx2);\n const tmaxX = Math.max(tx1, tx2);\n const tminY = Math.min(ty1, ty2);\n const tmaxY = Math.max(ty1, ty2);\n\n tmin = Math.max(tmin, Math.max(tminX, tminY));\n tmax = Math.min(tmax, Math.min(tmaxX, tmaxY));\n\n if (tmax < tmin || tmin < 0 || tmin > maxDistance) return null;\n\n const point = origin.add(dir.mul(tmin));\n // Determine normal based on which slab was hit\n let normal: Vector2;\n if (tmin === tminX) normal = new Vector2(dir.x > 0 ? -1 : 1, 0);\n else normal = new Vector2(0, dir.y > 0 ? -1 : 1);\n return { entity: box.getEntity(), point, normal, distance: tmin };\n}\n\nfunction raycastPolygon(poly: PolygonCollider, origin: Vector2, dir: Vector2, maxDistance: number): RaycastHit | null {\n // Cast ray against all edges; take nearest positive distance\n // We approximate normal as the edge normal pointing outward\n const end = origin.add(dir.mul(maxDistance));\n let bestT = Number.POSITIVE_INFINITY;\n let bestPoint: Vector2 | null = null;\n let bestNormal: Vector2 | null = null;\n\n // Access world vertices via getBounds + transform approximation would be inefficient; use internal helper via casting\n const any: any = poly as any;\n const parts: Vector2[][] = any['getWorldParts'] ? any['getWorldParts']() : [];\n for (const part of parts) {\n for (let i = 0; i < part.length; i++) {\n const a = part[i];\n const b = part[(i + 1) % part.length];\n if (!a || !b) continue;\n const hit = segmentRayIntersection(a, b, origin, end);\n if (!hit) continue;\n const t = hit.distance;\n if (t >= 0 && t <= maxDistance && t < bestT) {\n bestT = t;\n bestPoint = hit.point;\n const edge = b.sub(a);\n const n = new Vector2(-edge.y, edge.x).normalize();\n bestNormal = n;\n }\n }\n }\n\n if (!bestPoint || !bestNormal || bestT === Number.POSITIVE_INFINITY) return null;\n return { entity: poly.getEntity(), point: bestPoint, normal: bestNormal, distance: bestT };\n}\n\nfunction segmentRayIntersection(a: Vector2, b: Vector2, r0: Vector2, r1: Vector2): { point: Vector2; distance: number } | null {\n const v1 = r0.sub(a);\n const v2 = b.sub(a);\n const v3 = new Vector2(-(r1.y - r0.y), r1.x - r0.x);\n const denom = v2.dot(v3);\n if (Math.abs(denom) < 1e-9) return null; // parallel\n const t1 = v2.cross(v1) / denom;\n const t2 = v1.dot(v3) / denom;\n if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) {\n const hitPoint = new Vector2(r0.x + (r1.x - r0.x) * t1, r0.y + (r1.y - r0.y) * t1);\n const dist = hitPoint.sub(r0).length();\n return { point: hitPoint, distance: dist };\n }\n return null;\n}\n\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { Entity } from '../physics/Entity';\nimport { CollisionInfo } from './Collider';\n\n/**\n * Collision resolver configuration\n */\nexport interface ResolverConfig {\n /** Position correction factor (0-1, higher = more correction) */\n positionCorrectionFactor?: number;\n /** Minimum penetration depth to resolve */\n minPenetrationDepth?: number;\n /** Maximum position correction per step */\n maxPositionCorrection?: number;\n}\n\n/**\n * Collision resolver\n * \n * Resolves collisions by separating entities and applying impulses.\n * Uses impulse-based resolution for stable, deterministic physics.\n * \n * @example\n * ```typescript\n * const resolver = new CollisionResolver();\n * resolver.resolve(collision);\n * ```\n */\nexport class CollisionResolver {\n private config: Required<ResolverConfig>;\n\n /**\n * Creates a new collision resolver\n * \n * @param config - Resolver configuration\n */\n constructor(config: ResolverConfig = {}) {\n this.config = {\n positionCorrectionFactor: config.positionCorrectionFactor ?? 0.8,\n minPenetrationDepth: config.minPenetrationDepth ?? 0.0001,\n maxPositionCorrection: config.maxPositionCorrection ?? 5,\n };\n }\n\n /**\n * Resolves a collision\n * \n * Separates entities and applies collision response.\n * First checks if the collision should be resolved using resolution filters.\n * If any entity has a resolution filter that returns false, the collision\n * is skipped (entities pass through) but events are still fired.\n * \n * @param collision - Collision information to resolve\n */\n public resolve(collision: CollisionInfo): void {\n const { entityA, entityB, normal, depth } = collision;\n\n // Skip if penetration is too small\n if (depth < this.config.minPenetrationDepth) {\n return;\n }\n\n // Check resolution filters - if either entity says no, skip resolution\n // This allows entities to pass through each other while still detecting collisions\n if (!entityA.shouldResolveCollisionWith(entityB)) {\n return;\n }\n\n // Position correction (separate entities)\n this.separateEntities(entityA, entityB, normal, depth);\n\n // Velocity resolution (collision response)\n this.resolveVelocities(entityA, entityB, normal);\n }\n\n /**\n * Separates two entities by moving them apart\n * \n * This method applies position corrections to resolve penetration between\n * colliding entities. After applying corrections, it notifies position change\n * handlers to ensure proper synchronization with game logic (e.g., updating\n * owner.x/y signals for network sync).\n * \n * @param entityA - First entity\n * @param entityB - Second entity\n * @param normal - Separation normal (from A to B)\n * @param depth - Penetration depth\n */\n private separateEntities(\n entityA: Entity,\n entityB: Entity,\n normal: Vector2,\n depth: number\n ): void {\n const totalInvMass = entityA.invMass + entityB.invMass;\n if (totalInvMass === 0) {\n return; // Both static\n }\n\n // Calculate separation amount\n const correction = Math.min(\n depth * this.config.positionCorrectionFactor,\n this.config.maxPositionCorrection\n );\n\n // Distribute correction based on inverse mass\n const correctionA = normal.mul(-correction * (entityA.invMass / totalInvMass));\n const correctionB = normal.mul(correction * (entityB.invMass / totalInvMass));\n\n // Apply corrections and notify position change handlers\n // This ensures that owner.x/y signals are updated after collision resolution\n if (!entityA.isStatic()) {\n entityA.position.addInPlace(correctionA);\n entityA.notifyPositionChange();\n }\n if (!entityB.isStatic()) {\n entityB.position.addInPlace(correctionB);\n entityB.notifyPositionChange();\n }\n }\n\n /**\n * Resolves velocities using impulse-based collision response\n * \n * @param entityA - First entity\n * @param entityB - Second entity\n * @param normal - Collision normal (from A to B)\n */\n private resolveVelocities(\n entityA: Entity,\n entityB: Entity,\n normal: Vector2\n ): void {\n // Relative velocity\n const relativeVelocity = entityB.velocity.sub(entityA.velocity);\n const velocityAlongNormal = relativeVelocity.dot(normal);\n\n // Don't resolve if velocities are separating\n if (velocityAlongNormal > 0) {\n return;\n }\n\n // Calculate restitution (bounciness)\n const restitution = Math.min(entityA.restitution, entityB.restitution);\n\n // Calculate impulse scalar\n const totalInvMass = entityA.invMass + entityB.invMass;\n if (totalInvMass === 0) {\n return; // Both static\n }\n\n // Impulse: j = -(1 + e) * v_rel · n / (1/mA + 1/mB)\n const impulseScalar = -(1 + restitution) * velocityAlongNormal / totalInvMass;\n const impulse = normal.mul(impulseScalar);\n\n // Apply impulse\n if (!entityA.isStatic()) {\n entityA.velocity.addInPlace(impulse.mul(-entityA.invMass));\n entityA.notifyMovementChange();\n // Note: We don't call notifyDirectionChange() here because collision response\n // should not change the entity's intended direction (visual orientation).\n // Direction changes should only come from intentional movement (player input, AI).\n }\n if (!entityB.isStatic()) {\n entityB.velocity.addInPlace(impulse.mul(entityB.invMass));\n entityB.notifyMovementChange();\n // Note: We don't call notifyDirectionChange() here because collision response\n // should not change the entity's intended direction (visual orientation).\n // Direction changes should only come from intentional movement (player input, AI).\n }\n\n // Friction (simplified, using velocity tangent to collision)\n const tangent = relativeVelocity.sub(normal.mul(velocityAlongNormal));\n const tangentLength = tangent.length();\n\n if (tangentLength > 1e-5) {\n const friction = Math.sqrt(entityA.friction * entityB.friction);\n const tangentNormalized = tangent.normalize();\n const frictionImpulse = tangentNormalized.mul(-tangentLength * friction / totalInvMass);\n\n // Clamp friction impulse to not exceed relative velocity\n const maxFriction = Math.abs(impulseScalar * friction);\n if (frictionImpulse.length() > maxFriction) {\n frictionImpulse.normalizeInPlace().mulInPlace(maxFriction);\n }\n\n if (!entityA.isStatic()) {\n entityA.velocity.addInPlace(frictionImpulse.mul(-entityA.invMass));\n entityA.notifyMovementChange();\n // Note: We don't call notifyDirectionChange() here because friction adjustments\n // should not change the entity's intended direction (visual orientation).\n }\n if (!entityB.isStatic()) {\n entityB.velocity.addInPlace(frictionImpulse.mul(entityB.invMass));\n entityB.notifyMovementChange();\n // Note: We don't call notifyDirectionChange() here because friction adjustments\n // should not change the entity's intended direction (visual orientation).\n }\n }\n }\n\n /**\n * Resolves multiple collisions\n * \n * @param collisions - Array of collisions to resolve\n */\n public resolveAll(collisions: CollisionInfo[]): void {\n for (const collision of collisions) {\n this.resolve(collision);\n }\n }\n}\n\n","import { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport { Collider } from './Collider';\nimport { AABBCollider } from './AABBCollider';\nimport { CircleCollider } from './CircleCollider';\nimport { PolygonCollider } from './PolygonCollider';\nimport { createCollider } from './detector';\nimport { Entity } from '../physics/Entity';\n\nexport interface SweepResult {\n time: number; // 0..1 within the step\n normal: Vector2;\n point: Vector2;\n}\n\n/**\n * Computes time-of-impact for a pair of entities using simple analytical sweeps.\n * Supports Circle-Circle, Circle-AABB, AABB-AABB. Polygon falls back to AABB sweep.\n *\n * @param a - First entity\n * @param b - Second entity\n * @param delta - World displacement of entity A over the step (A's motion, B assumed static). For relative motion, pass (vA - vB) * dt.\n * @returns SweepResult or null if no hit in [0,1]\n *\n * @example\n * ```typescript\n * const rel = entityA.velocity.sub(entityB.velocity).mul(dt);\n * const hit = sweepEntities(entityA, entityB, rel);\n * ```\n */\nexport function sweepEntities(a: Entity, b: Entity, delta: Vector2): SweepResult | null {\n const ca = createCollider(a);\n const cb = createCollider(b);\n if (!ca || !cb) return null;\n return sweepColliders(ca, cb, delta);\n}\n\nexport function sweepColliders(a: Collider, b: Collider, delta: Vector2): SweepResult | null {\n if (a instanceof CircleCollider && b instanceof CircleCollider) {\n return sweepCircleCircle(a, b, delta);\n }\n if (a instanceof CircleCollider && b instanceof AABBCollider) {\n return sweepCircleAABB(a, b, delta);\n }\n if (a instanceof AABBCollider && b instanceof CircleCollider) {\n const res = sweepCircleAABB(b, a, delta.mul(-1));\n if (!res) return null;\n return { time: res.time, normal: res.normal.mul(-1), point: res.point };\n }\n if (a instanceof AABBCollider && b instanceof AABBCollider) {\n return sweepAABBAABB(a, b, delta);\n }\n // Fallback for polygons: use their AABBs\n if (a instanceof PolygonCollider || b instanceof PolygonCollider) {\n const aa = a.getBounds();\n const bb = b.getBounds();\n const ca = new AABBCollider(a.getEntity());\n const cb = new AABBCollider(b.getEntity());\n // Temporarily monkey-patch to use bounds of polygons\n (ca as any).getBounds = () => aa;\n (cb as any).getBounds = () => bb;\n return sweepAABBAABB(ca, cb, delta);\n }\n return null;\n}\n\nfunction sweepCircleCircle(a: CircleCollider, b: CircleCollider, delta: Vector2): SweepResult | null {\n // Relative motion: move A by delta, B static\n const p0 = a.getCenter();\n const c = b.getCenter();\n const r = a.getRadius() + b.getRadius();\n const m = p0.sub(c);\n const d = delta;\n const A = d.dot(d);\n const B = 2 * m.dot(d);\n const C = m.dot(m) - r * r;\n const disc = B * B - 4 * A * C;\n if (disc < 0 || A === 0) return null;\n const t = (-B - Math.sqrt(disc)) / (2 * A);\n if (t < 0 || t > 1) return null;\n const hitPoint = p0.add(d.mul(t));\n const normal = hitPoint.sub(c).normalize();\n return { time: t, normal, point: hitPoint.sub(normal.mul(a.getRadius())) };\n}\n\nfunction sweepCircleAABB(circle: CircleCollider, box: AABBCollider, delta: Vector2): SweepResult | null {\n // Expand AABB by circle radius, then raycast circle center against it\n const r = circle.getRadius();\n const b = box.getBounds();\n const expanded = new AABB(b.minX - r, b.minY - r, b.maxX + r, b.maxY + r);\n const p0 = circle.getCenter();\n\n // Ray vs expanded AABB\n const dir = delta;\n const maxDist = 1; // parameterize within [0,1]\n const origin = new Vector2(0, 0);\n // Transform so p0 -> origin, box relative\n const bb = new AABB(expanded.minX - p0.x, expanded.minY - p0.y, expanded.maxX - p0.x, expanded.maxY - p0.y);\n const res = rayVsAABB(origin, dir, bb, maxDist);\n if (!res) return null;\n const t = res.t;\n const hitPos = p0.add(dir.mul(t));\n const normal = res.normal;\n return { time: t, normal, point: hitPos.sub(normal.mul(r)) };\n}\n\nfunction sweepAABBAABB(a: AABBCollider, b: AABBCollider, delta: Vector2): SweepResult | null {\n // Compute times of entry/exit along each axis using swept AABB\n const A = a.getBounds();\n const B = b.getBounds();\n const invDx = 1 / (delta.x === 0 ? 1e-9 : delta.x);\n const invDy = 1 / (delta.y === 0 ? 1e-9 : delta.y);\n\n const xEntry = ((delta.x > 0 ? B.minX - A.maxX : B.maxX - A.minX) * invDx);\n const xExit = ((delta.x > 0 ? B.maxX - A.minX : B.minX - A.maxX) * invDx);\n const yEntry = ((delta.y > 0 ? B.minY - A.maxY : B.maxY - A.minY) * invDy);\n const yExit = ((delta.y > 0 ? B.maxY - A.minY : B.minY - A.maxY) * invDy);\n\n const tEntry = Math.max(Math.min(xEntry, xExit), Math.min(yEntry, yExit));\n const tExit = Math.min(Math.max(xEntry, xExit), Math.max(yEntry, yExit));\n\n if (tEntry > tExit || tEntry < 0 || tEntry > 1) return null;\n\n let normal: Vector2;\n if (Math.min(xEntry, xExit) > Math.min(yEntry, yExit)) {\n normal = new Vector2(delta.x > 0 ? -1 : 1, 0);\n } else {\n normal = new Vector2(0, delta.y > 0 ? -1 : 1);\n }\n\n const hitPoint = new Vector2(\n delta.x !== 0 ? (delta.x > 0 ? A.maxX : A.minX) : (A.minX + A.maxX) * 0.5,\n delta.y !== 0 ? (delta.y > 0 ? A.maxY : A.minY) : (A.minY + A.maxY) * 0.5,\n );\n\n return { time: tEntry, normal, point: hitPoint };\n}\n\nfunction rayVsAABB(origin: Vector2, dir: Vector2, b: AABB, maxT: number): { t: number; normal: Vector2 } | null {\n const invDx = 1 / (dir.x === 0 ? 1e-9 : dir.x);\n const invDy = 1 / (dir.y === 0 ? 1e-9 : dir.y);\n let tmin = 0;\n let tmax = maxT;\n\n const tx1 = (b.minX - origin.x) * invDx;\n const tx2 = (b.maxX - origin.x) * invDx;\n const ty1 = (b.minY - origin.y) * invDy;\n const ty2 = (b.maxY - origin.y) * invDy;\n\n const tminX = Math.min(tx1, tx2);\n const tmaxX = Math.max(tx1, tx2);\n const tminY = Math.min(ty1, ty2);\n const tmaxY = Math.max(ty1, ty2);\n\n tmin = Math.max(tmin, Math.max(tminX, tminY));\n tmax = Math.min(tmax, Math.min(tmaxX, tmaxY));\n\n if (tmax < tmin || tmin < 0 || tmin > maxT) return null;\n const normal = (tmin === tminX) ? new Vector2(dir.x > 0 ? -1 : 1, 0) : new Vector2(0, dir.y > 0 ? -1 : 1);\n return { t: tmin, normal };\n}\n\n\n","import { Entity } from '../physics/Entity';\nimport { CollisionInfo } from '../collision/Collider';\n\n/**\n * Event handler types\n */\nexport type CollisionEventHandler = (collision: CollisionInfo) => void;\nexport type EntityEventHandler = (entity: Entity) => void;\nexport type SleepEventHandler = (entity: Entity) => void;\nexport type WakeEventHandler = (entity: Entity) => void;\n\n/**\n * Event system for physics world\n * \n * Manages event handlers for collisions, entity lifecycle, and other physics events.\n */\nexport class EventSystem {\n private collisionEnterHandlers: Set<CollisionEventHandler> = new Set();\n private collisionExitHandlers: Set<CollisionEventHandler> = new Set();\n private entityAddedHandlers: Set<EntityEventHandler> = new Set();\n private entityRemovedHandlers: Set<EntityEventHandler> = new Set();\n private entitySleepHandlers: Set<SleepEventHandler> = new Set();\n private entityWakeHandlers: Set<WakeEventHandler> = new Set();\n\n /**\n * Registers a collision enter handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onCollisionEnter(handler: CollisionEventHandler): () => void {\n this.collisionEnterHandlers.add(handler);\n return () => this.collisionEnterHandlers.delete(handler);\n }\n\n /**\n * Registers a collision exit handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onCollisionExit(handler: CollisionEventHandler): () => void {\n this.collisionExitHandlers.add(handler);\n return () => this.collisionExitHandlers.delete(handler);\n }\n\n /**\n * Registers an entity added handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onEntityAdded(handler: EntityEventHandler): () => void {\n this.entityAddedHandlers.add(handler);\n return () => this.entityAddedHandlers.delete(handler);\n }\n\n /**\n * Registers an entity removed handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onEntityRemoved(handler: EntityEventHandler): () => void {\n this.entityRemovedHandlers.add(handler);\n return () => this.entityRemovedHandlers.delete(handler);\n }\n\n /**\n * Registers an entity sleep handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onEntitySleep(handler: SleepEventHandler): () => void {\n this.entitySleepHandlers.add(handler);\n return () => this.entitySleepHandlers.delete(handler);\n }\n\n /**\n * Registers an entity wake handler\n * \n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n public onEntityWake(handler: WakeEventHandler): () => void {\n this.entityWakeHandlers.add(handler);\n return () => this.entityWakeHandlers.delete(handler);\n }\n\n /**\n * Emits a collision enter event\n * \n * @param collision - Collision information\n */\n public emitCollisionEnter(collision: CollisionInfo): void {\n for (const handler of this.collisionEnterHandlers) {\n handler(collision);\n }\n }\n\n /**\n * Emits a collision exit event\n * \n * @param collision - Collision information\n */\n public emitCollisionExit(collision: CollisionInfo): void {\n for (const handler of this.collisionExitHandlers) {\n handler(collision);\n }\n }\n\n /**\n * Emits an entity added event\n * \n * @param entity - Entity that was added\n */\n public emitEntityAdded(entity: Entity): void {\n for (const handler of this.entityAddedHandlers) {\n handler(entity);\n }\n }\n\n /**\n * Emits an entity removed event\n * \n * @param entity - Entity that was removed\n */\n public emitEntityRemoved(entity: Entity): void {\n for (const handler of this.entityRemovedHandlers) {\n handler(entity);\n }\n }\n\n /**\n * Emits an entity sleep event\n * \n * @param entity - Entity that went to sleep\n */\n public emitEntitySleep(entity: Entity): void {\n for (const handler of this.entitySleepHandlers) {\n handler(entity);\n }\n }\n\n /**\n * Emits an entity wake event\n * \n * @param entity - Entity that woke up\n */\n public emitEntityWake(entity: Entity): void {\n for (const handler of this.entityWakeHandlers) {\n handler(entity);\n }\n }\n\n /**\n * Clears all event handlers\n */\n public clear(): void {\n this.collisionEnterHandlers.clear();\n this.collisionExitHandlers.clear();\n this.entityAddedHandlers.clear();\n this.entityRemovedHandlers.clear();\n this.entitySleepHandlers.clear();\n this.entityWakeHandlers.clear();\n }\n}\n\n","import { Entity } from '../physics/Entity';\nimport { Integrator, IntegrationMethod } from '../physics/integrator';\nimport { CollisionResolver } from '../collision/resolver';\nimport { SpatialHash } from '../collision/spatial-hash';\nimport { testCollision, createCollider } from '../collision/detector';\nimport { CollisionInfo } from '../collision/Collider';\nimport { EventSystem } from './events';\nimport { SpatialPartition } from './SpatialPartition';\nimport { Vector2 } from '../core/math/Vector2';\nimport { Ray, RaycastHit } from '../collision/Ray';\nimport type { EntityConfig } from '../physics/Entity';\nimport { sweepEntities } from '../collision/sweep';\n\n/**\n * World configuration\n */\nexport interface WorldConfig {\n /** Time step for simulation (default: 1/60 for 60 FPS) */\n timeStep?: number;\n /** Integration method (default: Euler) */\n integrationMethod?: IntegrationMethod;\n /** Gravity vector (default: zero for top-down) */\n gravity?: Vector2;\n /** Spatial partition cell size (default: 100) */\n spatialCellSize?: number;\n /** Spatial partition grid width (default: 100) */\n spatialGridWidth?: number;\n /** Spatial partition grid height (default: 100) */\n spatialGridHeight?: number;\n /** Enable sleep for inactive entities (default: true) */\n enableSleep?: boolean;\n /** Tile width for grid-based logic (default: 32) */\n tileWidth?: number;\n /** Tile height for grid-based logic (default: 32) */\n tileHeight?: number;\n /** Sleep threshold in seconds (default: 0.5) */\n sleepThreshold?: number;\n /** Velocity threshold for sleep detection (default: 0.01) */\n sleepVelocityThreshold?: number;\n /** Custom spatial partition (optional) */\n spatialPartition?: SpatialPartition;\n /**\n * Optional quantization step (world units) applied to positions after every tick.\n * Set to a positive number (e.g. 1/16) to reduce floating point drift for networking.\n */\n positionQuantizationStep?: number;\n /**\n * Optional quantization step (world units / second) applied to velocities after every tick.\n * Set to a positive number (e.g. 1/256) to enforce deterministic clamps.\n */\n velocityQuantizationStep?: number;\n /**\n * Number of collision-resolution iterations per tick (default: 3).\n * Higher values further reduce interpenetration in crowded scenes.\n */\n resolverIterations?: number;\n /** Custom collision resolver factor controlling how aggressively overlaps are corrected. */\n positionCorrectionFactor?: number;\n /** Maximum positional correction applied per iteration (world units). */\n maxPositionCorrection?: number;\n /** Minimum penetration depth before a collision is resolved. */\n minPenetrationDepth?: number;\n}\n\n/**\n * Physics world\n * \n * Manages entities, physics simulation, collisions, and events.\n * \n * @example\n * ```typescript\n * const world = new World({ timeStep: 1/60 });\n * const entity = world.addEntity({ position: { x: 0, y: 0 }, radius: 10 });\n * world.step();\n * ```\n */\nexport class World {\n private entities: Set<Entity> = new Set();\n // Separate collections for performance\n private staticEntities: Set<Entity> = new Set();\n private dynamicEntities: Set<Entity> = new Set();\n private integrator: Integrator;\n private resolver: CollisionResolver;\n private spatialPartition: SpatialPartition;\n private events: EventSystem;\n private timeStep: number;\n private enableSleep: boolean;\n private tileWidth: number;\n private tileHeight: number;\n private sleepThreshold: number;\n private sleepVelocityThreshold: number;\n private previousCollisions: Map<string, CollisionInfo> = new Map();\n // Reused set for spatial queries to avoid allocation\n private queryResults: Set<Entity> = new Set();\n private readonly positionQuantizationStep: number | null;\n private readonly velocityQuantizationStep: number | null;\n private readonly resolverIterations: number;\n\n /**\n * Creates a new physics world\n * \n * @param config - World configuration\n */\n constructor(config: WorldConfig = {}) {\n this.timeStep = config.timeStep ?? 1 / 60;\n this.enableSleep = config.enableSleep ?? true;\n this.tileWidth = config.tileWidth ?? 32;\n this.tileHeight = config.tileHeight ?? 32;\n this.sleepThreshold = config.sleepThreshold ?? 0.5;\n this.sleepVelocityThreshold = config.sleepVelocityThreshold ?? 0.01;\n this.positionQuantizationStep =\n typeof config.positionQuantizationStep === 'number' && config.positionQuantizationStep > 0\n ? config.positionQuantizationStep\n : null;\n this.velocityQuantizationStep =\n typeof config.velocityQuantizationStep === 'number' && config.velocityQuantizationStep > 0\n ? config.velocityQuantizationStep\n : null;\n\n // Create integrator\n const integratorConfig: {\n deltaTime: number;\n method?: IntegrationMethod;\n gravity?: Vector2;\n } = {\n deltaTime: this.timeStep,\n method: config.integrationMethod ?? IntegrationMethod.Euler,\n };\n if (config.gravity) {\n integratorConfig.gravity = config.gravity;\n }\n this.integrator = new Integrator(integratorConfig);\n\n // Create collision resolver\n this.resolverIterations = Math.max(1, Math.floor(config.resolverIterations ?? 3));\n const resolverConfig: any = {};\n if (config.positionCorrectionFactor !== undefined) resolverConfig.positionCorrectionFactor = config.positionCorrectionFactor;\n if (config.maxPositionCorrection !== undefined) resolverConfig.maxPositionCorrection = config.maxPositionCorrection;\n if (config.minPenetrationDepth !== undefined) resolverConfig.minPenetrationDepth = config.minPenetrationDepth;\n\n this.resolver = new CollisionResolver(resolverConfig);\n\n // Create spatial partition\n if (config.spatialPartition) {\n this.spatialPartition = config.spatialPartition;\n } else {\n this.spatialPartition = new SpatialHash(\n config.spatialCellSize ?? 100,\n config.spatialGridWidth ?? 100,\n config.spatialGridHeight ?? 100\n );\n }\n\n // Create event system\n this.events = new EventSystem();\n }\n\n /**\n * Gets the event system\n * \n * @returns Event system instance\n */\n public getEvents(): EventSystem {\n return this.events;\n }\n\n /**\n * Returns the fixed simulation time step.\n *\n * @returns Time step in seconds\n */\n public getTimeStep(): number {\n return this.timeStep;\n }\n\n /**\n * Adds an entity to the world\n * \n * @param entity - Entity to add\n * @returns The added entity\n */\n public addEntity(entity: Entity): Entity {\n this.entities.add(entity);\n if (entity.isStatic()) {\n this.staticEntities.add(entity);\n } else {\n this.dynamicEntities.add(entity);\n }\n this.spatialPartition.insert(entity);\n this.events.emitEntityAdded(entity);\n return entity;\n }\n\n /**\n * Performs a raycast against all entities in the world.\n * \n * @param origin - Starting point of the ray\n * @param direction - Direction of the ray (normalized)\n * @param length - Maximum length (default: Infinity)\n * @param mask - Optional collision mask (layer)\n * @param filter - Optional filter function (return true to include entity)\n * @returns Raycast hit info if hit, null otherwise\n */\n public raycast(origin: Vector2, direction: Vector2, length: number = Infinity, mask?: number, filter?: (entity: Entity) => boolean): RaycastHit | null {\n const ray = new Ray(origin, direction, length);\n return this.spatialPartition.raycast(ray, mask, filter);\n }\n\n /**\n * Creates and adds a new entity\n * \n * @param config - Entity configuration\n * @returns Created entity\n */\n public createEntity(config: EntityConfig): Entity {\n const entity = new Entity(config);\n return this.addEntity(entity);\n }\n\n /**\n * Removes an entity from the world\n * \n * @param entity - Entity to remove\n */\n public removeEntity(entity: Entity): void {\n if (this.entities.delete(entity)) {\n this.staticEntities.delete(entity);\n this.dynamicEntities.delete(entity);\n this.spatialPartition.remove(entity);\n this.events.emitEntityRemoved(entity);\n }\n }\n\n /**\n * Gets all entities in the world\n * \n * @returns Array of entities\n */\n public getEntities(): Entity[] {\n return Array.from(this.entities);\n }\n\n /**\n * Gets an entity by UUID\n * \n * @param uuid - Entity UUID\n * @returns Entity or undefined\n */\n public getEntityByUUID(uuid: string): Entity | undefined {\n for (const entity of this.entities) {\n if (entity.uuid === uuid) {\n return entity;\n }\n }\n return undefined;\n }\n\n /**\n * Steps the physics simulation forward\n * \n * Updates all entities, detects and resolves collisions.\n */\n public step(): void {\n // Update spatial partition with the latest positions\n this.refreshDynamicEntitiesInPartition();\n\n // Clear forces and integrate\n for (const entity of this.dynamicEntities) {\n if (!entity.isSleeping()) {\n const startPos = entity.position.clone();\n this.integrator.integrate(entity);\n\n // Check for tile change\n this.updateEntityTile(entity, startPos);\n\n // CCD: Check for tunneling if enabled\n if (entity.continuous) {\n this.performCCD(entity);\n }\n }\n }\n\n let firstPassCollisions: CollisionInfo[] = [];\n for (let iteration = 0; iteration < this.resolverIterations; iteration++) {\n const collisions = this.detectCollisions();\n if (iteration === 0) {\n firstPassCollisions = collisions;\n }\n if (collisions.length === 0) {\n break;\n }\n this.sortCollisionsForDeterminism(collisions);\n this.resolver.resolveAll(collisions);\n if (iteration + 1 < this.resolverIterations) {\n this.refreshDynamicEntitiesInPartition();\n }\n }\n\n if (this.positionQuantizationStep !== null || this.velocityQuantizationStep !== null) {\n this.quantizeEntities();\n }\n\n this.handleCollisionEvents(firstPassCollisions);\n\n if (this.enableSleep) {\n this.updateSleepState();\n }\n }\n\n /**\n * Detects collisions using spatial partition\n * \n * @returns Array of collision infos\n */\n /**\n * Detects collisions using spatial partition\n * \n * @returns Array of collision infos\n */\n private detectCollisions(): CollisionInfo[] {\n const collisions: CollisionInfo[] = [];\n\n // Only dynamic entities initiate collision checks\n for (const entity of this.dynamicEntities) {\n // Query nearby entities using reused set\n const nearby = this.spatialPartition.query(entity, this.queryResults);\n\n for (const other of nearby) {\n // Avoid duplicate checks for dynamic-dynamic pairs\n // For dynamic-dynamic: only check if entity.uuid < other.uuid\n // For dynamic-static: always check (since static won't initiate)\n if (other.isDynamic() && entity.uuid > other.uuid) {\n continue;\n }\n\n // Test collision\n const collision = testCollision(entity, other);\n if (collision) {\n collisions.push(collision);\n }\n }\n }\n\n return collisions;\n }\n\n private sortCollisionsForDeterminism(collisions: CollisionInfo[]): void {\n collisions.sort((a, b) => {\n const keyA = this.getCollisionKey(a);\n const keyB = this.getCollisionKey(b);\n return keyA.localeCompare(keyB);\n });\n }\n\n private getCollisionKey(collision: CollisionInfo): string {\n const idA = collision.entityA.uuid;\n const idB = collision.entityB.uuid;\n return idA < idB ? `${idA}-${idB}` : `${idB}-${idA}`;\n }\n\n /**\n * Handles collision enter/exit events\n * \n * @param collisions - Current frame collisions\n */\n private handleCollisionEvents(collisions: CollisionInfo[]): void {\n const currentCollisions = new Map<string, CollisionInfo>();\n\n // Process current collisions\n for (const collision of collisions) {\n const pairKey = collision.entityA.uuid < collision.entityB.uuid\n ? `${collision.entityA.uuid}-${collision.entityB.uuid}`\n : `${collision.entityB.uuid}-${collision.entityA.uuid}`;\n\n currentCollisions.set(pairKey, collision);\n\n // Check if this is a new collision\n if (!this.previousCollisions.has(pairKey)) {\n this.events.emitCollisionEnter(collision);\n collision.entityA.notifyCollisionEnter(collision, collision.entityB);\n collision.entityB.notifyCollisionEnter(collision, collision.entityA);\n }\n }\n\n // Check for exit collisions\n for (const [pairKey, collision] of this.previousCollisions) {\n if (!currentCollisions.has(pairKey)) {\n this.events.emitCollisionExit(collision);\n collision.entityA.notifyCollisionExit(collision, collision.entityB);\n collision.entityB.notifyCollisionExit(collision, collision.entityA);\n }\n }\n\n // Update previous collisions\n this.previousCollisions = currentCollisions;\n }\n\n\n /**\n * Updates sleep state for entities\n */\n private updateSleepState(): void {\n for (const entity of this.entities) {\n if (entity.isStatic() || entity.isSleeping()) {\n continue;\n }\n\n const speed = entity.velocity.length();\n const angularSpeed = Math.abs(entity.angularVelocity);\n\n if (speed < this.sleepVelocityThreshold && angularSpeed < this.sleepVelocityThreshold) {\n entity.timeSinceMovement += this.timeStep;\n\n if (entity.timeSinceMovement >= this.sleepThreshold) {\n entity.sleep();\n this.events.emitEntitySleep(entity);\n }\n } else {\n entity.timeSinceMovement = 0;\n if (entity.isSleeping()) {\n entity.wakeUp();\n this.events.emitEntityWake(entity);\n }\n }\n }\n }\n\n /**\n * Clears all entities from the world\n */\n public clear(): void {\n for (const entity of this.entities) {\n this.events.emitEntityRemoved(entity);\n }\n this.entities.clear();\n this.spatialPartition.clear();\n this.previousCollisions.clear();\n }\n\n private quantizeEntities(): void {\n for (const entity of this.dynamicEntities) {\n if (this.positionQuantizationStep !== null) {\n entity.position.x = this.quantizeValue(entity.position.x, this.positionQuantizationStep);\n entity.position.y = this.quantizeValue(entity.position.y, this.positionQuantizationStep);\n }\n if (this.velocityQuantizationStep !== null) {\n entity.velocity.x = this.quantizeValue(entity.velocity.x, this.velocityQuantizationStep);\n entity.velocity.y = this.quantizeValue(entity.velocity.y, this.velocityQuantizationStep);\n }\n }\n }\n\n private quantizeValue(value: number, step: number): number {\n return Math.round(value / step) * step;\n }\n\n private refreshDynamicEntitiesInPartition(): void {\n for (const entity of this.dynamicEntities) {\n this.spatialPartition.update(entity);\n }\n }\n\n /**\n * Gets statistics about the world\n * \n * @returns Statistics object\n */\n public getStats(): {\n totalEntities: number;\n dynamicEntities: number;\n staticEntities: number;\n sleepingEntities: number;\n } {\n let dynamic = 0;\n let static_ = 0;\n let sleeping = 0;\n\n for (const entity of this.entities) {\n if (entity.isStatic()) {\n static_++;\n } else {\n dynamic++;\n }\n if (entity.isSleeping()) {\n sleeping++;\n }\n }\n\n return {\n totalEntities: this.entities.size,\n dynamicEntities: dynamic,\n staticEntities: static_,\n sleepingEntities: sleeping,\n };\n }\n\n /**\n * Performs Continuous Collision Detection (CCD) for an entity\n * \n * @param entity - Entity to check\n */\n /**\n * Updates entity tile position and triggers hooks\n * \n * @param entity - Entity to update\n * @param previousPosition - Position before integration\n */\n private updateEntityTile(entity: Entity, previousPosition: Vector2): void {\n const oldTileX = Math.floor(previousPosition.x / this.tileWidth);\n const oldTileY = Math.floor(previousPosition.y / this.tileHeight);\n\n const newTileX = Math.floor(entity.position.x / this.tileWidth);\n const newTileY = Math.floor(entity.position.y / this.tileHeight);\n\n // Initialize currentTile if it's the first update (or if it was 0,0 by default)\n // We assume the entity starts in a valid tile or we sync it now\n if (entity.currentTile.x === 0 && entity.currentTile.y === 0 && (oldTileX !== 0 || oldTileY !== 0)) {\n entity.currentTile.set(oldTileX, oldTileY);\n }\n\n if (newTileX !== oldTileX || newTileY !== oldTileY) {\n // Check if can enter new tile\n if (!entity.checkCanEnterTile(newTileX, newTileY)) {\n // Prevent movement: revert to previous position\n // We also zero out velocity to stop momentum into the blocked tile\n entity.position.copyFrom(previousPosition);\n entity.velocity.set(0, 0);\n return;\n }\n\n // Trigger hooks\n entity.notifyLeaveTile(oldTileX, oldTileY);\n entity.currentTile.set(newTileX, newTileY);\n entity.notifyEnterTile(newTileX, newTileY);\n }\n }\n\n private performCCD(entity: Entity): void {\n // Simple CCD: Sweep against nearby static entities\n // We use the velocity * dt as the sweep vector\n // Note: This happens AFTER integration, so we are checking if the movement\n // that JUST happened caused tunneling.\n // Ideally CCD should happen BEFORE position update, or we re-integrate?\n // Standard approach:\n // 1. Integrate velocity\n // 2. Sweep from oldPos to newPos\n // 3. If hit, clamp position\n\n // Since we already integrated, we can reconstruct the motion:\n // delta = velocity * dt\n // But position is already updated.\n // Let's assume we want to prevent tunneling through static objects.\n\n // We need the previous position? Entity doesn't store it by default.\n // But we know velocity.\n // Let's approximate: sweep backwards? Or just check along the path.\n\n // Better: Check against potential colliders in the path.\n const dt = this.timeStep;\n const delta = entity.velocity.mul(dt);\n const dist = delta.length();\n\n if (dist < entity.radius) {\n // Moving slowly enough that discrete collision should catch it\n return;\n }\n\n // Calculate swept AABB\n const collider = createCollider(entity);\n if (!collider) return;\n\n const currentBounds = collider.getBounds();\n const originalBounds = currentBounds.translate(-delta.x, -delta.y);\n const sweptBounds = currentBounds.union(originalBounds);\n\n const nearby = this.spatialPartition.queryAABB(sweptBounds);\n let minTime = 1.0;\n let collision = null;\n\n for (const other of nearby) {\n if (other === entity || !other.isStatic()) continue;\n if (!entity.canCollideWith(other)) continue;\n\n // Sweep entity against other\n // We need to sweep from (pos - delta) to pos\n // Or equivalent: sweep other (static) against entity moving by -delta?\n // Let's use sweepEntities helper\n\n // We want to check if entity moving by 'delta' hits 'other'.\n // But entity is ALREADY at 'pos'.\n // So effectively we are checking if it hit something on the way.\n\n // Let's temporarily move entity back\n const originalPos = entity.position.clone();\n entity.position.subInPlace(delta);\n\n const hit = sweepEntities(entity, other, delta);\n\n // Restore position\n entity.position.copyFrom(originalPos);\n\n if (hit && hit.time < minTime) {\n minTime = hit.time;\n collision = hit;\n }\n }\n\n if (collision && minTime < 1.0) {\n // Clamp position to impact point\n // Move to impact point + small epsilon offset\n const correction = collision.normal.mul(0.001); // Epsilon\n entity.position.subInPlace(delta.mul(1 - minTime)).addInPlace(correction);\n\n // Kill velocity in normal direction\n const vn = entity.velocity.dot(collision.normal);\n if (vn < 0) {\n entity.velocity.subInPlace(collision.normal.mul(vn));\n }\n }\n }\n}\n\n","import { World } from '../world/World';\nimport { Entity } from '../physics/Entity';\nimport { AABB } from '../core/math/AABB';\nimport { Vector2 } from '../core/math/Vector2';\n\n/**\n * Region configuration\n */\nexport interface RegionConfig {\n /** Region bounds */\n bounds: AABB;\n /** Overlap size with neighboring regions (default: 0) */\n overlap?: number;\n /** Whether this region is active (default: true) */\n active?: boolean;\n}\n\n/**\n * Physical region in a distributed world\n * \n * Represents an independent simulation zone that can contain entities.\n * Regions can overlap to allow smooth entity transitions.\n * \n * @example\n * ```typescript\n * const region = new Region({\n * bounds: new AABB(0, 0, 100, 100),\n * overlap: 10\n * });\n * ```\n */\nexport class Region {\n private world: World;\n private bounds: AABB;\n private overlap: number;\n private active: boolean;\n private entities: Set<Entity> = new Set();\n\n /**\n * Creates a new region\n * \n * @param config - Region configuration\n */\n constructor(config: RegionConfig) {\n this.bounds = config.bounds.clone();\n this.overlap = config.overlap ?? 0;\n this.active = config.active ?? true;\n\n // Create world for this region\n this.world = new World({\n spatialCellSize: 50,\n spatialGridWidth: 50,\n spatialGridHeight: 50,\n });\n }\n\n /**\n * Gets the region bounds\n * \n * @returns AABB bounds\n */\n public getBounds(): AABB {\n return this.bounds.clone();\n }\n\n /**\n * Gets the expanded bounds including overlap\n * \n * @returns Expanded AABB\n */\n public getExpandedBounds(): AABB {\n return this.bounds.expand(this.overlap);\n }\n\n /**\n * Checks if a point is inside this region\n * \n * @param point - Point to check\n * @returns True if point is inside\n */\n public contains(point: Vector2): boolean {\n return this.bounds.contains(point);\n }\n\n /**\n * Checks if an entity should belong to this region\n * \n * @param entity - Entity to check\n * @returns True if entity should be in this region\n */\n public shouldContain(entity: Entity): boolean {\n return this.bounds.contains(entity.position);\n }\n\n /**\n * Adds an entity to this region\n * \n * @param entity - Entity to add\n */\n public addEntity(entity: Entity): void {\n if (this.entities.has(entity)) {\n return;\n }\n this.entities.add(entity);\n this.world.addEntity(entity);\n }\n\n /**\n * Removes an entity from this region\n * \n * @param entity - Entity to remove\n */\n public removeEntity(entity: Entity): void {\n if (this.entities.delete(entity)) {\n this.world.removeEntity(entity);\n }\n }\n\n /**\n * Gets all entities in this region\n * \n * @returns Array of entities\n */\n public getEntities(): Entity[] {\n return Array.from(this.entities);\n }\n\n /**\n * Steps the region's physics simulation\n */\n public step(): void {\n if (!this.active) {\n return;\n }\n this.world.step();\n }\n\n /**\n * Activates this region\n */\n public activate(): void {\n this.active = true;\n }\n\n /**\n * Deactivates this region\n */\n public deactivate(): void {\n this.active = false;\n }\n\n /**\n * Checks if this region is active\n * \n * @returns True if active\n */\n public isActive(): boolean {\n return this.active;\n }\n\n /**\n * Gets the world instance for this region\n * \n * @returns World instance\n */\n public getWorld(): World {\n return this.world;\n }\n\n /**\n * Checks if this region overlaps with another region\n * \n * @param other - Other region to check\n * @returns True if regions overlap\n */\n public overlaps(other: Region): boolean {\n const expandedA = this.getExpandedBounds();\n const expandedB = other.getExpandedBounds();\n return expandedA.intersects(expandedB);\n }\n\n /**\n * Gets entities that might need migration to neighboring regions\n * \n * @returns Array of entities near region boundaries\n */\n public getBoundaryEntities(): Entity[] {\n const boundaryEntities: Entity[] = [];\n const expandedBounds = this.getExpandedBounds();\n\n for (const entity of this.entities) {\n // Check if entity is in overlap zone\n if (expandedBounds.contains(entity.position) && !this.bounds.contains(entity.position)) {\n boundaryEntities.push(entity);\n }\n }\n\n return boundaryEntities;\n }\n}\n\n","import { Region } from './Region';\nimport { Entity } from '../physics/Entity';\nimport { AABB } from '../core/math/AABB';\nimport { Vector2 } from '../core/math/Vector2';\n\n/**\n * Region manager configuration\n */\nexport interface RegionManagerConfig {\n /** World bounds */\n worldBounds: AABB;\n /** Region size (width and height) */\n regionSize: number;\n /** Overlap between regions */\n overlap?: number;\n /** Auto-activate regions based on entity presence (default: true) */\n autoActivate?: boolean;\n}\n\n/**\n * Region manager\n * \n * Manages multiple regions in a distributed physics world.\n * Handles entity migration between regions and region activation/deactivation.\n * \n * @example\n * ```typescript\n * const manager = new RegionManager({\n * worldBounds: new AABB(0, 0, 1000, 1000),\n * regionSize: 200,\n * overlap: 20\n * });\n * ```\n */\nexport class RegionManager {\n private regions: Region[] = [];\n private regionMap: Map<string, Region> = new Map();\n private config: Required<Omit<RegionManagerConfig, 'worldBounds'>> & { worldBounds: AABB };\n private entityRegionMap: Map<Entity, Region> = new Map();\n\n /**\n * Creates a new region manager\n * \n * @param config - Manager configuration\n */\n constructor(config: RegionManagerConfig) {\n this.config = {\n worldBounds: config.worldBounds,\n regionSize: config.regionSize,\n overlap: config.overlap ?? 0,\n autoActivate: config.autoActivate ?? true,\n };\n\n this.createRegions();\n }\n\n /**\n * Creates the grid of regions\n */\n private createRegions(): void {\n const { worldBounds, regionSize, overlap } = this.config;\n const worldWidth = worldBounds.getWidth();\n const worldHeight = worldBounds.getHeight();\n\n const cols = Math.ceil(worldWidth / regionSize);\n const rows = Math.ceil(worldHeight / regionSize);\n\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) {\n const minX = worldBounds.minX + col * regionSize;\n const minY = worldBounds.minY + row * regionSize;\n const maxX = Math.min(minX + regionSize, worldBounds.maxX);\n const maxY = Math.min(minY + regionSize, worldBounds.maxY);\n\n const bounds = new AABB(minX, minY, maxX, maxY);\n const region = new Region({\n bounds,\n overlap,\n active: !this.config.autoActivate, // Start inactive if auto-activate is enabled\n });\n\n const key = this.getRegionKey(col, row);\n this.regions.push(region);\n this.regionMap.set(key, region);\n }\n }\n }\n\n /**\n * Gets a region key from grid coordinates\n * \n * @param col - Column index\n * @param row - Row index\n * @returns Region key string\n */\n private getRegionKey(col: number, row: number): string {\n return `${col},${row}`;\n }\n\n /**\n * Gets the region containing a point\n * \n * @param point - Point to find region for\n * @returns Region or null\n */\n public getRegionAt(point: Vector2): Region | null {\n for (const region of this.regions) {\n if (region.contains(point)) {\n return region;\n }\n }\n return null;\n }\n\n /**\n * Gets all regions that overlap with an AABB\n * \n * @param bounds - AABB to check\n * @returns Array of overlapping regions\n */\n public getRegionsInBounds(bounds: AABB): Region[] {\n const result: Region[] = [];\n for (const region of this.regions) {\n if (region.getExpandedBounds().intersects(bounds)) {\n result.push(region);\n }\n }\n return result;\n }\n\n /**\n * Adds an entity to the appropriate region\n * \n * @param entity - Entity to add\n */\n public addEntity(entity: Entity): void {\n const region = this.getRegionAt(entity.position);\n if (region) {\n region.addEntity(entity);\n this.entityRegionMap.set(entity, region);\n\n if (this.config.autoActivate) {\n region.activate();\n }\n }\n }\n\n /**\n * Removes an entity from its region\n * \n * @param entity - Entity to remove\n */\n public removeEntity(entity: Entity): void {\n const region = this.entityRegionMap.get(entity);\n if (region) {\n region.removeEntity(entity);\n this.entityRegionMap.delete(entity);\n\n if (this.config.autoActivate && region.getEntities().length === 0) {\n region.deactivate();\n }\n }\n }\n\n /**\n * Updates entity positions and migrates them between regions if needed\n */\n public updateEntities(): void {\n const entitiesToMigrate: Array<{ entity: Entity; newRegion: Region }> = [];\n\n for (const [entity, currentRegion] of this.entityRegionMap) {\n if (!currentRegion.shouldContain(entity)) {\n const newRegion = this.getRegionAt(entity.position);\n if (newRegion && newRegion !== currentRegion) {\n entitiesToMigrate.push({ entity, newRegion });\n }\n }\n }\n\n // Perform migrations\n for (const { entity, newRegion } of entitiesToMigrate) {\n const oldRegion = this.entityRegionMap.get(entity);\n if (oldRegion) {\n oldRegion.removeEntity(entity);\n }\n newRegion.addEntity(entity);\n this.entityRegionMap.set(entity, newRegion);\n\n if (this.config.autoActivate) {\n newRegion.activate();\n }\n }\n }\n\n /**\n * Steps all active regions\n */\n public step(): void {\n // Update entity positions first\n this.updateEntities();\n\n // Step each active region\n for (const region of this.regions) {\n if (region.isActive()) {\n region.step();\n }\n }\n }\n\n /**\n * Gets all regions\n * \n * @returns Array of all regions\n */\n public getRegions(): Region[] {\n return [...this.regions];\n }\n\n /**\n * Gets active regions\n * \n * @returns Array of active regions\n */\n public getActiveRegions(): Region[] {\n return this.regions.filter((r) => r.isActive());\n }\n\n /**\n * Gets the region containing an entity\n * \n * @param entity - Entity to find region for\n * @returns Region or null\n */\n public getEntityRegion(entity: Entity): Region | null {\n return this.entityRegionMap.get(entity) ?? null;\n }\n\n /**\n * Clears all entities from all regions\n */\n public clear(): void {\n for (const region of this.regions) {\n const entities = region.getEntities();\n for (const entity of entities) {\n region.removeEntity(entity);\n }\n }\n this.entityRegionMap.clear();\n }\n\n /**\n * Gets statistics about regions\n * \n * @returns Statistics object\n */\n public getStats(): {\n totalRegions: number;\n activeRegions: number;\n totalEntities: number;\n } {\n let totalEntities = 0;\n for (const region of this.regions) {\n totalEntities += region.getEntities().length;\n }\n\n return {\n totalRegions: this.regions.length,\n activeRegions: this.getActiveRegions().length,\n totalEntities,\n };\n }\n}\n\n","import { Vector2 } from '../../core/math/Vector2';\nimport { Entity } from '../../physics/Entity';\nimport { MovementBody } from '../MovementStrategy';\n\n/**\n * Wraps a physics entity to expose the generic `MovementBody` interface.\n */\nexport class EntityMovementBody implements MovementBody {\n constructor(private readonly entity: Entity) {}\n\n get id(): string {\n return this.entity.uuid;\n }\n\n get position(): { x: number; y: number } {\n return this.entity.position;\n }\n\n get velocity(): { x: number; y: number } {\n return this.entity.velocity;\n }\n\n setVelocity(velocity: { x: number; y: number }): void {\n this.entity.setVelocity(velocity);\n }\n\n translate(delta: { x: number; y: number }): void {\n this.entity.position.addInPlace(new Vector2(delta.x, delta.y));\n }\n\n isStatic(): boolean {\n return this.entity.isStatic();\n }\n\n /**\n * Returns the underlying entity reference.\n */\n getEntity(): Entity {\n return this.entity;\n }\n}\n\n","import { PhysicsEngine } from '../api/PhysicsEngine';\nimport { Entity } from '../physics/Entity';\nimport { EntityMovementBody } from './adapters/EntityMovementBody';\nimport { MovementBody, MovementStrategy, MovementOptions } from './MovementStrategy';\n\n/**\n * Resolves an entity from an identifier.\n *\n * When provided to the movement manager, the resolver enables ergonomic calls\n * that pass a string identifier instead of the `Entity` instance.\n *\n * @example\n * ```typescript\n * const manager = new MovementManager((id) => engine.getEntityByUUID(id));\n * manager.add(player.uuid, new Dash(6, { x: 1, y: 0 }, 0.2));\n * ```\n */\nexport type EntityResolver = (id: string) => MovementBody | undefined;\n\n/**\n * Internal entry for tracking a strategy with its options and Promise resolver\n */\ninterface StrategyEntry {\n strategy: MovementStrategy;\n options?: MovementOptions;\n resolve?: () => void;\n started: boolean;\n}\n\ninterface MovementEntry {\n body: MovementBody;\n strategies: StrategyEntry[];\n}\n\n/**\n * Manages movement strategies assigned to entities.\n *\n * The manager executes strategies before each physics step, removes completed\n * behaviours and exposes utilities to inspect and maintain assignments.\n *\n * @example\n * ```typescript\n * const manager = new MovementManager((id) => engine.getEntityByUUID(id));\n * manager.add(playerEntity, new LinearMove({ x: 2, y: 0 }));\n *\n * // Game loop\n * manager.update(deltaSeconds);\n * engine.step();\n * ```\n */\nexport class MovementManager {\n private readonly entries: Map<string, MovementEntry> = new Map();\n private readonly entityWrappers = new WeakMap<Entity, EntityMovementBody>();\n\n constructor(private readonly resolveEntity?: EntityResolver) {}\n\n /**\n * Convenience factory that binds the manager to a physics engine.\n *\n * @param engine - Physics engine whose entities will be controlled\n * @returns A movement manager configured with an entity resolver\n */\n static forEngine(engine: PhysicsEngine): MovementManager {\n let manager: MovementManager;\n manager = new MovementManager((id) => {\n const entity = engine.getEntityByUUID(id);\n return entity ? manager.wrapEntity(entity) : undefined;\n });\n return manager;\n }\n\n /**\n * Adds a movement strategy to an entity.\n * \n * Returns a Promise that resolves when the movement completes (when `isFinished()` returns true).\n * If the strategy doesn't implement `isFinished()`, the Promise resolves immediately after adding.\n *\n * @param target - Entity instance or entity UUID when a resolver is configured\n * @param strategy - Strategy to execute\n * @param options - Optional callbacks for movement lifecycle events\n * @returns Promise that resolves when the movement completes\n * \n * @example\n * ```typescript\n * // Simple usage - fire and forget\n * manager.add(player, new Dash(8, { x: 1, y: 0 }, 200));\n * \n * // Wait for completion\n * await manager.add(player, new Dash(8, { x: 1, y: 0 }, 200));\n * console.log('Dash finished!');\n * \n * // With callbacks\n * await manager.add(player, new Knockback({ x: -1, y: 0 }, 5, 300), {\n * onStart: () => {\n * player.directionFixed = true;\n * player.animationFixed = true;\n * },\n * onComplete: () => {\n * player.directionFixed = false;\n * player.animationFixed = false;\n * }\n * });\n * ```\n */\n add(target: Entity | MovementBody | string, strategy: MovementStrategy, options?: MovementOptions): Promise<void> {\n const body = this.resolveTarget(target);\n const key = body.id;\n\n if (!this.entries.has(key)) {\n this.entries.set(key, { body, strategies: [] });\n }\n\n // If the strategy doesn't have isFinished, resolve immediately\n if (!strategy.isFinished) {\n const entry: StrategyEntry = { strategy, started: false };\n if (options) {\n entry.options = options;\n }\n this.entries.get(key)!.strategies.push(entry);\n return Promise.resolve();\n }\n\n // Create a Promise that will resolve when the strategy finishes\n return new Promise<void>((resolve) => {\n const entry: StrategyEntry = { strategy, resolve, started: false };\n if (options) {\n entry.options = options;\n }\n this.entries.get(key)!.strategies.push(entry);\n });\n }\n\n /**\n * Removes a specific strategy from an entity.\n * \n * Note: This will NOT trigger the onComplete callback or resolve the Promise.\n * Use this when you want to cancel a movement without completion.\n *\n * @param target - Entity instance or identifier\n * @param strategy - Strategy instance to remove\n * @returns True when the strategy has been removed\n */\n remove(target: Entity | MovementBody | string, strategy: MovementStrategy): boolean {\n const body = this.resolveTarget(target);\n const entry = this.entries.get(body.id);\n if (!entry) {\n return false;\n }\n\n const index = entry.strategies.findIndex(e => e.strategy === strategy);\n if (index === -1) {\n return false;\n }\n\n entry.strategies.splice(index, 1);\n if (entry.strategies.length === 0) {\n this.entries.delete(body.id);\n }\n return true;\n }\n\n /**\n * Removes all strategies from an entity.\n *\n * @param target - Entity or identifier\n */\n clear(target: Entity | MovementBody | string): void {\n const body = this.resolveTarget(target);\n this.entries.delete(body.id);\n }\n\n /**\n * Stops all movement for an entity immediately\n * \n * This method completely stops an entity's movement by:\n * - Removing all active movement strategies (dash, linear moves, etc.)\n * - Stopping the entity's velocity and angular velocity\n * - Clearing accumulated forces\n * - Waking up the entity if it was sleeping\n * \n * This is useful when changing maps, teleporting, or when you need\n * to halt an entity's movement completely without making it static.\n * \n * @param target - Entity, MovementBody, or identifier\n * \n * @example\n * ```ts\n * // Stop movement when changing maps\n * if (mapChanged) {\n * movement.stopMovement(playerEntity);\n * }\n * \n * // Stop movement after teleporting\n * entity.position.set(100, 200);\n * movement.stopMovement(entity);\n * \n * // Stop movement when player dies\n * if (player.isDead()) {\n * movement.stopMovement(playerEntity);\n * }\n * ```\n */\n stopMovement(target: Entity | MovementBody | string): void {\n const body = this.resolveTarget(target);\n \n // Remove all movement strategies\n this.clear(target);\n \n // If the body wraps an Entity, stop its movement directly\n if ('getEntity' in body && typeof (body as any).getEntity === 'function') {\n const entity = (body as any).getEntity();\n if (entity && typeof entity.stopMovement === 'function') {\n entity.stopMovement();\n }\n }\n }\n\n /**\n * Checks if an entity has active strategies.\n *\n * @param target - Entity or identifier\n * @returns True when strategies are registered\n */\n hasActiveStrategies(target: Entity | MovementBody | string): boolean {\n const body = this.resolveTarget(target);\n return (this.entries.get(body.id)?.strategies.length ?? 0) > 0;\n }\n\n /**\n * Returns a snapshot of the strategies assigned to an entity.\n *\n * @param target - Entity or identifier\n * @returns Copy of the strategies array (empty array when none)\n */\n getStrategies(target: Entity | MovementBody | string): MovementStrategy[] {\n const body = this.resolveTarget(target);\n const entry = this.entries.get(body.id);\n return entry ? entry.strategies.map(e => e.strategy) : [];\n }\n\n /**\n * Updates all registered strategies.\n *\n * Call this method once per frame before `PhysicsEngine.step()` so that the\n * physics simulation integrates the velocities that strategies configure.\n * \n * This method handles the movement lifecycle:\n * - Triggers `onStart` callback on first update\n * - Calls `strategy.update()` each frame\n * - When `isFinished()` returns true:\n * - Calls `strategy.onFinished()` if defined\n * - Triggers `onComplete` callback\n * - Resolves the Promise returned by `add()`\n *\n * @param dt - Time delta in seconds\n */\n update(dt: number): void {\n for (const [key, entry] of this.entries) {\n const { body, strategies } = entry;\n\n if (strategies.length === 0) {\n this.entries.delete(key);\n continue;\n }\n\n for (let i = strategies.length - 1; i >= 0; i -= 1) {\n const strategyEntry = strategies[i];\n if (!strategyEntry) {\n continue;\n }\n\n const { strategy, options, resolve } = strategyEntry;\n\n // Trigger onStart on first update\n if (!strategyEntry.started) {\n strategyEntry.started = true;\n options?.onStart?.();\n }\n\n strategy.update(body, dt);\n\n const isFinished = strategy.isFinished?.();\n\n if (isFinished) {\n strategies.splice(i, 1);\n \n // Call strategy's own onFinished callback\n strategy.onFinished?.();\n \n // Call options onComplete callback\n options?.onComplete?.();\n \n // Resolve the Promise\n resolve?.();\n }\n }\n\n if (strategies.length === 0) {\n this.entries.delete(key);\n }\n }\n }\n\n /**\n * Removes all strategies from all entities.\n */\n clearAll(): void {\n this.entries.clear();\n }\n\n private resolveTarget(target: Entity | MovementBody | string): MovementBody {\n if (this.isMovementBody(target)) {\n return target;\n }\n\n if (target instanceof Entity) {\n return this.wrapEntity(target);\n }\n\n if (!this.resolveEntity) {\n throw new Error('MovementManager: cannot resolve entity from identifier without a resolver.');\n }\n\n const entity = this.resolveEntity(target);\n if (!entity) {\n throw new Error(`MovementManager: unable to resolve entity for identifier ${target}.`);\n }\n return entity;\n }\n\n private wrapEntity(entity: Entity): EntityMovementBody {\n let wrapper = this.entityWrappers.get(entity);\n if (!wrapper) {\n wrapper = new EntityMovementBody(entity);\n this.entityWrappers.set(entity, wrapper);\n }\n return wrapper;\n }\n\n private isMovementBody(value: unknown): value is MovementBody {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'id' in value &&\n 'setVelocity' in value &&\n typeof (value as MovementBody).setVelocity === 'function',\n );\n }\n}\n\n","import { PhysicsEngine } from './PhysicsEngine';\nimport { Entity } from '../physics/Entity';\nimport { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport { generateUUID } from '../utils/uuid';\n\n/**\n * Direction value for zone orientation (used for cone-shaped zones)\n */\nexport type ZoneDirection = 'up' | 'down' | 'left' | 'right';\n\n/**\n * Configuration for a static zone (fixed position in the world)\n */\nexport interface StaticZoneConfig {\n /** Zone position in world coordinates */\n position: Vector2 | { x: number; y: number };\n /** Zone radius */\n radius: number;\n /** Cone angle in degrees (360 = full circle, < 360 = cone) */\n angle?: number;\n /** Direction for cone-shaped zones */\n direction?: ZoneDirection;\n /** Whether line-of-sight is required (blocks through static entities) */\n limitedByWalls?: boolean;\n /** Optional metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Configuration for a zone attached to an entity\n */\nexport interface AttachedZoneConfig {\n /** Entity to attach the zone to */\n entity: Entity;\n /** Offset from entity position (default: {x: 0, y: 0}) */\n offset?: Vector2 | { x: number; y: number };\n /** Zone radius */\n radius: number;\n /** Cone angle in degrees (360 = full circle, < 360 = cone) */\n angle?: number;\n /** Direction for cone-shaped zones (can be relative to entity rotation or fixed) */\n direction?: ZoneDirection;\n /** Whether line-of-sight is required (blocks through static entities) */\n limitedByWalls?: boolean;\n /** Optional metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Union type for zone configuration\n */\nexport type ZoneConfig = StaticZoneConfig | AttachedZoneConfig;\n\n/**\n * Zone event callbacks\n */\nexport interface ZoneCallbacks {\n /**\n * Called when entities enter the zone\n * @param entities - Array of entities that entered\n */\n onEnter?: (entities: Entity[]) => void;\n /**\n * Called when entities exit the zone\n * @param entities - Array of entities that exited\n */\n onExit?: (entities: Entity[]) => void;\n}\n\n/**\n * Public zone information\n */\nexport interface ZoneInfo {\n id: string;\n type: 'static' | 'attached';\n position: Vector2;\n radius: number;\n angle: number;\n direction: ZoneDirection;\n limitedByWalls: boolean;\n metadata?: Record<string, any> | undefined;\n}\n\n/**\n * Internal zone record\n */\ninterface ZoneRecord extends ZoneInfo {\n attachedEntity?: Entity | undefined;\n offset?: Vector2 | undefined;\n callbacks?: ZoneCallbacks | undefined;\n inside: Set<string>; // Set of entity UUIDs currently inside\n}\n\n/**\n * Zone manager for detecting entities within circular/cone-shaped areas.\n *\n * Zones can be used for vision, skill ranges, explosions, and other gameplay mechanics\n * that need to detect entities without physical collisions.\n *\n * @example\n * ```typescript\n * const engine = new PhysicsEngine({ timeStep: 1/60 });\n * const zones = new ZoneManager(engine);\n *\n * // Create a static zone\n * const zoneId = zones.createZone({\n * position: { x: 100, y: 100 },\n * radius: 50,\n * onEnter: (entities) => console.log('Entities entered:', entities),\n * });\n *\n * // Create a zone attached to an entity\n * const player = engine.createEntity({ position: { x: 0, y: 0 }, radius: 10 });\n * const visionZone = zones.createAttachedZone(player, {\n * radius: 100,\n * angle: 90,\n * direction: 'right',\n * onEnter: (entities) => console.log('Player sees:', entities),\n * });\n *\n * // Update zones after each physics step\n * engine.step();\n * zones.update();\n * ```\n */\nexport class ZoneManager {\n private readonly engine: PhysicsEngine;\n private readonly zones = new Map<string, ZoneRecord>();\n\n /**\n * Creates a new zone manager\n *\n * @param engine - Physics engine instance\n */\n constructor(engine: PhysicsEngine) {\n this.engine = engine;\n }\n\n /**\n * Creates a new zone\n *\n * @param config - Zone configuration\n * @param callbacks - Optional event callbacks\n * @returns Zone identifier\n *\n * @example\n * ```typescript\n * const zoneId = zones.createZone({\n * position: { x: 100, y: 100 },\n * radius: 50,\n * angle: 180,\n * direction: 'right',\n * }, {\n * onEnter: (entities) => console.log('Entered:', entities),\n * onExit: (entities) => console.log('Exited:', entities),\n * });\n * ```\n */\n createZone(\n config: ZoneConfig,\n callbacks?: ZoneCallbacks,\n ): string {\n const id = generateUUID();\n const radius = config.radius;\n if (typeof radius !== 'number' || radius <= 0) {\n throw new Error('Zone radius must be a positive number');\n }\n\n const angle = config.angle ?? 360;\n const direction = config.direction ?? 'down';\n const limitedByWalls = config.limitedByWalls ?? false;\n\n let position: Vector2;\n let type: 'static' | 'attached';\n let attachedEntity: Entity | undefined;\n let offset: Vector2 | undefined;\n\n if ('entity' in config) {\n // Attached zone\n type = 'attached';\n attachedEntity = config.entity;\n const entityPos = attachedEntity.position;\n const offsetValue = config.offset ?? { x: 0, y: 0 };\n if (offsetValue instanceof Vector2) {\n offset = offsetValue.clone();\n } else {\n offset = new Vector2(offsetValue.x, offsetValue.y);\n }\n position = new Vector2(entityPos.x + offset.x, entityPos.y + offset.y);\n } else {\n // Static zone\n type = 'static';\n const pos = config.position;\n if (pos instanceof Vector2) {\n position = pos.clone();\n } else {\n position = new Vector2(pos.x, pos.y);\n }\n }\n\n const record: ZoneRecord = {\n id,\n type,\n position,\n radius,\n angle,\n direction,\n limitedByWalls,\n metadata: config.metadata,\n attachedEntity,\n offset,\n callbacks,\n inside: new Set(),\n };\n\n this.zones.set(id, record);\n return id;\n }\n\n /**\n * Creates a zone attached to an entity (convenience method)\n *\n * @param entity - Entity to attach the zone to\n * @param config - Zone configuration\n * @param callbacks - Optional event callbacks\n * @returns Zone identifier\n *\n * @example\n * ```typescript\n * const visionZone = zones.createAttachedZone(player, {\n * radius: 100,\n * angle: 90,\n * direction: 'right',\n * offset: { x: 0, y: -10 },\n * }, {\n * onEnter: (entities) => console.log('Player sees:', entities),\n * });\n * ```\n */\n createAttachedZone(\n entity: Entity,\n config: Omit<AttachedZoneConfig, 'entity'>,\n callbacks?: ZoneCallbacks,\n ): string {\n return this.createZone({ ...config, entity }, callbacks);\n }\n\n /**\n * Updates a zone's configuration\n *\n * @param id - Zone identifier\n * @param updates - Partial configuration updates\n * @returns True if the zone was found and updated\n *\n * @example\n * ```typescript\n * zones.updateZone(zoneId, { radius: 75, angle: 120 });\n * ```\n */\n updateZone(id: string, updates: Partial<ZoneConfig>): boolean {\n const zone = this.zones.get(id);\n if (!zone) return false;\n\n if (updates.radius !== undefined) {\n if (typeof updates.radius !== 'number' || updates.radius <= 0) {\n throw new Error('Zone radius must be a positive number');\n }\n zone.radius = updates.radius;\n }\n\n if (updates.angle !== undefined) {\n zone.angle = updates.angle;\n }\n\n if (updates.direction !== undefined) {\n zone.direction = updates.direction;\n }\n\n if (updates.limitedByWalls !== undefined) {\n zone.limitedByWalls = updates.limitedByWalls;\n }\n\n if (updates.metadata !== undefined) {\n zone.metadata = updates.metadata;\n }\n\n if ('offset' in updates && updates.offset !== undefined && zone.type === 'attached') {\n const offsetValue = updates.offset;\n if (offsetValue instanceof Vector2) {\n zone.offset = offsetValue.clone();\n } else {\n zone.offset = new Vector2(offsetValue.x, offsetValue.y);\n }\n }\n\n return true;\n }\n\n /**\n * Registers or updates callbacks for a zone\n *\n * @param id - Zone identifier\n * @param callbacks - Event callbacks\n * @returns True if the zone was found\n *\n * @example\n * ```typescript\n * zones.registerCallbacks(zoneId, {\n * onEnter: (entities) => console.log('Entered:', entities),\n * onExit: (entities) => console.log('Exited:', entities),\n * });\n * ```\n */\n registerCallbacks(id: string, callbacks: ZoneCallbacks): boolean {\n const zone = this.zones.get(id);\n if (!zone) return false;\n zone.callbacks = callbacks;\n return true;\n }\n\n /**\n * Removes a zone\n *\n * @param id - Zone identifier\n * @returns True if the zone was found and removed\n */\n removeZone(id: string): boolean {\n return this.zones.delete(id);\n }\n\n /**\n * Gets zone information\n *\n * @param id - Zone identifier\n * @returns Zone information or undefined\n */\n getZone(id: string): ZoneInfo | undefined {\n const zone = this.zones.get(id);\n if (!zone) return undefined;\n\n return {\n id: zone.id,\n type: zone.type,\n position: zone.position.clone(),\n radius: zone.radius,\n angle: zone.angle,\n direction: zone.direction,\n limitedByWalls: zone.limitedByWalls,\n metadata: zone.metadata,\n };\n }\n\n /**\n * Gets all entities currently inside a zone\n *\n * @param id - Zone identifier\n * @returns Array of entities inside the zone\n */\n getEntitiesInZone(id: string): Entity[] {\n const zone = this.zones.get(id);\n if (!zone) return [];\n\n const entities: Entity[] = [];\n for (const uuid of zone.inside) {\n const entity = this.engine.getEntityByUUID(uuid);\n if (entity) {\n entities.push(entity);\n }\n }\n return entities;\n }\n\n /**\n * Gets all zone identifiers\n *\n * @returns Array of zone IDs\n */\n getAllZoneIds(): string[] {\n return Array.from(this.zones.keys());\n }\n\n /**\n * Clears all zones\n */\n clear(): void {\n this.zones.clear();\n }\n\n /**\n * Updates all zones, detecting entities entering/exiting\n *\n * This should be called after each physics step to keep zones synchronized.\n *\n * @param _deltaTime - Optional delta time (not used currently, but kept for future use)\n *\n * @example\n * ```typescript\n * engine.step();\n * zones.update();\n * ```\n */\n update(_deltaTime?: number): void {\n for (const zone of this.zones.values()) {\n // Update position for attached zones\n if (zone.type === 'attached' && zone.attachedEntity) {\n const entityPos = zone.attachedEntity.position;\n const offset = zone.offset ?? new Vector2(0, 0);\n zone.position.set(entityPos.x + offset.x, entityPos.y + offset.y);\n }\n\n // Query entities in the zone's AABB (broad phase)\n const aabb = new AABB(\n zone.position.x - zone.radius,\n zone.position.y - zone.radius,\n zone.position.x + zone.radius,\n zone.position.y + zone.radius,\n );\n const candidates = this.engine.queryAABB(aabb);\n\n // Filter entities that are actually inside the zone (narrow phase)\n const hits = new Set<string>();\n for (const entity of candidates) {\n // Skip the attached entity itself\n if (zone.attachedEntity && entity.uuid === zone.attachedEntity.uuid) {\n continue;\n }\n\n if (this.isEntityInsideZone(zone, entity)) {\n hits.add(entity.uuid);\n }\n }\n\n // Detect enter/exit events\n const previous = zone.inside;\n const entered: Entity[] = [];\n const exited: Entity[] = [];\n\n for (const uuid of hits) {\n if (!previous.has(uuid)) {\n const entity = this.engine.getEntityByUUID(uuid);\n if (entity) {\n entered.push(entity);\n }\n }\n }\n\n for (const uuid of previous) {\n if (!hits.has(uuid)) {\n const entity = this.engine.getEntityByUUID(uuid);\n if (entity) {\n exited.push(entity);\n }\n }\n }\n\n // Update zone state\n zone.inside = hits;\n\n // Trigger callbacks\n if (entered.length > 0 && zone.callbacks?.onEnter) {\n zone.callbacks.onEnter(entered);\n }\n if (exited.length > 0 && zone.callbacks?.onExit) {\n zone.callbacks.onExit(exited);\n }\n }\n }\n\n /**\n * Checks if an entity is inside a zone\n *\n * @param zone - Zone record\n * @param entity - Entity to check\n * @returns True if the entity is inside the zone\n */\n private isEntityInsideZone(zone: ZoneRecord, entity: Entity): boolean {\n const zonePos = zone.position;\n const entityPos = entity.position;\n\n // Calculate distance from zone center to entity center\n const dx = entityPos.x - zonePos.x;\n const dy = entityPos.y - zonePos.y;\n const distance = Math.hypot(dx, dy);\n\n // Get entity radius (use max of width/height for AABB, or radius for circle)\n const entityRadius = entity.radius > 0\n ? entity.radius\n : Math.max(entity.width, entity.height) / 2;\n\n // Check if entity is within radius\n if (distance - entityRadius > zone.radius) {\n return false;\n }\n\n // Check cone angle if zone is not a full circle\n if (zone.angle < 360) {\n const facing = this.directionToAngle(zone.direction);\n const angle = Math.atan2(dy, dx);\n const delta = this.normalizeAngle(angle - facing);\n const halfAperture = (zone.angle * Math.PI) / 360;\n if (Math.abs(delta) > halfAperture) {\n return false;\n }\n }\n\n // Check line-of-sight if required\n if (zone.limitedByWalls) {\n if (!this.hasLineOfSight(zonePos, entityPos, entity.uuid)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks if there's a clear line of sight between two points\n *\n * @param start - Start position\n * @param end - End position\n * @param ignoreEntityId - Entity UUID to ignore (usually the target entity)\n * @returns True if line of sight is clear\n */\n private hasLineOfSight(\n start: Vector2,\n end: Vector2,\n ignoreEntityId?: string,\n ): boolean {\n const direction = end.sub(start);\n const distance = direction.length();\n\n if (distance < 1e-5) return true;\n\n direction.normalizeInPlace();\n\n // Use raycast for efficient line-of-sight check\n // We want to find if there is ANY static entity between start and end\n const hit = this.engine.raycast(start, direction, distance, undefined, (entity) => {\n // Ignore dynamic entities (unless we want them to block vision?)\n // For now, only static entities block vision as per original logic\n if (!entity.isStatic()) return false;\n\n // Ignore specific entity (e.g. the target itself)\n if (ignoreEntityId && entity.uuid === ignoreEntityId) return false;\n\n return true;\n });\n\n return hit === null;\n }\n\n /**\n * Converts direction string to angle in radians\n *\n * @param dir - Direction\n * @returns Angle in radians\n */\n private directionToAngle(dir: ZoneDirection): number {\n switch (dir) {\n case 'up':\n return -Math.PI / 2;\n case 'down':\n return Math.PI / 2;\n case 'left':\n return Math.PI;\n case 'right':\n default:\n return 0;\n }\n }\n\n /**\n * Normalizes angle to [-π, π]\n *\n * @param angle - Angle in radians\n * @returns Normalized angle\n */\n private normalizeAngle(angle: number): number {\n let a = angle;\n while (a > Math.PI) a -= Math.PI * 2;\n while (a < -Math.PI) a += Math.PI * 2;\n return a;\n }\n}\n\n","import { World, WorldConfig } from '../world/World';\nimport { Entity, EntityConfig } from '../physics/Entity';\nimport { RegionManager, RegionManagerConfig } from '../region/RegionManager';\nimport { EventSystem } from '../world/events';\nimport { Vector2 } from '../core/math/Vector2';\nimport { AABB } from '../core/math/AABB';\nimport type { SpatialPartition } from '../world/SpatialPartition';\nimport { assignPolygonCollider, PolygonConfig } from '../collision/PolygonCollider';\nimport { raycast as raycastUtil, RaycastHit } from '../collision/raycast';\nimport { sweepEntities as sweepUtil, SweepResult } from '../collision/sweep';\nimport { MovementManager } from '../movement/MovementManager';\nimport { ZoneManager } from './ZoneManager';\n\n/**\n * Physics engine configuration\n */\nexport interface PhysicsEngineConfig extends WorldConfig {\n /** Enable region-based simulation (default: false) */\n enableRegions?: boolean;\n /** Region manager configuration (required if enableRegions is true) */\n regionConfig?: RegionManagerConfig;\n}\n\n/**\n * Main physics engine interface\n * \n * Provides a high-level, gameplay-oriented API for physics simulation.\n * Supports both single-world and multi-region simulation modes.\n * \n * @example\n * ```typescript\n * const engine = new PhysicsEngine({ timeStep: 1/60 });\n * const entity = engine.createEntity({\n * position: { x: 0, y: 0 },\n * radius: 10,\n * mass: 1\n * });\n * \n * engine.step();\n * ```\n */\nexport class PhysicsEngine {\n private world: World;\n private regionManager: RegionManager | null = null;\n private useRegions: boolean;\n private movementManager: MovementManager | null = null;\n private zoneManager: ZoneManager | null = null;\n private tick: number = 0;\n\n /**\n * Creates a new physics engine\n * \n * @param config - Engine configuration\n */\n constructor(config: PhysicsEngineConfig = {}) {\n this.useRegions = config.enableRegions ?? false;\n\n if (this.useRegions) {\n if (!config.regionConfig) {\n throw new Error('Region configuration is required when enableRegions is true');\n }\n this.regionManager = new RegionManager(config.regionConfig);\n // Create a minimal world for entities not in regions\n this.world = new World({\n ...config,\n enableSleep: false, // Regions handle sleep\n });\n } else {\n this.world = new World(config);\n }\n }\n\n /**\n * Gets the movement manager bound to this engine.\n *\n * The manager is lazily created and reused.\n *\n * @returns Movement manager instance\n */\n public getMovementManager(): MovementManager {\n if (!this.movementManager) {\n this.movementManager = MovementManager.forEngine(this);\n }\n return this.movementManager;\n }\n\n /**\n * Gets the zone manager bound to this engine.\n *\n * The manager is lazily created and reused. Zones allow detecting entities\n * within circular or cone-shaped areas without physical collisions (useful\n * for vision, skill ranges, explosions, etc.).\n *\n * **Important:** Call `zoneManager.update()` after each physics step to\n * keep zones synchronized:\n *\n * ```typescript\n * engine.step();\n * engine.getZoneManager().update();\n * ```\n *\n * @returns Zone manager instance\n *\n * @example\n * ```typescript\n * const zones = engine.getZoneManager();\n * const visionZone = zones.createAttachedZone(player, {\n * radius: 100,\n * angle: 90,\n * direction: 'right',\n * }, {\n * onEnter: (entities) => console.log('Player sees:', entities),\n * });\n *\n * engine.step();\n * zones.update();\n * ```\n */\n public getZoneManager(): ZoneManager {\n if (!this.zoneManager) {\n this.zoneManager = new ZoneManager(this);\n }\n return this.zoneManager;\n }\n\n /**\n * Updates all registered movement strategies.\n *\n * @param dt - Time delta in seconds (defaults to the world's time step)\n */\n public updateMovements(dt?: number): void {\n const manager = this.getMovementManager();\n const delta = dt ?? this.world.getTimeStep();\n manager.update(delta);\n }\n\n /**\n * Updates movements and then steps the simulation.\n *\n * @param dt - Time delta in seconds (defaults to the world's time step)\n */\n public stepWithMovements(dt?: number): void {\n this.updateMovements(dt);\n this.step();\n }\n\n /**\n * Advances the simulation by exactly one fixed tick.\n *\n * This helper is equivalent to {@link step} but returns the tick index after the step,\n * making it convenient for client-side prediction loops.\n *\n * @returns Current tick index after stepping\n */\n public stepOneTick(): number {\n this.step();\n return this.tick;\n }\n\n /**\n * Advances the simulation by a fixed number of ticks.\n *\n * @param ticks - Number of ticks to simulate (>= 1)\n * @returns Current tick index after stepping\n */\n public stepTicks(ticks: number): number {\n if (!Number.isFinite(ticks) || ticks <= 0) {\n return this.tick;\n }\n const total = Math.floor(ticks);\n for (let i = 0; i < total; i += 1) {\n this.step();\n }\n return this.tick;\n }\n\n /**\n * Creates a new entity\n * \n * @param config - Entity configuration\n * @returns Created entity\n * \n * @example\n * ```typescript\n * const entity = engine.createEntity({\n * position: { x: 100, y: 100 },\n * radius: 15,\n * mass: 1,\n * velocity: { x: 5, y: 0 }\n * });\n * ```\n */\n public createEntity(config: EntityConfig): Entity {\n const entity = new Entity(config);\n\n if (this.useRegions && this.regionManager) {\n this.regionManager.addEntity(entity);\n } else {\n this.world.addEntity(entity);\n }\n\n return entity;\n }\n\n /**\n * Adds an existing entity to the engine\n * \n * @param entity - Entity to add\n * @returns The added entity\n */\n public addEntity(entity: Entity): Entity {\n if (this.useRegions && this.regionManager) {\n this.regionManager.addEntity(entity);\n } else {\n this.world.addEntity(entity);\n }\n return entity;\n }\n\n /**\n * Removes an entity from the engine\n * \n * @param entity - Entity to remove\n */\n public removeEntity(entity: Entity): void {\n if (this.useRegions && this.regionManager) {\n this.regionManager.removeEntity(entity);\n } else {\n this.world.removeEntity(entity);\n }\n }\n\n /**\n * Gets all entities\n * \n * @returns Array of all entities\n */\n public getEntities(): Entity[] {\n if (this.useRegions && this.regionManager) {\n const entities: Entity[] = [];\n for (const region of this.regionManager.getRegions()) {\n entities.push(...region.getEntities());\n }\n return entities;\n }\n return this.world.getEntities();\n }\n\n /**\n * Gets an entity by UUID\n * \n * @param uuid - Entity UUID\n * @returns Entity or undefined\n */\n public getEntityByUUID(uuid: string): Entity | undefined {\n if (this.useRegions && this.regionManager) {\n for (const region of this.regionManager.getRegions()) {\n const entity = region.getWorld().getEntityByUUID(uuid);\n if (entity) {\n return entity;\n }\n }\n return undefined;\n }\n return this.world.getEntityByUUID(uuid);\n }\n\n /**\n * Steps the physics simulation forward\n * \n * Updates all entities, detects and resolves collisions.\n */\n public step(): void {\n if (this.useRegions && this.regionManager) {\n this.regionManager.step();\n } else {\n this.world.step();\n }\n this.tick += 1;\n }\n\n /**\n * Gets the event system\n * \n * @returns Event system instance\n */\n public getEvents(): EventSystem {\n return this.world.getEvents();\n }\n\n /**\n * Applies a force to an entity\n * \n * @param entity - Entity to apply force to\n * @param force - Force vector\n */\n public applyForce(entity: Entity, force: Vector2): void {\n entity.applyForce(force);\n }\n\n /**\n * Applies an impulse to an entity\n * \n * @param entity - Entity to apply impulse to\n * @param impulse - Impulse vector\n */\n public applyImpulse(entity: Entity, impulse: Vector2): void {\n entity.applyImpulse(impulse);\n }\n\n /**\n * Teleports an entity to a new position\n * \n * @param entity - Entity to teleport\n * @param position - New position\n */\n public teleport(entity: Entity, position: Vector2 | { x: number; y: number }): void {\n entity.teleport(position);\n\n // Update region if using regions\n if (this.useRegions && this.regionManager) {\n this.regionManager.updateEntities();\n }\n }\n\n /**\n * Freezes an entity (makes it static)\n * \n * @param entity - Entity to freeze\n */\n public freeze(entity: Entity): void {\n entity.freeze();\n }\n\n /**\n * Unfreezes an entity (makes it dynamic)\n * \n * @param entity - Entity to unfreeze\n */\n public unfreeze(entity: Entity): void {\n entity.unfreeze();\n }\n\n /**\n * Queries entities in an AABB region\n * \n * @param bounds - AABB to query\n * @returns Array of entities in the region\n */\n public queryAABB(bounds: AABB): Entity[] {\n if (this.useRegions && this.regionManager) {\n const entities: Entity[] = [];\n const regions = this.regionManager.getRegionsInBounds(bounds);\n for (const region of regions) {\n const world = region.getWorld();\n const worldEntities = world.getEntities();\n for (const entity of worldEntities) {\n if (bounds.contains(entity.position)) {\n entities.push(entity);\n }\n }\n }\n return entities;\n }\n // Use spatial partition from world\n const world = this.world as any;\n if (world.spatialPartition) {\n return Array.from(world.spatialPartition.queryAABB(bounds));\n }\n // Fallback to checking all entities\n return this.world.getEntities().filter((e) => bounds.contains(e.position));\n }\n\n /**\n * Clears all entities from the engine\n */\n public clear(): void {\n if (this.useRegions && this.regionManager) {\n this.regionManager.clear();\n } else {\n this.world.clear();\n }\n this.tick = 0;\n }\n\n /**\n * Assigns a polygon collider to an entity (supports convex or concave via convex parts).\n *\n * Design: the collider is attached via a registry and used by the detector on demand.\n * This keeps entities lightweight and preserves the separation of detection/resolution.\n *\n * @param entity - Target entity\n * @param config - Polygon configuration\n * @example\n * ```typescript\n * engine.assignPolygonCollider(entity, { vertices: [new Vector2(-1,-1), new Vector2(1,-1), new Vector2(1,1), new Vector2(-1,1)], isConvex: true });\n * ```\n */\n public assignPolygonCollider(entity: Entity, config: PolygonConfig): void {\n assignPolygonCollider(entity, config);\n }\n\n /**\n * Casts a ray in the physics world and returns the nearest hit, if any.\n * Uses the world's spatial partition for broad-phase and shape-specific narrow-phase tests.\n *\n * @param origin - Ray origin\n * @param direction - Ray direction (any length)\n * @param maxDistance - Maximum cast length\n * @param mask - Optional collision mask (layer)\n * @param filter - Optional filter function (return true to include entity)\n * @returns Raycast hit or null\n * @example\n * ```typescript\n * const hit = engine.raycast(new Vector2(0,0), new Vector2(1,0), 1000);\n * ```\n */\n public raycast(origin: Vector2, direction: Vector2, maxDistance: number, mask?: number, filter?: (entity: Entity) => boolean): RaycastHit | null {\n const world = this.world as any;\n const partition: SpatialPartition | undefined = world.spatialPartition;\n if (!partition) return null;\n return raycastUtil(partition, origin, direction, maxDistance, mask, filter);\n }\n\n /**\n * Computes continuous collision detection (sweep test) time-of-impact between two entities\n * over the next step of duration `dt`, using relative motion.\n *\n * @param a - First entity\n * @param b - Second entity\n * @param dt - Time step duration\n * @returns Sweep result or null if no hit in [0,1]\n * @example\n * ```typescript\n * const toi = engine.sweep(entityA, entityB, 1/60);\n * if (toi) {\n * // pre-resolve or clamp motion\n * }\n * ```\n */\n public sweep(a: Entity, b: Entity, dt: number): SweepResult | null {\n const rel = a.velocity.sub(b.velocity).mul(dt);\n return sweepUtil(a, b, rel);\n }\n\n /**\n * Gets statistics about the engine\n * \n * @returns Statistics object\n */\n public getStats(): {\n totalEntities: number;\n dynamicEntities: number;\n staticEntities: number;\n sleepingEntities: number;\n regions?: {\n total: number;\n active: number;\n };\n } {\n if (this.useRegions && this.regionManager) {\n const regionStats = this.regionManager.getStats();\n const worldStats = this.world.getStats();\n return {\n ...worldStats,\n regions: {\n total: regionStats.totalRegions,\n active: regionStats.activeRegions,\n },\n };\n }\n return this.world.getStats();\n }\n\n /**\n * Gets the underlying world instance\n * \n * @returns World instance\n */\n public getWorld(): World {\n return this.world;\n }\n\n /**\n * Gets the current simulation tick.\n *\n * @returns Tick counter (starts at 0 and increments after each {@link step})\n */\n public getTick(): number {\n return this.tick;\n }\n\n /**\n * Captures a lightweight snapshot of the current world state.\n *\n * The snapshot only stores the minimum data required for client-side prediction:\n * position, velocity, rotation, angular velocity and sleeping flag per entity.\n *\n * @returns Snapshot object\n */\n public takeSnapshot(): PhysicsSnapshot {\n return {\n tick: this.tick,\n entities: this.getEntities().map((entity) => ({\n uuid: entity.uuid,\n position: { x: entity.position.x, y: entity.position.y },\n velocity: { x: entity.velocity.x, y: entity.velocity.y },\n rotation: entity.rotation,\n angularVelocity: entity.angularVelocity,\n sleeping: entity.isSleeping(),\n })),\n };\n }\n\n /**\n * Restores a snapshot previously produced by {@link takeSnapshot}.\n *\n * Entities that cannot be found in the current engine are skipped silently.\n *\n * @param snapshot - Snapshot to restore\n */\n public restoreSnapshot(snapshot: PhysicsSnapshot): void {\n const entities = new Map(this.getEntities().map((entity) => [entity.uuid, entity]));\n\n for (const state of snapshot.entities) {\n const entity = entities.get(state.uuid);\n if (!entity) continue;\n\n entity.position.set(state.position.x, state.position.y);\n entity.velocity.set(state.velocity.x, state.velocity.y);\n entity.rotation = state.rotation;\n entity.angularVelocity = state.angularVelocity;\n\n if (state.sleeping) {\n entity.sleep();\n } else {\n entity.wakeUp();\n }\n }\n\n this.tick = snapshot.tick;\n }\n\n /**\n * Gets the region manager (if regions are enabled)\n * \n * @returns Region manager or null\n */\n public getRegionManager(): RegionManager | null {\n return this.regionManager;\n }\n}\n\nexport interface PhysicsSnapshot {\n tick: number;\n entities: Array<{\n uuid: string;\n position: { x: number; y: number };\n velocity: { x: number; y: number };\n rotation: number;\n angularVelocity: number;\n sleeping: boolean;\n }>;\n}\n\n","import { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Applies a burst of velocity during a fixed duration.\n *\n * The dash sets a constant velocity along a direction, then stops the entity\n * once the duration has elapsed.\n *\n * @example\n * ```typescript\n * movementManager.add(player, new Dash(8, { x: 1, y: 0 }, 0.15));\n * ```\n */\nexport class Dash implements MovementStrategy {\n private elapsed = 0;\n private readonly direction: { x: number; y: number };\n private finished = false;\n\n /**\n * Creates a dash movement.\n *\n * @param speed - Movement speed in units per second\n * @param direction - Direction vector (will be normalized)\n * @param duration - Duration in seconds\n */\n constructor(\n private readonly speed: number,\n direction: { x: number; y: number },\n private readonly duration: number,\n ) {\n const magnitude = Math.hypot(direction.x, direction.y);\n this.direction = magnitude > 0\n ? { x: direction.x / magnitude, y: direction.y / magnitude }\n : { x: 1, y: 0 };\n }\n\n update(body: MovementBody, dt: number): void {\n if (this.finished) {\n return;\n }\n\n this.elapsed += dt;\n\n if (this.elapsed <= this.duration) {\n body.setVelocity({\n x: this.direction.x * this.speed,\n y: this.direction.y * this.speed,\n });\n } else {\n body.setVelocity({ x: 0, y: 0 });\n this.finished = true;\n }\n }\n\n isFinished(): boolean {\n return this.finished;\n }\n}\n\n","import { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Simulates slippery movement with gradual acceleration and deceleration.\n *\n * @example\n * ```typescript\n * const ice = new IceMovement({ x: 1, y: 0 }, 3, 0.25, 0.1);\n * movementManager.add(player, ice);\n * ```\n */\nexport class IceMovement implements MovementStrategy {\n private currentVelocity = { x: 0, y: 0 };\n private elapsed = 0;\n private stopped = false;\n private readonly targetDirection: { x: number; y: number };\n\n /**\n * Creates an ice-like movement behaviour.\n *\n * @param direction - Initial desired direction (normalized automatically)\n * @param maxSpeed - Maximum speed in units per second\n * @param acceleration - Fraction of the gap closed per second (0-1)\n * @param friction - Fraction of velocity retained per second when stopping (0-1)\n * @param duration - Optional duration in seconds\n */\n constructor(\n direction: { x: number; y: number },\n private maxSpeed = 4,\n private acceleration = 0.2,\n private friction = 0.08,\n private readonly duration?: number,\n ) {\n const magnitude = Math.hypot(direction.x, direction.y);\n this.targetDirection = magnitude > 0\n ? { x: direction.x / magnitude, y: direction.y / magnitude }\n : { x: 0, y: 0 };\n }\n\n update(body: MovementBody, dt: number): void {\n if (this.duration !== undefined) {\n this.elapsed += dt;\n if (this.elapsed >= this.duration) {\n this.stopped = true;\n }\n }\n\n if (!this.stopped) {\n const accelFactor = this.perSecondFactor(this.acceleration, dt);\n const targetVx = this.targetDirection.x * this.maxSpeed;\n const targetVy = this.targetDirection.y * this.maxSpeed;\n\n this.currentVelocity.x += (targetVx - this.currentVelocity.x) * accelFactor;\n this.currentVelocity.y += (targetVy - this.currentVelocity.y) * accelFactor;\n } else {\n const frictionFactor = this.perSecondFactor(this.friction, dt);\n this.currentVelocity.x *= 1 - frictionFactor;\n this.currentVelocity.y *= 1 - frictionFactor;\n }\n\n body.setVelocity({\n x: this.currentVelocity.x,\n y: this.currentVelocity.y,\n });\n }\n\n isFinished(): boolean {\n if (!this.stopped) {\n return false;\n }\n const speed = Math.hypot(this.currentVelocity.x, this.currentVelocity.y);\n return speed < 0.05;\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n resume(): void {\n this.stopped = false;\n }\n\n setTargetDirection(direction: { x: number; y: number }): void {\n const magnitude = Math.hypot(direction.x, direction.y);\n this.targetDirection.x = magnitude > 0 ? direction.x / magnitude : 0;\n this.targetDirection.y = magnitude > 0 ? direction.y / magnitude : 0;\n this.stopped = false;\n }\n\n setParameters(maxSpeed?: number, acceleration?: number, friction?: number): void {\n if (maxSpeed !== undefined) {\n this.maxSpeed = maxSpeed;\n }\n if (acceleration !== undefined) {\n this.acceleration = acceleration;\n }\n if (friction !== undefined) {\n this.friction = friction;\n }\n }\n\n private perSecondFactor(value: number, dt: number): number {\n const clamped = Math.max(0, Math.min(1, value));\n if (dt <= 0) {\n return clamped;\n }\n return 1 - Math.pow(1 - clamped, dt);\n }\n}\n\n","import { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Simulates an impulse that pushes an entity away and gradually decays.\n *\n * @example\n * ```typescript\n * movementManager.add(enemy, new Knockback({ x: -1, y: 0 }, 12, 0.25, 0.4));\n * ```\n */\nexport class Knockback implements MovementStrategy {\n private readonly direction: { x: number; y: number };\n private elapsed = 0;\n private currentSpeed: number;\n\n /**\n * Creates a knockback movement.\n *\n * @param direction - Direction of the impulse (will be normalized)\n * @param initialSpeed - Initial speed in units per second\n * @param duration - Duration in seconds\n * @param decayFactor - Fraction of speed preserved per second (0-1)\n */\n constructor(\n direction: { x: number; y: number },\n initialSpeed: number,\n private readonly duration: number,\n private readonly decayFactor = 0.35,\n ) {\n const magnitude = Math.hypot(direction.x, direction.y);\n this.direction = magnitude > 0\n ? { x: direction.x / magnitude, y: direction.y / magnitude }\n : { x: 1, y: 0 };\n this.currentSpeed = initialSpeed;\n }\n\n update(body: MovementBody, dt: number): void {\n this.elapsed += dt;\n\n if (this.elapsed <= this.duration) {\n body.setVelocity({\n x: this.direction.x * this.currentSpeed,\n y: this.direction.y * this.currentSpeed,\n });\n\n const decay = Math.max(0, Math.min(1, this.decayFactor));\n if (decay === 0) {\n this.currentSpeed = 0;\n } else if (decay === 1) {\n // preserve speed, no change\n } else {\n this.currentSpeed *= Math.pow(decay, dt);\n }\n } else {\n body.setVelocity({ x: 0, y: 0 });\n }\n }\n\n isFinished(): boolean {\n return this.elapsed >= this.duration;\n }\n}\n\n","import { PhysicsEngine } from '../../api/PhysicsEngine';\nimport { AABB } from '../../core/math/AABB';\nimport { Vector2 } from '../../core/math/Vector2';\nimport { Entity } from '../../physics/Entity';\nimport { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Seeks a target while repelling from nearby obstacles using a linear falloff.\n *\n * @example\n * ```typescript\n * const strategy = new LinearRepulsion(\n * engine,\n * () => player.position.clone(),\n * 3,\n * 2,\n * 5,\n * );\n * movementManager.add(enemy, strategy);\n * ```\n */\nexport class LinearRepulsion implements MovementStrategy {\n private repulseRadiusSq: number;\n\n /**\n * @param engine - Physics engine used for spatial queries\n * @param targetProvider - Function returning the target position\n * @param maxSpeed - Maximum speed in units per second\n * @param repulseRadius - Radius used to sample nearby obstacles\n * @param repulseWeight - Weight of the repulsion force\n * @param ignoredEntity - Optional entity to exclude from avoidance (e.g. the target)\n */\n constructor(\n private readonly engine: PhysicsEngine,\n private readonly targetProvider: () => { x: number; y: number },\n private maxSpeed = 2.5,\n private repulseRadius = 2,\n private repulseWeight = 4,\n private readonly ignoredEntity?: () => Entity | undefined,\n ) {\n this.repulseRadiusSq = repulseRadius * repulseRadius;\n }\n\n update(body: MovementBody, _dt: number): void {\n const entity = body.getEntity?.();\n if (!entity) {\n throw new Error('LinearRepulsion requires a movement body backed by a physics entity.');\n }\n\n const targetPosition = this.targetProvider();\n const toTarget = new Vector2(targetPosition.x - entity.position.x, targetPosition.y - entity.position.y);\n const distance = toTarget.length();\n\n if (distance > 0) {\n toTarget.divInPlace(distance);\n } else {\n toTarget.set(0, 0);\n }\n\n const bounds = AABB.fromCenterSize(entity.position.x, entity.position.y, this.repulseRadius * 2, this.repulseRadius * 2);\n const neighbors = this.engine.queryAABB(bounds);\n const ignored = this.ignoredEntity?.();\n\n const push = new Vector2(0, 0);\n for (const other of neighbors) {\n if (other === entity || other === ignored || other.isStatic()) {\n continue;\n }\n\n const diff = new Vector2(entity.position.x - other.position.x, entity.position.y - other.position.y);\n const d2 = diff.lengthSquared();\n if (d2 > this.repulseRadiusSq || d2 === 0) {\n continue;\n }\n\n const d = Math.sqrt(d2);\n const weight = this.repulseWeight * (this.repulseRadius - Math.min(d, this.repulseRadius)) / this.repulseRadius;\n push.addInPlace(diff.mul(weight / d));\n }\n\n const maxPush = this.maxSpeed * 3;\n const pushLength = push.length();\n if (pushLength > maxPush && pushLength > 0) {\n push.mulInPlace(maxPush / pushLength);\n }\n\n const desired = toTarget.mul(this.maxSpeed).add(push);\n const desiredLength = desired.length();\n if (desiredLength > this.maxSpeed && desiredLength > 0) {\n desired.mulInPlace(this.maxSpeed / desiredLength);\n }\n\n if (!Number.isFinite(desired.x) || !Number.isFinite(desired.y)) {\n entity.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n body.setVelocity(desired);\n }\n\n setParameters(maxSpeed?: number, repulseRadius?: number, repulseWeight?: number): void {\n if (maxSpeed !== undefined) {\n this.maxSpeed = maxSpeed;\n }\n if (repulseRadius !== undefined) {\n this.repulseRadius = repulseRadius;\n this.repulseRadiusSq = repulseRadius * repulseRadius;\n }\n if (repulseWeight !== undefined) {\n this.repulseWeight = repulseWeight;\n }\n }\n}\n\n","import { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Oscillates an entity around its initial position using different wave patterns.\n *\n * @example\n * ```typescript\n * movementManager.add(platform, new Oscillate({ x: 1, y: 0 }, 2, 3, 'sine'));\n * ```\n */\nexport class Oscillate implements MovementStrategy {\n private readonly direction: { x: number; y: number };\n private elapsed = 0;\n private anchor: { x: number; y: number } | null = null;\n\n /**\n * Creates an oscillating movement.\n *\n * @param direction - Base direction (will be normalized)\n * @param amplitude - Maximum displacement from the anchor position\n * @param period - Duration of a full cycle in seconds\n * @param type - Oscillation pattern\n * @param duration - Total life time in seconds (undefined for infinite)\n */\n constructor(\n direction: { x: number; y: number },\n private readonly amplitude: number,\n private readonly period: number,\n private readonly type: 'linear' | 'sine' | 'circular' = 'sine',\n private readonly duration?: number,\n ) {\n const magnitude = Math.hypot(direction.x, direction.y);\n this.direction = magnitude > 0\n ? { x: direction.x / magnitude, y: direction.y / magnitude }\n : { x: 1, y: 0 };\n }\n\n update(body: MovementBody, dt: number): void {\n if (this.anchor === null) {\n this.anchor = { x: body.position.x, y: body.position.y };\n }\n\n this.elapsed += dt;\n\n if (this.duration !== undefined && this.elapsed >= this.duration) {\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n const cycle = this.period <= 0 ? 0 : (this.elapsed % this.period) / this.period;\n\n // Calculate velocity based on the derivative of the oscillation function\n // For sine: derivative is cos, scaled by amplitude and frequency\n const frequency = this.period > 0 ? (2 * Math.PI) / this.period : 0;\n let velocityScale: number;\n \n switch (this.type) {\n case 'sine':\n velocityScale = Math.cos(cycle * Math.PI * 2) * frequency * this.amplitude;\n break;\n case 'circular':\n velocityScale = Math.cos(cycle * Math.PI * 2) * frequency * this.amplitude;\n break;\n case 'linear':\n // Linear oscillation has constant velocity during each half\n const halfCycle = cycle < 0.5;\n velocityScale = (halfCycle ? 1 : -1) * (2 * this.amplitude) / (this.period / 2);\n break;\n default:\n velocityScale = 0;\n }\n\n const vx = this.direction.x * velocityScale;\n const vy = this.direction.y * velocityScale;\n \n // For circular motion, add perpendicular component\n if (this.type === 'circular') {\n const perpendicularScale = -Math.sin(cycle * Math.PI * 2) * frequency * this.amplitude;\n body.setVelocity({\n x: vx - this.direction.y * perpendicularScale,\n y: vy + this.direction.x * perpendicularScale,\n });\n } else {\n body.setVelocity({ x: vx, y: vy });\n }\n }\n\n isFinished(): boolean {\n return this.duration !== undefined && this.elapsed >= this.duration;\n }\n\n reset(): void {\n this.elapsed = 0;\n this.anchor = null;\n }\n}\n\n","import { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Makes an entity follow a list of waypoints at a constant speed.\n *\n * @example\n * ```typescript\n * movementManager.add(npc, new PathFollow(\n * [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }],\n * 1.5,\n * true,\n * 0.5,\n * ));\n * ```\n */\nexport class PathFollow implements MovementStrategy {\n private currentWaypoint = 0;\n private elapsedPause = 0;\n private paused = false;\n private finished = false;\n private direction: { x: number; y: number } = { x: 0, y: 0 };\n\n /**\n * Creates a path-following strategy.\n *\n * @param waypoints - List of waypoints to traverse\n * @param speed - Travel speed in units per second\n * @param loop - When true, restart from the first waypoint\n * @param pauseAtWaypoints - Optional pause duration (seconds) at each waypoint\n * @param tolerance - Distance tolerance to consider a waypoint reached\n */\n constructor(\n private waypoints: Array<{ x: number; y: number }>,\n private readonly speed: number,\n private readonly loop = false,\n private readonly pauseAtWaypoints = 0,\n private readonly tolerance = 0.1,\n ) {\n if (waypoints.length === 0) {\n this.finished = true;\n }\n }\n\n update(body: MovementBody, dt: number): void {\n if (this.finished || this.waypoints.length === 0) {\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n if (this.paused) {\n this.elapsedPause += dt;\n body.setVelocity({ x: 0, y: 0 });\n\n if (this.elapsedPause >= this.pauseAtWaypoints) {\n this.paused = false;\n this.elapsedPause = 0;\n } else {\n return;\n }\n }\n\n const target = this.waypoints[this.currentWaypoint];\n if (!target) {\n this.finished = true;\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n const dx = target.x - body.position.x;\n const dy = target.y - body.position.y;\n const distance = Math.hypot(dx, dy);\n\n if (distance <= this.tolerance) {\n this.currentWaypoint += 1;\n\n if (this.currentWaypoint >= this.waypoints.length) {\n if (this.loop) {\n this.currentWaypoint = 0;\n } else {\n this.finished = true;\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n }\n\n if (this.pauseAtWaypoints > 0) {\n this.paused = true;\n this.elapsedPause = 0;\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n }\n\n if (distance > 0) {\n this.direction = { x: dx / distance, y: dy / distance };\n }\n\n body.setVelocity({\n x: this.direction.x * this.speed,\n y: this.direction.y * this.speed,\n });\n }\n\n isFinished(): boolean {\n return this.finished;\n }\n\n getCurrentWaypoint(): number {\n return this.currentWaypoint;\n }\n\n setWaypoints(waypoints: Array<{ x: number; y: number }>, reset = true): void {\n this.waypoints = waypoints;\n this.finished = waypoints.length === 0;\n if (reset) {\n this.currentWaypoint = 0;\n this.paused = false;\n this.elapsedPause = 0;\n }\n }\n}\n\n","import { Vector2 } from '../../core/math/Vector2';\nimport { MovementBody, MovementStrategy } from '../MovementStrategy';\n\n/**\n * Type of projectile trajectory.\n */\nexport enum ProjectileType {\n Straight = 'straight',\n Arc = 'arc',\n Bounce = 'bounce',\n}\n\nenum ProjectileStage {\n Flying,\n Rolling,\n Finished,\n}\n\n/**\n * Configuration for a projectile trajectory.\n */\nexport interface ProjectileOptions {\n /** Horizontal speed in units per second */\n speed: number;\n /** Heading direction (will be normalized) */\n direction: { x: number; y: number };\n /** Maximum travel distance (optional) */\n maxRange?: number;\n /** Maximum lifetime in seconds (optional) */\n lifetime?: number;\n /** Initial vertical height */\n initialHeight?: number;\n /** Apex height for arc trajectories */\n maxHeight?: number;\n /** Gravity strength applied to arc/bounce projectiles */\n gravity?: number;\n /** Number of allowed bounces */\n maxBounces?: number;\n /** Energy retained after each bounce (0-1) */\n bounciness?: number;\n /** Drag factor applied per second (0-1) */\n drag?: number;\n /** Optional callback receiving height updates */\n onHeightUpdate?: (height: number, body: MovementBody) => void;\n}\n\n/**\n * Moves an entity following a projectile trajectory.\n *\n * @example\n * ```typescript\n * const projectile = new ProjectileMovement(ProjectileType.Arc, {\n * speed: 12,\n * direction: { x: 1, y: 0 },\n * maxHeight: 3,\n * gravity: 30,\n * });\n * movementManager.add(entity, projectile);\n * ```\n */\nexport class ProjectileMovement implements MovementStrategy {\n private elapsed = 0;\n private distanceTraveled = 0;\n private startPosition: Vector2 | null = null;\n private bounceCount = 0;\n private stage: ProjectileStage = ProjectileStage.Flying;\n private finished = false;\n\n private currentHeight = 0;\n private verticalVelocity = 0;\n private readonly direction: { x: number; y: number };\n\n private readonly options: ProjectileOptions;\n\n constructor(\n private readonly type: ProjectileType,\n options: ProjectileOptions,\n ) {\n const defaults: ProjectileOptions = {\n speed: options.speed,\n direction: options.direction,\n initialHeight: 0,\n maxHeight: 2,\n gravity: 30,\n maxBounces: 0,\n bounciness: 0.6,\n drag: 0,\n };\n\n this.options = { ...defaults, ...options };\n\n const magnitude = Math.hypot(this.options.direction.x, this.options.direction.y);\n this.direction = magnitude > 0\n ? { x: this.options.direction.x / magnitude, y: this.options.direction.y / magnitude }\n : { x: 1, y: 0 };\n\n this.currentHeight = this.options.initialHeight ?? 0;\n\n if (this.type === ProjectileType.Arc || this.type === ProjectileType.Bounce) {\n const gravity = this.options.gravity ?? 30;\n const maxHeight = this.options.maxHeight ?? 2;\n this.verticalVelocity = Math.sqrt(Math.max(0, 2 * gravity * maxHeight));\n }\n }\n\n update(body: MovementBody, dt: number): void {\n if (this.finished || dt <= 0) {\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n if (this.startPosition === null) {\n this.startPosition = new Vector2(body.position.x, body.position.y);\n }\n\n this.elapsed += dt;\n if (this.options.lifetime !== undefined && this.elapsed >= this.options.lifetime) {\n this.finish(body);\n return;\n }\n\n switch (this.stage) {\n case ProjectileStage.Flying:\n this.updateFlying(body, dt);\n break;\n case ProjectileStage.Rolling:\n this.updateRolling(body, dt);\n break;\n case ProjectileStage.Finished:\n this.finish(body);\n return;\n }\n\n if (this.startPosition) {\n this.distanceTraveled = new Vector2(body.position.x, body.position.y).distanceTo(this.startPosition);\n if (this.options.maxRange !== undefined && this.distanceTraveled >= this.options.maxRange) {\n this.finish(body);\n }\n }\n }\n\n isFinished(): boolean {\n return this.finished;\n }\n\n getHeight(): number {\n return this.currentHeight;\n }\n\n getProgress(): number {\n if (this.options.maxRange) {\n return Math.min(1, this.distanceTraveled / this.options.maxRange);\n }\n if (this.options.lifetime) {\n return Math.min(1, this.elapsed / this.options.lifetime);\n }\n return 0;\n }\n\n private updateFlying(body: MovementBody, dt: number): void {\n let vx = this.direction.x * this.options.speed;\n let vy = this.direction.y * this.options.speed;\n\n const drag = Math.max(0, Math.min(1, this.options.drag ?? 0));\n if (drag > 0) {\n const dragFactor = Math.pow(1 - drag, dt);\n vx *= dragFactor;\n vy *= dragFactor;\n }\n\n if (this.type === ProjectileType.Arc || this.type === ProjectileType.Bounce) {\n const gravity = this.options.gravity ?? 30;\n this.verticalVelocity -= gravity * dt;\n this.currentHeight += this.verticalVelocity * dt;\n\n if (this.options.onHeightUpdate) {\n this.options.onHeightUpdate(this.currentHeight, body);\n } else {\n const dispatcher = globalThis as typeof globalThis & { dispatchEvent?: (event: Event) => void };\n if (typeof dispatcher.dispatchEvent === 'function' && typeof CustomEvent !== 'undefined') {\n const event = new CustomEvent('projectile:height', {\n detail: {\n id: body.id,\n height: this.currentHeight,\n },\n });\n dispatcher.dispatchEvent(event);\n }\n }\n\n if (this.currentHeight <= 0) {\n this.currentHeight = 0;\n if (this.type === ProjectileType.Bounce) {\n if (this.bounceCount < (this.options.maxBounces ?? 0)) {\n const bounceEnergy = this.options.bounciness ?? 0.6;\n this.verticalVelocity = Math.abs(this.verticalVelocity) * bounceEnergy;\n vx *= bounceEnergy;\n vy *= bounceEnergy;\n this.bounceCount += 1;\n } else {\n this.stage = ProjectileStage.Rolling;\n }\n } else {\n this.finish(body);\n return;\n }\n }\n }\n\n body.setVelocity({ x: vx, y: vy });\n }\n\n private updateRolling(body: MovementBody, dt: number): void {\n const friction = 0.85;\n const vx = body.velocity.x * Math.pow(friction, dt * 60);\n const vy = body.velocity.y * Math.pow(friction, dt * 60);\n\n body.setVelocity({ x: vx, y: vy });\n\n if (Math.abs(vx) < 0.1 && Math.abs(vy) < 0.1) {\n this.finish(body);\n }\n }\n\n private finish(body: MovementBody): void {\n this.finished = true;\n this.stage = ProjectileStage.Finished;\n body.setVelocity({ x: 0, y: 0 });\n }\n}\n\n","import { PhysicsEngine } from '../../api/PhysicsEngine';\nimport { AABB } from '../../core/math/AABB';\nimport { Vector2 } from '../../core/math/Vector2';\nimport { Entity } from '../../physics/Entity';\nimport { MovementBody, MovementStrategy } from '../MovementStrategy';\n\nconst EPSILON = 1e-3;\n\n/**\n * Seeks a moving target while avoiding nearby obstacles.\n *\n * The strategy combines a pull towards the target with repulsive forces from\n * close entities, creating smooth avoidance behaviour.\n *\n * @example\n * ```typescript\n * const seek = new SeekAvoid(engine, () => playerEntity, 3, 2, 6, 0.5);\n * movementManager.add(enemy, seek);\n * ```\n */\nexport class SeekAvoid implements MovementStrategy {\n private repulseRadiusSq: number;\n private arriveRadiusSq: number;\n\n /**\n * @param engine - Physics engine used for spatial queries\n * @param targetProvider - Function returning the target entity (or null)\n * @param maxSpeed - Maximum speed in units per second\n * @param repulseRadius - Radius in which obstacles apply repulsion\n * @param repulseWeight - Strength of the repulsion force\n * @param arriveRadius - Distance considered as arrival\n */\n constructor(\n private readonly engine: PhysicsEngine,\n private readonly targetProvider: () => Entity | null | undefined,\n private maxSpeed = 2.5,\n private repulseRadius = 2,\n private repulseWeight = 4,\n arriveRadius = 0.5,\n ) {\n this.repulseRadiusSq = repulseRadius * repulseRadius;\n this.arriveRadiusSq = arriveRadius * arriveRadius;\n }\n\n update(body: MovementBody, _dt: number): void {\n const entity = body.getEntity?.();\n if (!entity) {\n throw new Error('SeekAvoid requires a movement body backed by a physics entity.');\n }\n\n const target = this.targetProvider();\n if (!target) {\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n const toTarget = new Vector2(target.position.x - entity.position.x, target.position.y - entity.position.y);\n const distSq = toTarget.lengthSquared();\n let arrived = false;\n\n if (distSq <= this.arriveRadiusSq) {\n toTarget.set(0, 0);\n arrived = true;\n } else if (distSq > 0) {\n toTarget.divInPlace(Math.sqrt(distSq));\n }\n\n const bounds = AABB.fromCenterSize(entity.position.x, entity.position.y, this.repulseRadius * 2, this.repulseRadius * 2);\n const neighbors = this.engine.queryAABB(bounds);\n\n const push = new Vector2(0, 0);\n let neighborCount = 0;\n if (!arrived) {\n for (const other of neighbors) {\n if (other === entity || other === target || other.isStatic()) {\n continue;\n }\n\n const diff = new Vector2(entity.position.x - other.position.x, entity.position.y - other.position.y);\n let d2 = diff.lengthSquared();\n if (d2 > this.repulseRadiusSq) {\n continue;\n }\n\n neighborCount++;\n if (d2 < EPSILON) {\n d2 = EPSILON;\n }\n\n const weight = this.repulseWeight / d2;\n push.addInPlace(diff.mul(weight));\n }\n }\n\n const pushLength = push.length();\n // Clamp avoidance so it cannot overwhelm the attraction toward the target.\n // Push should be weaker than the seek force\n const maxPush = this.maxSpeed * 0.5;\n if (pushLength > maxPush && pushLength > 0) {\n push.mulInPlace(maxPush / pushLength);\n }\n\n // Combine seek and avoid forces\n const desired = toTarget.mul(this.maxSpeed).add(push);\n const desiredLength = desired.length();\n \n // Allow the combined velocity to exceed maxSpeed slightly to maintain responsiveness\n const maxCombinedSpeed = this.maxSpeed * 1.5;\n if (desiredLength > maxCombinedSpeed && desiredLength > 0) {\n desired.mulInPlace(maxCombinedSpeed / desiredLength);\n }\n\n if (!Number.isFinite(desired.x) || !Number.isFinite(desired.y)) {\n body.setVelocity({ x: 0, y: 0 });\n return;\n }\n\n body.setVelocity(desired);\n }\n\n setParameters(\n maxSpeed?: number,\n repulseRadius?: number,\n repulseWeight?: number,\n arriveRadius?: number,\n ): void {\n if (maxSpeed !== undefined) {\n this.maxSpeed = maxSpeed;\n }\n if (repulseRadius !== undefined) {\n this.repulseRadius = repulseRadius;\n this.repulseRadiusSq = repulseRadius * repulseRadius;\n }\n if (repulseWeight !== undefined) {\n this.repulseWeight = repulseWeight;\n }\n if (arriveRadius !== undefined) {\n this.arriveRadiusSq = arriveRadius * arriveRadius;\n }\n }\n}\n\n","import {\n MovementManager as PhysicMovementManager,\n MovementStrategy,\n MovementOptions,\n PhysicsEngine,\n} from '@rpgjs/physic';\n\n/**\n * Thin proxy around the physics movement manager.\n *\n * Delegates every operation to the deterministic engine provided by `PhysicsEngine`\n * so strategies operate on the exact same entities as the physics simulation.\n */\nexport class MovementManager {\n constructor(private readonly physicProvider: () => PhysicsEngine) {}\n\n private get core(): PhysicMovementManager {\n return this.physicProvider().getMovementManager();\n }\n\n /**\n * Adds a movement strategy and returns a Promise that resolves when it completes.\n * \n * @param id - Entity identifier\n * @param strategy - Movement strategy to add\n * @param options - Optional callbacks for movement lifecycle events\n * @returns Promise that resolves when the movement completes\n */\n add(id: string, strategy: MovementStrategy, options?: MovementOptions): Promise<void> {\n return this.core.add(id, strategy, options);\n }\n\n remove(id: string, strategy: MovementStrategy): boolean {\n return this.core.remove(id, strategy);\n }\n\n clear(id: string): void {\n this.core.clear(id);\n }\n\n stopMovement(id: string): void {\n this.core.stopMovement(id);\n }\n\n hasActiveStrategies(id: string): boolean {\n return this.core.hasActiveStrategies(id);\n }\n\n getStrategies(id: string): MovementStrategy[] {\n return this.core.getStrategies(id);\n }\n\n update(dtMs: number): void {\n this.core.update(dtMs / 1000);\n }\n\n clearAll(): void {\n this.core.clearAll();\n }\n}\n\n","import { generateShortUUID, users } from \"@signe/sync\";\nimport { effect, Signal, signal } from \"@signe/reactive\";\nimport { Direction, RpgCommonPlayer } from \"../Player\";\nimport {\n PhysicsEngine,\n Vector2,\n Entity,\n EntityState,\n assignPolygonCollider,\n AABB,\n createCollider,\n} from \"@rpgjs/physic\";\nimport { combineLatest, Observable, share, Subject, Subscription } from \"rxjs\";\nimport { MovementManager } from \"../movement\";\nimport { WorldMapsManager, type RpgWorldMaps } from \"./WorldMaps\";\n\nexport type PhysicsEntityKind = \"hero\" | \"npc\" | \"generic\";\n\nexport interface MapPhysicsInitContext {\n mapData: any;\n}\n\nexport interface MapPhysicsEntityContext {\n owner: any;\n entity: Entity;\n kind: PhysicsEntityKind;\n}\n\ninterface ZoneOptions {\n x?: number;\n y?: number;\n radius: number;\n angle?: number;\n direction?: \"up\" | \"down\" | \"left\" | \"right\";\n linkedTo?: string;\n limitedByWalls?: boolean;\n}\n\nexport abstract class RpgCommonMap<T extends RpgCommonPlayer> {\n abstract players: Signal<Record<string, T>>;\n abstract events: Signal<Record<string, any>>;\n\n data = signal<any | null>(null);\n physic = new PhysicsEngine({\n timeStep: 1 / 60,\n gravity: new Vector2(0, 0),\n enableSleep: false,\n });\n moveManager = new MovementManager(() => this.physic);\n\n private speedScalar = 50; // Default speed scalar for movement\n\n // World Maps properties\n tileWidth: number = 32;\n tileHeight: number = 32;\n worldMapsManager?: WorldMapsManager;\n\n // Synchronization throttling properties\n throttleSync?: number;\n throttleStorage?: number;\n sessionExpiryTime?: number;\n\n tickSubscription?: Subscription | null;\n playersSubscription?: Subscription | null;\n eventsSubscription?: Subscription | null;\n private physicsAccumulatorMs = 0;\n private physicsSyncDepth = 0;\n\n /**\n * Whether to automatically subscribe to tick$ for physics updates\n * Set to false in test environments for manual control with nextTick()\n */\n protected autoTickEnabled: boolean = true;\n\n get isStandalone() {\n return typeof window !== 'undefined'\n }\n \n\n /**\n * Get the width of the map in pixels\n * \n * @returns The width of the map in pixels, or 0 if not loaded\n * \n * @example\n * ```ts\n * const width = map.widthPx;\n * console.log(`Map width: ${width}px`);\n * ```\n */\n get widthPx(): number {\n return this.data()?.width ?? 0\n }\n\n /**\n * Get the height of the map in pixels\n * \n * @returns The height of the map in pixels, or 0 if not loaded\n * \n * @example\n * ```ts\n * const height = map.heightPx;\n * console.log(`Map height: ${height}px`);\n * ```\n */\n get heightPx(): number {\n return this.data()?.height ?? 0\n }\n\n /**\n * Get the unique identifier of the map\n * \n * @returns The map ID, or empty string if not loaded\n * \n * @example\n * ```ts\n * const mapId = map.id;\n * console.log(`Current map: ${mapId}`);\n * ```\n */\n get id(): string {\n return this.data()?.id ?? ''\n }\n\n /**\n * Get the X position of this map in the world coordinate system\n * \n * This is used when maps are part of a larger world map. The world position\n * indicates where this map is located relative to other maps.\n * \n * @returns The X position in world coordinates, or 0 if not in a world\n * \n * @example\n * ```ts\n * const worldX = map.worldX;\n * console.log(`Map is at world position (${worldX}, ${map.worldY})`);\n * ```\n */\n get worldX(): number {\n const worldMaps = this.getWorldMapsManager?.();\n if (!worldMaps) return 0;\n // Extract real map ID (remove \"map-\" prefix if present)\n const mapId = this.id.startsWith('map-') ? this.id.slice(4) : this.id;\n return worldMaps.getMapInfo(mapId)?.worldX ?? 0\n }\n \n /**\n * Get the Y position of this map in the world coordinate system\n * \n * This is used when maps are part of a larger world map. The world position\n * indicates where this map is located relative to other maps.\n * \n * @returns The Y position in world coordinates, or 0 if not in a world\n * \n * @example\n * ```ts\n * const worldY = map.worldY;\n * console.log(`Map is at world position (${map.worldX}, ${worldY})`);\n * ```\n */\n get worldY(): number {\n const worldMaps = this.getWorldMapsManager?.();\n if (!worldMaps) return 0;\n // Extract real map ID (remove \"map-\" prefix if present)\n const mapId = this.id.startsWith('map-') ? this.id.slice(4) : this.id;\n return worldMaps.getMapInfo(mapId)?.worldY ?? 0\n }\n\n /**\n * Observable representing the game loop tick\n * \n * This observable emits the current timestamp every 16ms (approximately 60fps).\n * It's shared using the share() operator, meaning that all subscribers will receive\n * events from a single interval rather than creating multiple intervals.\n * \n * ## Physics Loop Architecture\n * \n * The physics simulation is centralized in this game loop:\n * \n * 1. **Input Processing** (`processInput`): Only updates entity velocities, does NOT step physics\n * 2. **Game Loop** (`tick$` -> `runFixedTicks`): Executes physics simulation with fixed timestep\n * 3. **Fixed Timestep Pattern**: Accumulator-based approach ensures deterministic physics\n * \n * ```\n * Input Events ─────────────────────────────────────────────────────────────►\n * │ \n * ▼ (update velocity only) \n * ┌─────────────────────────────────────────────────────────────────────────┐\n * │ Game Loop (tick$) │\n * │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │\n * │ │ updateMovements │ → │ stepOneTick │ → │ postTickUpdates │ │\n * │ │ (apply velocity)│ │ (physics step) │ │ (zones, sync) │ │\n * │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │\n * └─────────────────────────────────────────────────────────────────────────┘\n * ```\n * \n * @example\n * ```ts\n * // Subscribe to the game tick for custom updates\n * map.tick$.subscribe(({ delta, timestamp }) => {\n * // Custom game logic runs alongside physics\n * this.updateCustomEntities(delta);\n * });\n * ```\n */\n tick$ = new Observable<{ delta: number, timestamp: number }>(observer => {\n const interval = setInterval(() => {\n observer.next({\n delta: 16,\n timestamp: Date.now()\n });\n }, 16);\n return () => clearInterval(interval);\n }).pipe(\n share()\n );\n\n /**\n * Clear all physics content and reset to initial state\n * \n * This method completely clears the physics system by:\n * - Removing all hitboxes (static and movable)\n * - Removing all zones\n * - Clearing all collision data and events\n * - Clearing all movement events and sliding data\n * - Unsubscribing from the tick subscription\n * - Resetting the physics engine to a clean state\n * \n * Use this method when you need to completely reset the map's physics\n * system, such as when changing maps or restarting a level.\n * \n * @example\n * ```ts\n * // Clear all physics when changing maps\n * map.clearPhysic();\n * \n * // Then reload physics for the new map\n * map.loadPhysic();\n * ```\n */\n clearPhysic() {\n // Unsubscribe from tick to stop physics updates\n if (this.tickSubscription) {\n this.tickSubscription.unsubscribe();\n this.tickSubscription = null;\n }\n\n if (this.playersSubscription) {\n this.playersSubscription.unsubscribe();\n this.playersSubscription = null;\n }\n\n if (this.eventsSubscription) {\n this.eventsSubscription.unsubscribe();\n this.eventsSubscription = null;\n }\n\n // Clear all hitboxes and zones from physics system\n this.clearAll();\n\n // Reset movement manager\n this.moveManager.clearAll();\n this.emitPhysicsReset();\n\n this.physicsAccumulatorMs = 0;\n }\n\n /**\n * Clear all physics entities and internal state\n * @private\n */\n private clearAll(): void {\n // Remove all entities from physics engine\n const entities = this.physic.getEntities();\n for (const entity of entities) {\n const owner = (entity as any).owner;\n if (owner) {\n this.emitPhysicsEntityRemove({\n owner,\n entity,\n kind: this.resolvePhysicsEntityKind(owner, entity.uuid),\n });\n }\n this.unbindCharacterSignalSync(entity);\n this.physic.removeEntity(entity);\n }\n\n // Clear movement manager and zone manager\n this.physic.getMovementManager().clearAll();\n this.physic.getZoneManager().clear();\n }\n\n loadPhysic() {\n this.clearPhysic();\n\n const mapData = this.data?.();\n const mapWidth = typeof mapData?.width === \"number\" ? mapData.width : 0;\n const mapHeight = typeof mapData?.height === \"number\" ? mapData.height : 0;\n const hitboxes: Array<\n | { id?: string; x: number; y: number; width: number; height: number }\n | { id?: string; points: number[][] }\n > = Array.isArray(mapData?.hitboxes) ? mapData.hitboxes : [];\n\n if (mapWidth > 0 && mapHeight > 0) {\n const gap = 100;\n this.addStaticHitbox('map-width-left', -gap, 0, gap, mapHeight);\n this.addStaticHitbox('map-width-right', mapWidth, 0, gap, mapHeight);\n this.addStaticHitbox('map-height-top', 0, -gap, mapWidth, gap);\n this.addStaticHitbox('map-height-bottom', 0, mapHeight, mapWidth, gap);\n }\n\n for (let staticHitbox of hitboxes) {\n if ('x' in staticHitbox) {\n this.addStaticHitbox(staticHitbox.id ?? generateShortUUID(), staticHitbox.x, staticHitbox.y, staticHitbox.width, staticHitbox.height);\n }\n else if ('points' in staticHitbox) {\n this.addStaticHitbox(staticHitbox.id ?? generateShortUUID(), staticHitbox.points);\n }\n }\n\n this.emitPhysicsInit({ mapData });\n\n this.playersSubscription = (this.players as any).observable.subscribe(\n ({ value: player, type, key }: any) => {\n if (type === \"remove\") {\n this.removeHitbox(key, player, \"hero\");\n return;\n }\n\n if (type == 'reset') {\n if (!player) return;\n for (let id in player) {\n const _player = player[id]\n _player.id = _player.id ?? id;\n this.createCharacterHitbox(_player, \"hero\");\n }\n return;\n }\n\n if (!player) return;\n if (type === \"add\") {\n player.id = key;\n this.createCharacterHitbox(player, \"hero\");\n } else if (type === \"update\") {\n player.id = player.id ?? key;\n if (!this.getBody(key)) {\n this.createCharacterHitbox(player, \"hero\");\n return;\n }\n if (this.isPhysicsSyncingSignals) {\n return;\n }\n this.updateCharacterHitbox(player);\n }\n },\n );\n\n this.eventsSubscription = this.events.observable.subscribe(({ value: event, type, key }) => {\n if (type === \"add\") {\n event.id = key;\n this.createCharacterHitbox(event, \"npc\", {\n mass: 100,\n });\n } else if (type === \"remove\") {\n // Clean up movement event subscriptions\n const eventObj = this.getObjectById(key);\n if (eventObj && typeof (eventObj as any)._movementUnsubscribe === 'function') {\n (eventObj as any)._movementUnsubscribe();\n }\n this.removeHitbox(key, event, \"npc\");\n } else if (type === \"update\") {\n event.id = event.id ?? key;\n if (!this.getBody(key)) {\n this.createCharacterHitbox(event, \"npc\", {\n mass: 100,\n });\n return;\n }\n this.updateCharacterHitbox(event);\n } else if (type === \"reset\") {\n for (const id in event) {\n const _event = event[id];\n if (!_event) continue;\n _event.id = _event.id ?? id;\n this.createCharacterHitbox(_event, \"npc\", {\n mass: 100,\n });\n }\n }\n });\n\n // Hydrate physics world with already-loaded scene objects.\n // This covers cases where sync state is present before subscriptions are attached.\n const players = this.players();\n for (const id in players) {\n const player = players[id];\n if (!player) continue;\n player.id = player.id ?? id;\n this.createCharacterHitbox(player, \"hero\");\n }\n\n const events = this.events();\n for (const id in events) {\n const event = events[id];\n if (!event) continue;\n event.id = event.id ?? id;\n this.createCharacterHitbox(event, \"npc\", {\n mass: 100,\n });\n }\n\n // S'abonner au ticker automatique seulement si autoTickEnabled est true\n if (this.autoTickEnabled) {\n this.tickSubscription = this.tick$.subscribe(({ delta }) => {\n this.runFixedTicks(delta);\n });\n }\n }\n\n async movePlayer(player: T, direction: Direction) {\n // Calculate next position before movement\n const currentX = player.x();\n const currentY = player.y();\n const speed = player.speed();\n\n let nextX = currentX;\n let nextY = currentY;\n \n switch (direction) {\n case Direction.Left:\n nextX = currentX - speed;\n break;\n case Direction.Right:\n nextX = currentX + speed;\n break;\n case Direction.Up:\n nextY = currentY - speed;\n break;\n case Direction.Down:\n nextY = currentY + speed;\n break;\n }\n\n player.changeDirection(direction);\n\n // Check for automatic map change if the method exists\n if (typeof (player as any).autoChangeMap === 'function' && !player.isEvent()) {\n const mapChanged = await (player as any).autoChangeMap({ x: nextX, y: nextY }, direction);\n if (mapChanged) {\n this.stopMovement(player);\n return\n }\n }\n \n this.moveBody(player, direction);\n }\n\n /**\n * Check if an entity is currently moving\n * \n * @param id - ID of the entity to check\n * @returns Boolean indicating if the entity is in motion\n * \n * @example\n * ```ts\n * // Check if player is moving\n * if (map.isMoving('player1')) {\n * // Player is in motion\n * }\n * ```\n */\n isMoving(id: string): boolean {\n return this.isEntityMoving(id);\n }\n\n getObjectById(id: string) {\n return this.players()[id] ?? this.events()[id];\n }\n\n /**\n * Execute physics simulation with fixed timestep\n * \n * This method runs the physics engine using a fixed timestep accumulator pattern.\n * It ensures deterministic physics regardless of frame rate by:\n * 1. Accumulating delta time\n * 2. Running fixed-size physics steps until the accumulator is depleted\n * 3. Calling `updateMovements()` before each step to apply velocity changes\n * 4. Running post-tick updates (zones, callbacks) after each step\n * \n * ## Architecture\n * \n * The physics loop is centralized here and called from `tick$` subscription.\n * Input processing (`processInput`) only updates entity velocities - it does NOT\n * step the physics. This ensures:\n * - Consistent physics timing (60fps fixed timestep)\n * - No double-stepping when inputs are processed\n * - Proper accumulator-based interpolation support\n * \n * @param deltaMs - Time elapsed since last call in milliseconds\n * @param hooks - Optional callbacks for before/after each physics step\n * @returns Number of physics ticks executed\n * \n * @example\n * ```ts\n * // Called automatically by tick$ subscription\n * this.tickSubscription = this.tick$.subscribe(({ delta }) => {\n * this.runFixedTicks(delta);\n * });\n * \n * // Or manually with hooks for debugging\n * this.runFixedTicks(16, {\n * beforeStep: () => console.log('Before physics step'),\n * afterStep: (tick) => console.log(`Physics tick ${tick} completed`)\n * });\n * ```\n */\n protected runFixedTicks(\n deltaMs: number,\n hooks?: {\n beforeStep?: () => void;\n afterStep?: (tick: number) => void;\n },\n ): number {\n if (!Number.isFinite(deltaMs) || deltaMs <= 0) {\n return 0;\n }\n\n const fixedStepMs = this.physic.getWorld().getTimeStep() * 1000;\n this.physicsAccumulatorMs += deltaMs;\n let executed = 0;\n\n while (this.physicsAccumulatorMs >= fixedStepMs) {\n this.physicsAccumulatorMs -= fixedStepMs;\n hooks?.beforeStep?.();\n \n // Update movements before physics step (applies velocity changes from inputs)\n this.physic.updateMovements();\n \n const tick = this.physic.stepOneTick();\n executed += 1;\n \n // Run post-tick updates (zones, position sync callbacks)\n this.runPostTickUpdates();\n \n hooks?.afterStep?.(tick);\n }\n\n return executed;\n }\n\n /**\n * Manually trigger a single game tick\n * \n * This method allows you to manually advance the game by one tick (16ms at 60fps).\n * It's primarily useful for testing where you need precise control over when\n * physics updates occur, rather than relying on the automatic tick$ subscription.\n * \n * ## Use Cases\n * \n * - **Testing**: Control exactly when physics steps occur in unit tests\n * - **Manual control**: Step through game state manually for debugging\n * - **Deterministic testing**: Ensure consistent timing in test scenarios\n * \n * ## Important\n * \n * This method should NOT be used in production code alongside the automatic `tick$`\n * subscription, as it will cause double-stepping. Use either:\n * - Automatic ticks (via `loadPhysic()` which subscribes to `tick$`)\n * - Manual ticks (via `nextTick()` without `loadPhysic()` subscription)\n * \n * @param deltaMs - Optional delta time in milliseconds (default: 16ms for 60fps)\n * @returns Number of physics ticks executed\n * \n * @example\n * ```ts\n * // In tests: manually advance game by one tick\n * map.nextTick(); // Advances by 16ms (one frame at 60fps)\n * \n * // With custom delta\n * map.nextTick(32); // Advances by 32ms (two frames at 60fps)\n * \n * // In a test loop\n * for (let i = 0; i < 60; i++) {\n * map.nextTick(); // Simulate 1 second of game time\n * }\n * ```\n */\n nextTick(deltaMs: number = 16): number {\n return this.runFixedTicks(deltaMs);\n }\n\n /**\n * Force a single physics tick outside of the normal game loop\n * \n * This method is primarily used for **client-side prediction** where the client\n * needs to immediately simulate physics in response to local input, rather than\n * waiting for the next game loop tick.\n * \n * ## Use Cases\n * \n * - **Client-side prediction**: Immediately simulate player movement for responsive feel\n * - **Testing**: Force a physics step in unit tests\n * - **Special effects**: Immediate physics response for specific game events\n * \n * ## Important\n * \n * This method should NOT be used on the server for normal input processing.\n * Server-side physics is handled by `runFixedTicks` in the main game loop to ensure\n * deterministic simulation.\n * \n * @param hooks - Optional callbacks for before/after the physics step\n * @returns The physics tick number\n * \n * @example\n * ```ts\n * // Client-side: immediately simulate predicted movement\n * class RpgClientMap extends RpgCommonMap {\n * stepPredictionTick(): void {\n * this.forceSingleTick();\n * }\n * }\n * ```\n */\n protected forceSingleTick(hooks?: { beforeStep?: () => void; afterStep?: (tick: number) => void }): number {\n hooks?.beforeStep?.();\n this.physic.updateMovements();\n const tick = this.physic.stepOneTick();\n this.runPostTickUpdates();\n hooks?.afterStep?.(tick);\n const fixedMs = this.physic.getWorld().getTimeStep() * 1000;\n this.physicsAccumulatorMs = Math.max(0, this.physicsAccumulatorMs - fixedMs);\n return tick;\n }\n\n private createCharacterHitbox(\n owner: any,\n kind: PhysicsEntityKind,\n options?: { isStatic?: boolean; mass?: number },\n ): void {\n if (!owner?.id) {\n return;\n }\n const existingEntity = this.physic.getEntityByUUID(owner.id);\n if (existingEntity) {\n // Rebind owner when the player instance is restored/replaced (e.g. map transfer).\n // Position sync callbacks read entity.owner at runtime.\n (existingEntity as any).owner = owner;\n this.bindCharacterSignalSync(existingEntity, owner);\n this.updateCharacterHitbox(owner);\n return;\n }\n\n const hitbox = typeof owner.hitbox === \"function\" ? owner.hitbox() : owner.hitbox;\n const width = hitbox?.w ?? 32;\n const height = hitbox?.h ?? 32;\n const radius = Math.max(width, height) / 2;\n this.addCharacter({\n owner,\n radius,\n kind,\n maxSpeed: owner.speed(),\n collidesWithCharacters: !this.shouldDisableCharacterCollisions(owner),\n isStatic: options?.isStatic,\n mass: options?.mass,\n });\n const entity = this.getBody(owner.id);\n if (entity) {\n this.emitPhysicsEntityAdd({\n owner,\n entity,\n kind,\n });\n }\n }\n\n private updateCharacterHitbox(owner: any): void {\n if (!owner?.id) return;\n const entity = this.physic.getEntityByUUID(owner.id);\n if (!entity) return;\n\n // Rebind owner on every update to keep physics callbacks attached to the\n // current player instance after room/session transfers.\n (entity as any).owner = owner;\n this.bindCharacterSignalSync(entity, owner);\n\n const hitbox = typeof owner.hitbox === \"function\" ? owner.hitbox() : owner.hitbox;\n const width = hitbox?.w ?? 32;\n const height = hitbox?.h ?? 32;\n const topLeftX = this.resolveNumeric(owner.x);\n const topLeftY = this.resolveNumeric(owner.y);\n this.updateHitbox(owner.id, topLeftX, topLeftY, width, height);\n this.setCharacterCollisionEnabled(owner.id, !this.shouldDisableCharacterCollisions(owner));\n }\n\n private resolveNumeric(source: any, fallback = 0): number {\n if (typeof source === \"function\") {\n try {\n return Number(source()) ?? fallback;\n } catch {\n return fallback;\n }\n }\n if (typeof source === \"number\") {\n return source;\n }\n return fallback;\n }\n\n private bindCharacterSignalSync(entity: Entity, owner: any): void {\n const entityAny = entity as any;\n if (\n entityAny.__rpgSignalSyncOwner === owner &&\n typeof entityAny.__rpgSignalSyncUnsubscribe === \"function\"\n ) {\n return;\n }\n\n this.unbindCharacterSignalSync(entity);\n entityAny.__rpgSignalSyncOwner = owner;\n\n const subscriptions: Subscription[] = [];\n entityAny.__rpgSignalSyncUnsubscribe = () => {\n subscriptions.forEach((subscription) => subscription.unsubscribe());\n delete entityAny.__rpgSignalSyncUnsubscribe;\n delete entityAny.__rpgSignalSyncOwner;\n };\n\n const syncFromSignals = () => {\n if (this.isPhysicsSyncingSignals) {\n return;\n }\n const currentOwner = entityAny.owner;\n if (!currentOwner?.id || currentOwner.id !== entity.uuid) {\n return;\n }\n this.updateCharacterHitbox(currentOwner);\n };\n\n const subscribeSignal = (signalLike: any) => {\n const observable = signalLike?.observable;\n if (!observable || typeof observable.subscribe !== \"function\") {\n return;\n }\n subscriptions.push(observable.subscribe(() => syncFromSignals()));\n };\n\n subscribeSignal(owner.x);\n subscribeSignal(owner.y);\n subscribeSignal(owner.hitbox);\n subscribeSignal(owner._through);\n }\n\n private unbindCharacterSignalSync(entity: Entity): void {\n const entityAny = entity as any;\n const unsubscribe = entityAny.__rpgSignalSyncUnsubscribe;\n if (typeof unsubscribe === \"function\") {\n unsubscribe();\n return;\n }\n delete entityAny.__rpgSignalSyncOwner;\n }\n\n private shouldDisableCharacterCollisions(owner: any): boolean {\n if (typeof owner._through === \"function\") {\n try {\n return !!owner._through();\n } catch {\n return false;\n }\n }\n if (typeof owner.through === \"boolean\") {\n return owner.through;\n }\n return false;\n }\n\n private resolvePhysicsEntityKind(owner: any, id?: string): PhysicsEntityKind {\n if (typeof owner?.isEvent === \"function\") {\n try {\n if (owner.isEvent()) {\n return \"npc\";\n }\n } catch {\n // Ignore owner inspection errors and fallback below\n }\n }\n\n const ownerId = typeof owner?.id === \"string\" ? owner.id : id;\n if (ownerId && this.players()?.[ownerId]) {\n return \"hero\";\n }\n if (ownerId && this.events()?.[ownerId]) {\n return \"npc\";\n }\n return \"generic\";\n }\n\n protected emitPhysicsInit(_context: MapPhysicsInitContext): void {}\n\n protected emitPhysicsEntityAdd(_context: MapPhysicsEntityContext): void {}\n\n protected emitPhysicsEntityRemove(_context: MapPhysicsEntityContext): void {}\n\n protected emitPhysicsReset(): void {}\n\n protected withPhysicsSync<T>(run: () => T): T {\n this.physicsSyncDepth += 1;\n try {\n return run();\n } finally {\n this.physicsSyncDepth -= 1;\n }\n }\n\n protected get isPhysicsSyncingSignals(): boolean {\n return this.physicsSyncDepth > 0;\n }\n\n /**\n * Get the world maps manager\n * \n * @returns WorldMapsManager instance or null if not configured\n * \n * @example\n * ```ts\n * const worldMaps = map.getWorldMapsManager();\n * if (worldMaps) {\n * const adjacentMaps = worldMaps.getAdjacentMaps(currentMap, coordinates);\n * }\n * ```\n */\n getWorldMapsManager(): WorldMapsManager | null {\n return this.worldMapsManager ?? null;\n }\n\n /**\n * Get attached World\n * \n * Recover the world attached to this map (undefined if no world attached)\n * \n * @since 3.0.0-beta.8\n * @returns {RpgWorldMaps | undefined} The world maps manager instance if attached, otherwise undefined\n * \n * @example\n * ```ts\n * const world = map.getInWorldMaps();\n * if (world) {\n * console.log(world.getAllMaps());\n * }\n * ```\n */\n getInWorldMaps(): RpgWorldMaps | undefined {\n return this.worldMapsManager ?? undefined;\n }\n\n /**\n * Remove this map from the world\n * \n * Remove this map from the world\n * \n * @since 3.0.0-beta.8\n * @returns {boolean | undefined} True if removed, false if not found, undefined if no world attached\n * \n * @example\n * ```ts\n * const removed = map.removeFromWorldMaps();\n * ```\n */\n removeFromWorldMaps(): boolean | undefined {\n if (!this.worldMapsManager) return undefined;\n const id = (this as any).id as string | undefined;\n if (!id) return false;\n return this.worldMapsManager.removeMap(id);\n }\n\n /**\n * Assign the map to a world\n * \n * Assign the map to a world\n * \n * @since 3.0.0-beta.8\n * @param {RpgWorldMaps} worldMap world maps\n * @returns {void}\n * \n * @example\n * ```ts\n * const world = new WorldMapsManager();\n * world.configure([{ id: 'm1', worldX: 0, worldY: 0, width: 1024, height: 1024 }]);\n * map.setInWorldMaps(world);\n * ```\n */\n setInWorldMaps(worldMap: RpgWorldMaps): void {\n this.worldMapsManager = worldMap;\n }\n\n \n\n /**\n * Create a temporary and moving hitbox on the map\n * \n * Allows to create a temporary hitbox that moves through multiple positions sequentially.\n * For example, you can use it to explode a bomb and find all the affected players, \n * or during a sword strike, you can create a moving hitbox and find the affected players.\n * \n * The method creates a zone sensor that moves through the specified hitbox positions\n * at the given speed, detecting collisions with players and events at each step.\n * \n * @param hitboxes - Array of hitbox positions to move through sequentially\n * @param options - Configuration options for the movement\n * @returns Observable that emits arrays of hit entities and completes when movement is finished\n * \n * @example\n * ```ts\n * // Create a sword slash effect that moves through two positions\n * map.createMovingHitbox([\n * { x: 100, y: 100, width: 50, height: 50 },\n * { x: 120, y: 100, width: 50, height: 50 }\n * ], { speed: 2 }).subscribe({\n * next(hits) {\n * // hits contains RpgPlayer or RpgEvent objects that were hit\n * console.log('Hit entities:', hits);\n * },\n * complete() {\n * console.log('Movement finished');\n * }\n * });\n * ```\n */\n createMovingHitbox(\n hitboxes: Array<{ x: number; y: number; width: number; height: number }>,\n options: { speed?: number } = {}\n ): Observable<(T | any)[]> {\n const { speed = 1 } = options;\n const zoneId = `moving_hitbox_${generateShortUUID()}`;\n\n return new Observable(observer => {\n if (hitboxes.length === 0) {\n observer.complete();\n return;\n }\n\n let currentIndex = 0;\n let frameCounter = 0;\n const hitEntities = new Set<string>();\n\n // Create initial zone at first hitbox position\n const firstHitbox = hitboxes[0];\n const radius = Math.max(firstHitbox.width, firstHitbox.height) / 2;\n\n this.addZone(zoneId, {\n x: firstHitbox.x + firstHitbox.width / 2,\n y: firstHitbox.y + firstHitbox.height / 2,\n radius: radius\n });\n\n // Register zone events to detect hits\n this.registerZoneEvents(\n zoneId,\n (hitIds: string[]) => {\n // Convert hit IDs to actual objects and emit\n const hitObjects = hitIds\n .map(id => this.getObjectById(id))\n .filter(obj => obj !== undefined);\n\n if (hitObjects.length > 0) {\n // Track hit entities to avoid duplicates\n hitIds.forEach(id => hitEntities.add(id));\n observer.next(hitObjects);\n }\n }\n );\n\n // Subscribe to tick to handle movement\n const tickSubscription = this.tick$.subscribe(() => {\n frameCounter++;\n\n // Move to next position based on speed\n if (frameCounter >= speed) {\n frameCounter = 0;\n currentIndex++;\n\n // Check if we've reached the end\n if (currentIndex >= hitboxes.length) {\n // Clean up and complete\n this.removeZone(zoneId);\n tickSubscription.unsubscribe();\n observer.complete();\n return;\n }\n\n // Move zone to next position\n const nextHitbox = hitboxes[currentIndex];\n const zone = this.getZone(zoneId);\n\n if (zone) {\n // Remove current zone and create new one at next position\n this.removeZone(zoneId);\n\n const newRadius = Math.max(nextHitbox.width, nextHitbox.height) / 2;\n this.addZone(zoneId, {\n x: nextHitbox.x + nextHitbox.width / 2,\n y: nextHitbox.y + nextHitbox.height / 2,\n radius: newRadius\n });\n\n // Re-register zone events for the new zone\n this.registerZoneEvents(\n zoneId,\n (hitIds: string[]) => {\n const hitObjects = hitIds\n .map(id => this.getObjectById(id))\n .filter(obj => obj !== undefined);\n\n if (hitObjects.length > 0) {\n hitIds.forEach(id => hitEntities.add(id));\n observer.next(hitObjects);\n }\n }\n );\n }\n }\n });\n\n // Cleanup function\n return () => {\n tickSubscription.unsubscribe();\n this.removeZone(zoneId);\n };\n });\n }\n\n /**\n * Add a static hitbox to the physics world\n * @private\n */\n private addStaticHitbox(\n id: string,\n xOrPoints: number | number[][],\n y?: number,\n width?: number,\n height?: number,\n ): string {\n // Check if entity already exists\n if (this.physic.getEntityByUUID(id)) {\n throw new Error(`Hitbox with id ${id} already exists`);\n }\n\n let entity: Entity;\n let boxWidth: number;\n let boxHeight: number;\n\n if (Array.isArray(xOrPoints)) {\n const points = xOrPoints;\n if (points.length < 3) {\n throw new Error(`Polygon must have at least 3 points, got ${points.length}`);\n }\n\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n\n for (const point of points) {\n if (!Array.isArray(point) || point.length !== 2 || typeof point[0] !== \"number\" || typeof point[1] !== \"number\") {\n throw new Error(`Invalid point ${JSON.stringify(point)}. Expected [x, y].`);\n }\n minX = Math.min(minX, point[0]);\n maxX = Math.max(maxX, point[0]);\n minY = Math.min(minY, point[1]);\n maxY = Math.max(maxY, point[1]);\n }\n\n const centerX = (minX + maxX) / 2;\n const centerY = (minY + maxY) / 2;\n boxWidth = Math.max(maxX - minX, 1);\n boxHeight = Math.max(maxY - minY, 1);\n\n entity = this.physic.createEntity({\n uuid: id,\n position: { x: centerX, y: centerY },\n width: boxWidth,\n height: boxHeight,\n mass: Infinity,\n state: EntityState.Static,\n restitution: 0\n });\n entity.freeze();\n\n const localVertices = points.map((point) => {\n const [px, py] = point as [number, number];\n return new Vector2(px - centerX, py - centerY);\n });\n assignPolygonCollider(entity, { vertices: localVertices });\n } else {\n if (typeof y !== \"number\" || typeof width !== \"number\" || typeof height !== \"number\") {\n throw new Error(\"Rectangle hitbox requires x, y, width and height parameters\");\n }\n\n const centerX = xOrPoints + width / 2;\n const centerY = y + height / 2;\n boxWidth = Math.max(width, 1);\n boxHeight = Math.max(height, 1);\n\n entity = this.physic.createEntity({\n uuid: id,\n position: { x: centerX, y: centerY },\n width: boxWidth,\n height: boxHeight,\n mass: Infinity,\n state: EntityState.Static,\n restitution: 0\n });\n entity.freeze();\n }\n\n return id;\n }\n\n /**\n * Add a character to the physics world\n * @private\n */\n /**\n * Add a character entity to the physics world\n * \n * Creates a physics entity for a character (player or NPC) with proper position handling.\n * The owner's x/y signals represent **top-left** coordinates, while the physics entity\n * uses **center** coordinates internally.\n * \n * ## Position System\n * \n * - `owner.x()` / `owner.y()` → **top-left** corner of the character's hitbox\n * - `entity.position` → **center** of the physics collider\n * - Conversion: `center = topLeft + (size / 2)`\n * \n * @param options - Character configuration\n * @returns The character's unique ID\n * \n * @example\n * ```ts\n * // Player at top-left position (100, 100) with 32x32 hitbox\n * // Physics entity will be at center (116, 116)\n * this.addCharacter({\n * owner: player,\n * x: 116, // center X (ignored, uses owner.x())\n * y: 116, // center Y (ignored, uses owner.y())\n * kind: \"hero\"\n * });\n * ```\n * \n * @private\n */\n private addCharacter(options: {\n owner: any;\n radius?: number;\n kind?: PhysicsEntityKind;\n collidesWithCharacters?: boolean;\n maxSpeed?: number;\n isStatic?: boolean;\n friction?: number;\n mass?: number;\n }): string {\n if (!options || typeof options.owner?.id !== \"string\") {\n throw new Error(\"Character requires an owner object with a string id\");\n }\n\n const owner = options.owner;\n const id = owner.id;\n\n // Get hitbox dimensions - hitbox.w/h are the FULL dimensions, not radius\n const hitbox = typeof owner.hitbox === \"function\" ? owner.hitbox() : owner.hitbox;\n const width = hitbox?.w ?? 32;\n const height = hitbox?.h ?? 32;\n\n // Calculate radius from dimensions (use the larger dimension for circular collider)\n const radius = Math.max(width, height) / 2;\n\n // owner.x() and owner.y() are TOP-LEFT positions\n const topLeftX = owner.x();\n const topLeftY = owner.y();\n\n // Convert to CENTER for physics engine\n const centerX = topLeftX + width / 2;\n const centerY = topLeftY + height / 2;\n\n const isStatic = !!options.isStatic;\n\n const entity = this.physic.createEntity({\n uuid: id,\n position: { x: centerX, y: centerY },\n // Use radius for circular collision detection\n radius: Math.max(radius, 1),\n // Also store explicit width/height for consistent position conversions\n // This ensures getBodyPosition/setBodyPosition use the same dimensions\n width: width,\n height: height,\n mass: options.mass ?? (isStatic ? Infinity : 1),\n friction: options.friction ?? 0.4,\n linearDamping: isStatic ? 1 : 0.2,\n maxLinearVelocity: options.maxSpeed ? options.maxSpeed * this.speedScalar : 200,\n restitution: 0\n });\n\n if (isStatic) {\n entity.freeze();\n } else {\n entity.unfreeze();\n }\n\n // Store owner reference directly on entity for syncing positions\n (entity as any).owner = owner;\n this.bindCharacterSignalSync(entity, owner);\n\n entity.onDirectionChange(({ cardinalDirection }) => {\n // hack to prevent direction in client side\n if (!('$send' in this)) return;\n const owner = (entity as any).owner;\n if (!owner) return;\n if (cardinalDirection === 'idle') return;\n // Don't change direction if it's locked\n if (owner.directionFixed) return;\n owner.changeDirection(cardinalDirection as Direction);\n });\n\n entity.onMovementChange(({ isMoving, intensity }) => {\n // Prevent animation changes on client side (same as onDirectionChange)\n if (!('$send' in this)) return;\n \n // Get owner from entity (same pattern as onDirectionChange)\n const owner = (entity as any).owner;\n if (!owner) return;\n \n // Don't change animation if it's locked\n if (owner.animationFixed) return;\n \n // Only change animation if intensity is low (avoid animation flicker on micro-movements)\n // Intensity threshold: 10 pixels/second (adjust based on your game's needs)\n const LOW_INTENSITY_THRESHOLD = 10;\n \n // Try to use setAnimation method if available (preferred method)\n // Otherwise, try to access animationName signal directly\n const hasSetAnimation = typeof owner.setAnimation === 'function';\n const animationNameSignal = owner.animationName;\n const ownerHasAnimationName = animationNameSignal && typeof animationNameSignal === 'object' && typeof animationNameSignal.set === 'function';\n \n if (isMoving && intensity > LOW_INTENSITY_THRESHOLD) {\n if (hasSetAnimation) {\n owner.setGraphicAnimation(\"walk\");\n } else if (ownerHasAnimationName) {\n animationNameSignal.set(\"walk\");\n }\n } else if (!isMoving) {\n if (hasSetAnimation) {\n owner.setGraphicAnimation(\"stand\");\n } else if (ownerHasAnimationName) {\n animationNameSignal.set(\"stand\");\n }\n }\n // If moving with high intensity, keep current animation (e.g., already running)\n });\n\n // Register position sync handler to update owner.x and owner.y.\n // Read owner dynamically from entity to avoid stale references after map transfer.\n \n entity.onPositionChange(({ x, y }) => {\n const currentOwner = (entity as any).owner;\n if (!currentOwner) {\n return;\n }\n\n const entityWidth = entity.width || width;\n const entityHeight = entity.height || height;\n // Calculate top-left from center using the original hitbox dimensions\n // This ensures consistency: center = topLeft + (size / 2)\n // Therefore: topLeft = center - (size / 2)\n const topLeftX = x - entityWidth / 2;\n const topLeftY = y - entityHeight / 2;\n let changed = false;\n\n this.withPhysicsSync(() => {\n if (typeof currentOwner.x === \"function\" && typeof currentOwner.x.set === \"function\") {\n currentOwner.x.set(Math.round(topLeftX));\n changed = true;\n }\n if (typeof currentOwner.y === \"function\" && typeof currentOwner.y.set === \"function\") {\n currentOwner.y.set(Math.round(topLeftY));\n changed = true;\n }\n });\n if (changed) {\n currentOwner.applyFrames?.();\n }\n });\n\n // Add resolution filter for through/throughOtherPlayer/throughEvent\n // This filter determines if collisions should be RESOLVED (blocking) or just DETECTED.\n // When returning false, entities pass through each other but collision events still fire.\n entity.addResolutionFilter((self, other) => {\n const selfOwner = (self as any).owner;\n const otherOwner = (other as any).owner;\n\n // If either entity has no owner, resolve collision (e.g., walls, obstacles must block)\n if (!selfOwner || !otherOwner) {\n return true;\n }\n\n \n if (selfOwner.z() !== otherOwner.z()) {\n return false; // Don't resolve collision\n }\n\n // Check if selfOwner has _through property (passes through everything)\n // This applies to both players and events\n if (typeof selfOwner._through === \"function\") {\n try {\n if (selfOwner._through() === true) {\n return false; // Pass through but events still fire\n }\n } catch {\n // Ignore errors\n }\n } else if (selfOwner.through === true) {\n return false;\n }\n\n // Determine the type of both entities via lookup in players/events\n const playersMap = this.players();\n const eventsMap = this.events();\n const isSelfPlayer = !!playersMap[self.uuid];\n const isOtherPlayer = !!playersMap[other.uuid];\n const isSelfEvent = !!eventsMap[self.uuid];\n const isOtherEvent = !!eventsMap[other.uuid];\n const readScenarioOwnerId = (owner: any): string | undefined => {\n const scenarioOwnerId = owner?._scenarioOwnerId ?? owner?.scenarioOwnerId;\n return typeof scenarioOwnerId === \"string\" && scenarioOwnerId.length > 0\n ? scenarioOwnerId\n : undefined;\n };\n const selfScenarioOwnerId = readScenarioOwnerId(selfOwner);\n const otherScenarioOwnerId = readScenarioOwnerId(otherOwner);\n\n // Scenario events are isolated per player:\n // they only collide with their owner and scenario events of the same owner.\n if (selfScenarioOwnerId) {\n if (isOtherPlayer && other.uuid !== selfScenarioOwnerId) {\n return false;\n }\n if (isOtherEvent && otherScenarioOwnerId !== selfScenarioOwnerId) {\n return false;\n }\n }\n if (otherScenarioOwnerId) {\n if (isSelfPlayer && self.uuid !== otherScenarioOwnerId) {\n return false;\n }\n if (isSelfEvent && selfScenarioOwnerId !== otherScenarioOwnerId) {\n return false;\n }\n }\n\n // throughOtherPlayer only applies when SELF is a player and OTHER is also a player\n // (players passing through other players)\n if (isSelfPlayer && isOtherPlayer) {\n if (typeof selfOwner._throughOtherPlayer === \"function\") {\n try {\n if (selfOwner._throughOtherPlayer() === true) {\n return false; // Pass through players but events still fire\n }\n } catch {\n // Ignore errors\n }\n } else if (selfOwner.throughOtherPlayer === true) {\n return false;\n }\n }\n\n // throughEvent only applies when SELF is a player and OTHER is an event\n // (players passing through events)\n if (isSelfPlayer && isOtherEvent) {\n if (typeof selfOwner._throughEvent === \"function\") {\n try {\n if (selfOwner._throughEvent() === true) {\n return false; // Pass through events but events still fire\n }\n } catch {\n // Ignore errors\n }\n } else if (selfOwner.throughEvent === true) {\n return false;\n }\n }\n\n return true; // Resolve collision (block movement)\n });\n\n return id;\n }\n\n /**\n * Update hitbox position and size\n * \n * @param id - Entity ID\n * @param x - Top-left X coordinate\n * @param y - Top-left Y coordinate\n * @param width - Optional width\n * @param height - Optional height\n * @returns True if hitbox was updated successfully\n */\n updateHitbox(id: string, x: number, y: number, width?: number, height?: number): boolean {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) return false;\n\n if (typeof width === \"number\" && typeof height === \"number\") {\n entity.width = Math.max(width, 1);\n entity.height = Math.max(height, 1);\n }\n\n // Calculate center from top-left\n const entityWidth = entity.width || entity.radius * 2 || 32;\n const entityHeight = entity.height || entity.radius * 2 || 32;\n const centerX = x + entityWidth / 2;\n const centerY = y + entityHeight / 2;\n entity.position.set(centerX, centerY);\n\n return true;\n }\n\n /**\n * Remove a hitbox from the physics world\n * @private\n */\n private removeHitbox(id: string, owner?: any, kind?: PhysicsEntityKind): boolean {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) {\n return false;\n }\n this.unbindCharacterSignalSync(entity);\n const resolvedOwner = owner ?? (entity as any).owner;\n if (resolvedOwner) {\n this.emitPhysicsEntityRemove({\n owner: resolvedOwner,\n entity,\n kind: kind ?? this.resolvePhysicsEntityKind(resolvedOwner, id),\n });\n }\n this.physic.removeEntity(entity);\n return true;\n }\n\n /**\n * Check if an entity is moving\n * @private\n */\n private isEntityMoving(id: string): boolean {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) return false;\n // Check if entity has velocity\n return entity.velocity.length() > 0.1;\n }\n\n /**\n * Move a body in a direction\n * @private\n */\n private moveBody(player: any, direction: Direction): boolean {\n const entity = this.physic.getEntityByUUID(player.id);\n if (!entity) return false;\n\n const speedValue = player.speed()\n\n let vx = 0, vy = 0;\n switch (direction) {\n case Direction.Left:\n vx = -speedValue * this.speedScalar;\n break;\n case Direction.Right:\n vx = speedValue * this.speedScalar;\n break;\n case Direction.Up:\n vy = -speedValue * this.speedScalar;\n break;\n case Direction.Down:\n vy = speedValue * this.speedScalar;\n break;\n }\n\n // Input sets the base velocity. Movement strategies (dash/knockback/AI, etc.)\n // are responsible for adding or overriding velocity when needed.\n entity.setVelocity({ x: vx, y: vy });\n entity.wakeUp();\n return true;\n }\n\n /**\n * Stop movement for a player\n * \n * Completely stops all movement for a player, including:\n * - Clearing all active movement strategies (dash, linear moves, etc.)\n * - Setting velocity to zero\n * - Resetting intended direction\n * \n * This method is particularly useful when changing maps to ensure\n * the player doesn't carry over movement from the previous map.\n * \n * @param player - The player to stop\n * @returns True if the player was found and movement was stopped\n * \n * @example\n * ```ts\n * // Stop player movement when changing maps\n * if (mapChanged) {\n * map.stopMovement(player);\n * }\n * \n * // Stop movement when player dies\n * if (player.isDead()) {\n * map.stopMovement(player);\n * }\n * ```\n * @protected\n */\n protected stopMovement(player: any): boolean {\n const entity = this.physic.getEntityByUUID(player.id);\n if (!entity) return false;\n\n // Stop all movement using the MovementManager (clears strategies and stops entity movement)\n this.moveManager.stopMovement(player.id);\n\n player.pendingInputs = [];\n \n return true;\n }\n\n /**\n * Set character collision enabled\n * @private\n */\n private setCharacterCollisionEnabled(id: string, collides: boolean): boolean {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) {\n return false;\n }\n // Collision filtering is handled by PhysicsEngine's collision system\n // This method is kept for API compatibility but doesn't need to do anything\n // as PhysicsEngine handles collisions automatically\n return true;\n }\n\n /**\n * Get collisions for an entity\n * \n * Returns all entities that are colliding with the specified entity.\n * Uses the entity's actual AABB bounds to detect collisions in all directions.\n * \n * @param id - Entity UUID to check collisions for\n * @returns Array of entity UUIDs that are colliding with the specified entity\n * \n * @example\n * ```ts\n * // Get all entities colliding with player\n * const collisions = map.getCollisions('player1');\n * collisions.forEach(id => {\n * console.log(`Entity ${id} is colliding with player`);\n * });\n * ```\n */\n protected getCollisions(id: string): string[] {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) return [];\n\n // Get the entity's actual collider and AABB bounds\n const collider = createCollider(entity);\n if (!collider) return [];\n\n const entityAABB = collider.getBounds();\n \n // Expand AABB slightly to ensure we catch nearby entities\n // This helps with edge cases where entities are just touching\n const expandedAABB = entityAABB.expand(1);\n\n // Query nearby entities using the expanded AABB\n const nearby = this.physic.queryAABB(expandedAABB);\n const collisions: string[] = [];\n\n // Check actual AABB intersections for each nearby entity\n for (const other of nearby) {\n if (other.uuid === id) continue;\n\n const otherCollider = createCollider(other);\n if (!otherCollider) continue;\n\n const otherAABB = otherCollider.getBounds();\n \n // Check if AABBs actually intersect\n if (entityAABB.intersects(otherAABB)) {\n collisions.push(other.uuid);\n }\n }\n\n return collisions;\n }\n\n /**\n * Get physics body (entity) for an id\n * @protected\n */\n public getBody(id: string): Entity | undefined {\n return this.physic.getEntityByUUID(id);\n }\n\n /**\n * Get the current physics tick\n * @returns Current tick number\n */\n getTick(): number {\n return this.physic.getTick();\n }\n\n /**\n * Get body position in different modes\n * \n * @param id - Entity ID\n * @param mode - Position mode: \"center\" or \"top-left\"\n * @returns Position coordinates or undefined if entity not found\n */\n getBodyPosition(\n id: string,\n mode: \"center\" | \"top-left\" = \"center\",\n ): { x: number; y: number } | undefined {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) return undefined;\n\n const centerX = entity.position.x;\n const centerY = entity.position.y;\n if (mode === \"center\") {\n return { x: centerX, y: centerY };\n }\n\n // Calculate top-left from center\n const width = entity.width || (entity.radius ? entity.radius * 2 : 32);\n const height = entity.height || (entity.radius ? entity.radius * 2 : 32);\n return {\n x: centerX - width / 2,\n y: centerY - height / 2,\n };\n }\n\n /**\n * Set body position\n * \n * @param id - Entity ID\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param mode - Position mode: \"center\" or \"top-left\"\n * @returns True if position was set successfully\n */\n setBodyPosition(\n id: string,\n x: number,\n y: number,\n mode: \"center\" | \"top-left\" = \"center\",\n ): Entity | undefined {\n const entity = this.physic.getEntityByUUID(id);\n if (!entity) return;\n\n const width = entity.width || (entity.radius ? entity.radius * 2 : 32);\n const height = entity.height || (entity.radius ? entity.radius * 2 : 32);\n\n let centerX = x;\n let centerY = y;\n if (mode === \"top-left\") {\n centerX = x + width / 2;\n centerY = y + height / 2;\n }\n\n entity.position.set(centerX, centerY);\n entity.notifyPositionChange();\n \n return entity;\n }\n\n /**\n * Handle collision enter\n * @private\n */\n // Collision handling is now done directly via entity hooks in addCharacter\n // These methods are no longer needed as PhysicsEngine handles collisions internally\n\n /**\n * Add a zone\n * @private\n */\n private addZone(id: string, options: ZoneOptions): string {\n // Check if zone or entity already exists\n const zoneManager = this.physic.getZoneManager();\n if (this.physic.getEntityByUUID(id)) {\n throw new Error(`Zone with id ${id} already exists as entity`);\n }\n\n const radius = options.radius;\n if (typeof radius !== \"number\" || radius <= 0) {\n throw new Error(\"Zone radius must be a positive number\");\n }\n\n // If linkedTo is specified, get the entity\n let attachedEntity: Entity | undefined;\n if (options.linkedTo) {\n attachedEntity = this.physic.getEntityByUUID(options.linkedTo);\n if (!attachedEntity) {\n throw new Error(`Cannot link zone to unknown entity ${options.linkedTo}`);\n }\n }\n\n const callbacks: { onEnter?: (entities: Entity[]) => void; onExit?: (entities: Entity[]) => void } = {};\n\n // Store callbacks for later updates\n (callbacks as any)._onEnterString = undefined;\n (callbacks as any)._onExitString = undefined;\n\n const zoneId = attachedEntity\n ? zoneManager.createAttachedZone(attachedEntity, {\n radius,\n angle: options.angle ?? 360,\n direction: options.direction ?? 'down',\n limitedByWalls: options.limitedByWalls ?? false,\n }, callbacks)\n : zoneManager.createZone({\n position: { x: options.x ?? 0, y: options.y ?? 0 },\n radius,\n angle: options.angle ?? 360,\n direction: options.direction ?? 'down',\n limitedByWalls: options.limitedByWalls ?? false,\n }, callbacks);\n\n // Store zone ID mapping\n (this as any)._zoneIdMap = (this as any)._zoneIdMap || new Map();\n (this as any)._zoneIdMap.set(id, zoneId);\n\n return id;\n }\n\n /**\n * Remove a zone\n * @private\n */\n private removeZone(id: string): boolean {\n const zoneIdMap = (this as any)._zoneIdMap;\n if (!zoneIdMap) return false;\n\n const zoneId = zoneIdMap.get(id);\n if (!zoneId) return false;\n\n const zoneManager = this.physic.getZoneManager();\n zoneManager.removeZone(zoneId);\n zoneIdMap.delete(id);\n return true;\n }\n\n /**\n * Get a zone\n * @private\n */\n private getZone(id: string): any {\n const zoneIdMap = (this as any)._zoneIdMap;\n if (!zoneIdMap) return undefined;\n\n const zoneId = zoneIdMap.get(id);\n if (!zoneId) return undefined;\n\n const zoneManager = this.physic.getZoneManager();\n return zoneManager.getZone(zoneId);\n }\n\n /**\n * Register zone events\n * @private\n */\n private registerZoneEvents(\n id: string,\n onEnter?: (hitIds: string[]) => void,\n onExit?: (hitIds: string[]) => void,\n ): boolean {\n const zoneIdMap = (this as any)._zoneIdMap;\n if (!zoneIdMap) return false;\n\n const zoneId = zoneIdMap.get(id);\n if (!zoneId) return false;\n\n const zoneManager = this.physic.getZoneManager();\n\n // Use registerCallbacks to update callbacks\n const callbacks: { onEnter?: (entities: Entity[]) => void; onExit?: (entities: Entity[]) => void } = {};\n if (onEnter) {\n callbacks.onEnter = (entities: Entity[]) => {\n onEnter(entities.map(e => e.uuid));\n };\n }\n if (onExit) {\n callbacks.onExit = (entities: Entity[]) => {\n onExit(entities.map(e => e.uuid));\n };\n }\n\n return zoneManager.registerCallbacks(zoneId, callbacks);\n }\n\n /**\n * Run post-tick updates (update zones)\n * @private\n */\n private runPostTickUpdates(): void {\n // Position sync is now handled automatically by entity.onPositionChange hooks\n // Movement callbacks are also handled in the onPositionChange handler\n\n // Update zones\n const zoneManager = this.physic.getZoneManager();\n zoneManager.update();\n }\n}\n","import { Direction } from \"../Player\";\n\n/**\n * Interface for world map information\n */\nexport interface WorldMapInfo {\n id: string;\n x: number; // World X position \n y: number; // World Y position\n width: number; // Width in pixels\n height: number; // Height in pixels\n worldX: number; // World X coordinate (alias for x)\n worldY: number; // World Y coordinate (alias for y)\n widthPx: number; // Width in pixels (alias for width)\n heightPx: number; // Height in pixels (alias for height)\n tileWidth: number; // Tile width\n tileHeight: number; // Tile height\n}\n\n/**\n * Configuration for a world map\n */\nexport interface WorldMapConfig {\n id: string;\n worldX: number;\n worldY: number;\n width: number;\n height: number;\n tileWidth?: number;\n tileHeight?: number;\n}\n\n/**\n * World Maps Manager\n * \n * Manages a collection of interconnected maps and their spatial relationships\n */\nexport class WorldMapsManager {\n private maps: Map<string, WorldMapInfo> = new Map();\n private spatialIndex: Map<string, string> = new Map(); // \"x,y\" -> mapId\n\n /**\n * Configure the world maps\n * \n * @param configs - Array of map configurations\n * \n * @example\n * ```ts\n * const worldMaps = new WorldMapsManager();\n * worldMaps.configure([\n * { id: \"town\", worldX: 0, worldY: 0, width: 1024, height: 768 },\n * { id: \"forest\", worldX: 1024, worldY: 0, width: 1024, height: 768 }\n * ]);\n * ```\n */\n configure(configs: WorldMapConfig[]) {\n this.maps.clear();\n this.spatialIndex.clear();\n\n for (const config of configs) {\n const worldMap: WorldMapInfo = {\n id: config.id,\n x: config.worldX,\n y: config.worldY,\n width: config.width,\n height: config.height,\n worldX: config.worldX,\n worldY: config.worldY,\n widthPx: config.width,\n heightPx: config.height,\n tileWidth: config.tileWidth ?? 32,\n tileHeight: config.tileHeight ?? 32,\n };\n\n this.maps.set(config.id, worldMap);\n this.spatialIndex.set(`${config.worldX},${config.worldY}`, config.id);\n }\n }\n\n /**\n * Remove a map from the world by its id\n * \n * Deletes the map from the internal registry and spatial index.\n * \n * @param mapId - Map identifier\n * @returns True if a map was removed, false otherwise\n * \n * @example\n * ```ts\n * const removed = world.removeMap(\"forest\");\n * ```\n */\n removeMap(mapId: string): boolean {\n const map = this.maps.get(mapId);\n if (!map) return false;\n this.maps.delete(mapId);\n this.spatialIndex.delete(`${map.worldX},${map.worldY}`);\n return true;\n }\n\n /**\n * Find adjacent maps based on various search strategies\n * \n * Supports three search modes:\n * - PositionBox: collect maps intersecting the given box\n * - Direction: collect maps adjacent in the given direction\n * - Point: collect the map containing the given world point\n * \n * The given `map` can be any object exposing `worldX`, `worldY`, `width`, `height` properties\n * (e.g. your `RpgMap` instance or a `WorldMapInfo`).\n * \n * @param map - The source map\n * @param search - Search strategy (box, direction or point)\n * @returns Array of matching adjacent map infos\n * \n * @example\n * ```ts\n * // Point\n * world.getAdjacentMaps(currentMap, { x: 1024, y: 0 });\n * \n * // Direction\n * world.getAdjacentMaps(currentMap, Direction.Up);\n * \n * // Box\n * world.getAdjacentMaps(currentMap, { minX: 0, minY: 0, maxX: 2048, maxY: 1024 });\n * ```\n */\n getAdjacentMaps(\n map: { worldX: number; worldY: number; widthPx: number; heightPx: number },\n search:\n | { minX: number; minY: number; maxX: number; maxY: number }\n | { x: number; y: number }\n | number\n ): WorldMapInfo[] {\n const maps = Array.from(this.maps.values());\n\n // Direction lookup (number) --------------------------------------------\n if (typeof search === 'number') {\n const src = map;\n return maps.filter(m => {\n // Check if maps overlap or touch in the perpendicular direction\n // For vertical directions (Up/Down), we need horizontal overlap or touch\n // For horizontal directions (Left/Right), we need vertical overlap or touch\n const horizontallyOverlapsOrTouches =\n Math.max(src.worldX, m.worldX) <= Math.min(src.worldX + src.widthPx, m.worldX + m.widthPx);\n const verticallyOverlapsOrTouches =\n Math.max(src.worldY, m.worldY) <= Math.min(src.worldY + src.heightPx, m.worldY + m.heightPx);\n\n const marginLeftRight = src.tileWidth / 2\n const marginTopDown = src.tileHeight / 2\n \n switch (search) {\n case 0: // Up\n return verticallyOverlapsOrTouches && m.worldY + m.heightPx - marginTopDown === src.worldY;\n case 1: // Down\n return verticallyOverlapsOrTouches && m.worldY + marginTopDown === src.worldY + src.heightPx;\n case 2: // Left\n return horizontallyOverlapsOrTouches && m.worldX + m.widthPx - marginLeftRight === src.worldX;\n case 3: // Right\n return horizontallyOverlapsOrTouches && m.worldX + marginLeftRight === src.worldX + src.widthPx;\n default:\n return false;\n }\n });\n }\n\n // Point lookup ----------------------------------------------------------\n if ('x' in search && 'y' in search) {\n const found = maps.find(m =>\n search.x >= m.worldX && search.x < m.worldX + m.widthPx &&\n search.y >= m.worldY && search.y < m.worldY + m.heightPx\n );\n return found ? [found] : [];\n }\n\n // Box lookup ------------------------------------------------------------\n if ('minX' in search) {\n const { minX, minY, maxX, maxY } = search;\n return maps.filter(m => {\n const aLeft = m.worldX;\n const aRight = m.worldX + m.widthPx;\n const aTop = m.worldY;\n const aBottom = m.worldY + m.heightPx;\n const bLeft = minX;\n const bRight = maxX;\n const bTop = minY;\n const bBottom = maxY;\n const overlapX = aLeft < bRight && aRight > bLeft;\n const overlapY = aTop < bBottom && aBottom > bTop;\n return overlapX && overlapY;\n });\n }\n\n return [];\n }\n\n /**\n * Get map information by ID\n * \n * @param mapId - Map ID\n * @returns Map information or null if not found\n * \n * @example\n * ```ts\n * const mapInfo = worldMaps.getMapInfo(\"forest\");\n * ```\n */\n getMapInfo(mapId: string): WorldMapInfo | null {\n return this.maps.get(mapId) ?? null;\n }\n\n /**\n * Get all configured maps\n * \n * @returns Array of all world maps\n */\n getAllMaps(): WorldMapInfo[] {\n return Array.from(this.maps.values());\n }\n\n /**\n * Find map by world coordinates\n * \n * @param worldX - World X coordinate\n * @param worldY - World Y coordinate\n * @returns Map found or null\n */\n getMapByWorldCoordinates(worldX: number, worldY: number): WorldMapInfo | null {\n const mapId = this.spatialIndex.get(`${worldX},${worldY}`);\n return mapId ? this.maps.get(mapId) ?? null : null;\n }\n\n /**\n * Calculate absolute world position of a player\n * \n * @param map - Current map\n * @param localX - Local X position in the map\n * @param localY - Local Y position in the map\n * @returns Absolute coordinates in the world\n */\n getWorldPosition(map: WorldMapInfo, localX: number, localY: number): {x: number, y: number} {\n return {\n x: map.worldX + localX,\n y: map.worldY + localY\n };\n }\n\n /**\n * Calculate local position from world position\n * \n * @param worldX - World X position\n * @param worldY - World Y position\n * @param targetMap - Target map\n * @returns Local position in the target map\n */\n getLocalPosition(worldX: number, worldY: number, targetMap: WorldMapInfo): {x: number, y: number} {\n return {\n x: worldX - targetMap.worldX,\n y: worldY - targetMap.worldY\n };\n }\n}\n\n/**\n * Public alias for the world maps manager\n * \n * This alias is provided for API readability in map methods.\n */\nexport type RpgWorldMaps = WorldMapsManager;","export const ModulesToken = \"ModulesToken\";\n\nimport { Context, Provider, Providers } from \"@signe/di\";\nimport { Subject, Observable, from } from \"rxjs\";\nimport { mergeMap, toArray } from \"rxjs/operators\";\n\nexport enum Side {\n Server = 'server',\n Client = 'client'\n}\n\ntype ModuleSide = {\n client?: any,\n server?: any\n}\n\nexport type ModuleType = ModuleSide | [ModuleSide, {\n client?: any,\n server?: any\n}]\n\nexport function RpgModule<T>(options: T) {\n return (target) => {\n if ((options as any).hooks) {\n target.hooks = (options as any).hooks\n }\n for (let key in options) {\n target.prototype[key] = options[key]\n }\n }\n}\n\nexport class Hooks {\n /**\n * Store of all module hooks by ID\n */\n private moduleHooks: Record<string, Subject<any>> = {};\n\n /**\n * Store of all hook functions by ID\n */\n private hookFunctions: Record<string, Function[]> = {};\n\n constructor(private modules: any[], private namespace: string) {\n this.init();\n }\n\n private init() {\n for (const module of this.modules) {\n for (const type in module) {\n const hookObject = module[type];\n for (const hook in hookObject) {\n const hookFunction = hookObject[hook];\n if (hookFunction) {\n const hookId = `${this.namespace}-${type}-${hook}`;\n\n // Créer un Subject pour ce hook s'il n'existe pas déjà\n if (!this.moduleHooks[hookId]) {\n this.moduleHooks[hookId] = new Subject<any>();\n }\n\n // Initialiser le tableau de fonctions pour cet ID si nécessaire\n if (!this.hookFunctions[hookId]) {\n this.hookFunctions[hookId] = [];\n }\n\n // Ajouter la fonction au tableau des hooks pour cet ID\n // (sans l'exécuter immédiatement)\n if (!this.hookFunctions[hookId].includes(hookFunction)) {\n this.hookFunctions[hookId].push(hookFunction);\n }\n }\n }\n }\n }\n\n return this.moduleHooks;\n }\n\n /**\n * Call hooks for a specific ID, passing arguments to all subscribed hooks\n *\n * @param hookId - The unique identifier of the module hook\n * @param args - Arguments to pass to the hook functions\n * @returns An Observable that emits an array with all hook results when subscribed\n * @example\n * ```ts\n * // Call all hook functions for the ID 'my-namespace-type-hook'\n * callHooks('my-namespace-type-hook', { x: 10, y: 20 }).subscribe(results => {\n * console.log('Hook results:', results); // Array of all hook function results\n * });\n * \n * // Hook functions are only executed when you subscribe to the returned Observable\n * const observable = callHooks('my-namespace-type-hook', player);\n * // ... later ...\n * observable.subscribe(results => {\n * // Process results array\n * });\n * ```\n */\n public callHooks(hookId: string, ...args: any[]): Observable<any[]> {\n if (!this.moduleHooks[hookId]) {\n this.moduleHooks[hookId] = new Subject<any>();\n }\n\n\n // Create an Observable that will execute all hook functions when subscribed\n return new Observable<any[]>((subscriber) => {\n if (this.hookFunctions[hookId] && this.hookFunctions[hookId].length > 0) {\n // Map each hook function to an Observable that can handle both synchronous values and Promises\n const hookResults$ = from(this.hookFunctions[hookId]).pipe(\n mergeMap((hookFunction) => {\n let result;\n try {\n result = hookFunction(...args);\n return from(Promise.resolve(result));\n } catch (error) {\n subscriber.error(error);\n return [];\n }\n }),\n toArray() // Collect all results into an array\n );\n\n // Subscribe to the hook results Observable\n const subscription = hookResults$.subscribe({\n next: (results) => {\n // Emit all collected results to subscribers of this hook\n this.moduleHooks[hookId].next(results);\n subscriber.next(results);\n subscriber.complete();\n },\n error: (err) => {\n subscriber.error(err);\n }\n });\n\n // Return cleanup function\n return () => {\n subscription.unsubscribe();\n };\n } else {\n // No hook functions to execute, emit an empty array\n subscriber.next([]);\n subscriber.complete();\n return () => {};\n }\n });\n }\n}\n\n/**\n * Provide modules configuration to Angular Dependency Injection\n * Registers hook functions for later execution\n *\n * @param modules - Array of modules to provide\n * @param namespace - Namespace to prefix hook IDs\n * @returns Provider configuration for Angular DI\n * @example\n * ```ts\n * // Define modules\n * const modules = [\n * {\n * player: {\n * onMove: (player) => {\n * // Handle player movement\n * }\n * }\n * }\n * ];\n *\n * // Provide modules\n * const provider = provideModules(modules, 'game');\n * ```\n */\nexport function provideModules(modules: any[], namespace: string, transform?: (modules: any, context: Context) => any) {\n return {\n provide: ModulesToken,\n useFactory: (context: Context) => {\n modules = transform ? transform(modules, context) : modules\n return new Hooks(modules, namespace);\n },\n };\n}\n\nexport function findModules(context: Context, namespace: string) {\n let modules: any[] = []\n for (let key in context['values']) {\n if (key.endsWith('Module' + namespace)) {\n modules.push(context['values'][key].values.get('__default__'))\n }\n }\n return modules\n}\n\n/**\n * Create module providers from a token name and array of providers\n * Transforms objects with server/client properties into separate ModuleServer and ModuleClient providers\n *\n * @param tokenName - The base token name for the module\n * @param providers - Array of providers that can be regular providers or objects with server/client properties\n * @returns Flattened array of providers with transformed server/client objects\n * @example\n * ```ts\n * // Input: createModule('battle', [{ server: serverModule, client: clientModule }])\n * // Output: [\n * // { provide: 'battleModuleServer', useValue: { server: serverModule, client: clientModule }, meta: { server: true, isModule: true } },\n * // { provide: 'battleModuleClient', useValue: { server: serverModule, client: clientModule }, meta: { client: true, isModule: true } }\n * // ]\n * \n * // Regular providers are passed through unchanged\n * createModule('battle', [regularProvider, { server, client }])\n * ```\n */\nexport function createModule(tokenName: string, providers:(Provider | Provider[] | ({ server?: any, client?: any }))[]) {\n const results = providers.map(provider => {\n const results: any[] = [];\n\n if (!provider) {\n return []\n }\n \n if ('server' in provider) {\n results.push({\n provide: tokenName + 'ModuleServer',\n useValue: provider,\n meta: {\n server: true,\n isModule: true,\n }\n });\n }\n \n if ('client' in provider) {\n results.push({\n provide: tokenName + 'ModuleClient',\n useValue: provider,\n meta: {\n client: true,\n isModule: true,\n }\n });\n }\n \n // If neither server nor client properties, return the provider as-is\n if (!('server' in provider) && !('client' in provider)) {\n results.push(provider);\n }\n \n return results;\n }).flat(); // Flatten the array to handle multiple results per provider\n\n return results.flat();\n}\n\nexport function defineModule<T>(options: T) {\n return options\n}","export type Constructor<T = {}> = new (...args: any[]) => T;\n\nexport function delay(cb: () => void, ms: number = 50): void {\n setTimeout(cb, ms);\n}\n\nexport function random(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n\nexport function isBrowser(): boolean {\n return typeof window !== \"undefined\";\n}\n\nexport function isFunction(val: unknown): boolean {\n return {}.toString.call(val) === \"[object Function]\";\n}\n\nexport function isClass(func: unknown): boolean {\n return typeof func === \"function\";\n}\n\nexport function isPromise(val: unknown) {\n return isInstanceOf<Promise<unknown>>(val, Promise);\n}\n\nexport function isArray(val: unknown) {\n return isInstanceOf<Array<unknown>>(val, Array);\n}\n\nexport function isObject(val: unknown): boolean {\n return typeof val == \"object\" && val != null && !isArray(val);\n}\n\nexport function isString(val: unknown): boolean {\n return typeof val == \"string\";\n}\n\nexport function isInstanceOf<T = any>(val: unknown, _class: any) {\n return val instanceof _class;\n}\n\nexport function arrayUniq(array: any[]): any[] {\n return [...new Set(array)];\n}\n\nexport function arrayFlat(array: any[]): any[] {\n return array.reduce((acc, val) => acc.concat(val), []);\n}\n\nexport function intersection(\n [start1, end1]: [number, number],\n [start2, end2]: [number, number]\n): boolean {\n return (\n (start1 >= start2 && start1 <= end2) || (start2 >= start1 && start2 < end1)\n );\n}\n\nexport function capitalize(s: unknown): string {\n if (typeof s !== \"string\") return \"\";\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport function camelToKebab(str: string): string {\n return str.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase();\n}\n\nexport function arrayEquals(a: any[], b: any[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\n/**\n * Combines multiple mixins into one\n *\n * @param mixins - Array of mixin functions to combine\n * @returns A single mixin function that applies all mixins\n *\n * @example\n * ```ts\n * const AllMixins = combineMixins([WithStats, WithInventory, WithComponentManager]);\n * class MyClass extends AllMixins(BaseClass) {\n * // MyClass now has all capabilities from all mixins\n * }\n * ```\n */\nexport function combineMixins(\n mixins: Array<<T extends Constructor>(Base: T) => any>\n) {\n return <T extends Constructor>(Base: T) =>\n mixins.reduce((ExtendedClass, mixin) => mixin(ExtendedClass), Base);\n}\n\nexport function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {\n const baseCtorName = Object.getOwnPropertyDescriptor(\n baseCtor.prototype,\n name\n );\n if (!baseCtorName) {\n return;\n }\n Object.defineProperty(derivedCtor.prototype, name, baseCtorName);\n });\n });\n}\n\nexport function generateUID(): string {\n let firstPart: any = (Math.random() * 46656) | 0;\n let secondPart: any = (Math.random() * 46656) | 0;\n firstPart = (\"000\" + firstPart.toString(36)).slice(-3);\n secondPart = (\"000\" + secondPart.toString(36)).slice(-3);\n return firstPart + secondPart;\n}\n\nexport function createConstructor<T>(...propNames: any[]): T {\n return class {\n constructor(...propValues) {\n propNames.forEach((name, idx) => {\n this[name] = propValues[idx];\n });\n }\n } as unknown as T;\n}\n\nexport function sharedArrayBuffer() {\n let buffer;\n if (typeof SharedArrayBuffer != \"undefined\") {\n buffer = SharedArrayBuffer;\n } else {\n buffer = ArrayBuffer;\n }\n return buffer;\n}\n\nexport function toRadians(angle: number) {\n return angle * (Math.PI / 180);\n}\n\nexport function hexaToNumber(hexa: string): {\n value: number;\n alpha: number;\n} {\n let val = hexa.replace(\"#\", \"\");\n let alpha = 1;\n if (val.length === 3) {\n val = val\n .split(\"\")\n .map((v) => v + v)\n .join(\"\");\n }\n if (val.length === 8) {\n alpha = parseInt(val.substring(0, 2), 16) / 255;\n val = val.substring(2);\n }\n return {\n value: parseInt(val, 16),\n alpha,\n };\n}\n\nexport function extractId(path: string): string | null {\n const id = path.match(/([a-zA-Z0-9-_$!]+)\\.[a-z0-9]+$/i);\n if (!id) return null;\n return id[1];\n}\n\nexport function basename(path: string): string {\n return path.substring(path.lastIndexOf(\"/\") + 1);\n}\n\nexport function fps2ms(fps: number): number {\n return 1000 / fps;\n}\n\nexport function preciseNow(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nexport function round(num: number, decimals: number = 100): number {\n return Math.round(num * decimals) / decimals;\n}\n\n// https://stackoverflow.com/questions/54733539/javascript-implementation-of-lodash-set-method\nexport function set(obj, path, value, onlyPlainObject = false) {\n if (Object(obj) !== obj) return obj; // When obj is not an object\n // If not yet an array, get the keys from the string-path\n if (!Array.isArray(path)) path = path.toString().match(/[^.[\\]]+/g) || [];\n path.slice(0, -1).reduce(\n (\n a,\n c,\n i // Iterate all of them except the last one\n ) =>\n Object(a[c]) === a[c] // Does the key exist and is its value an object?\n ? // Yes: then follow that path\n a[c]\n : // No: create the key. Is the next key a potential array-index?\n (a[c] =\n Math.abs(path[i + 1]) >> 0 === +path[i + 1]\n ? onlyPlainObject\n ? {}\n : [] // Yes: assign a new array object\n : {}), // No: assign a new plain object\n obj\n )[path[path.length - 1]] = value; // Finally assign the value to the last key\n return obj; // Return the top-level object to allow chaining\n}\n\nexport function elementToPositionAbsolute(element: HTMLElement) {\n element.style.position = \"absolute\";\n element.style.top = \"0\";\n element.style.left = \"0\";\n element.style.right = \"0\";\n element.style.bottom = \"0\";\n element.style.width = \"100%\";\n element.style.height = \"100%\";\n}\n\n\nexport function mergeObjectWithMethods<T, S>(target: T, source: S): T & S {\n // Copier toutes les propriétés propres (énumérables et non-énumérables)\n const propertyNames = Object.getOwnPropertyNames(source);\n for (const name of propertyNames) {\n if (name !== 'constructor') {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n if (descriptor) {\n Object.defineProperty(target, name, descriptor);\n }\n }\n }\n \n // Configurer le prototype pour hériter des méthodes de la classe\n const sourceProto = Object.getPrototypeOf(source);\n if (sourceProto && sourceProto !== Object.prototype) {\n Object.setPrototypeOf(target, sourceProto);\n }\n \n return target as T & S;\n}\n\nexport default {\n random,\n isBrowser,\n isPromise,\n isArray,\n isObject,\n isString,\n isFunction,\n isClass,\n isInstanceOf,\n arrayUniq,\n arrayFlat,\n arrayEquals,\n intersection,\n applyMixins,\n capitalize,\n sharedArrayBuffer,\n generateUID,\n createConstructor,\n toRadians,\n extractId,\n basename,\n fps2ms,\n preciseNow,\n hexaToNumber,\n set,\n round,\n camelToKebab,\n elementToPositionAbsolute,\n mergeObjectWithMethods\n};\n"," /** \n * \n * Pre-made GUIs already exist. For example, the command `player.showText()` displays the rpg-dialog component. It is up to you to customize the component or take advantage of the `@rpgjs/default-gui` module which already contains ready-made components\n * \n * @title Prebuilt GUI\n * @enum {string}\n * \n * PrebuiltGui.Dialog | rpg-dialog\n * PrebuiltGui.MainMenu | rpg-main-menu\n * PrebuiltGui.Shop | rpg-shop\n * PrebuiltGui.Disconnect | rpg-disconnect\n * PrebuiltGui.Gameover | rpg-gameover\n * PrebuiltGui.Save | rpg-save\n * PrebuiltGui.Controls | rpg-controls\n * PrebuiltGui.Notification | rpg-notification\n * PrebuiltGui.TitleScreen | rpg-title-screen\n * @memberof PrebuiltGui\n * */\n export enum PrebuiltGui {\n Dialog = 'rpg-dialog',\n MainMenu = 'rpg-main-menu',\n Shop = 'rpg-shop',\n Disconnect = 'rpg-disconnect',\n Gameover = 'rpg-gameover',\n Save = 'rpg-save',\n Controls = 'rpg-controls',\n Notification = 'rpg-notification',\n TitleScreen = 'rpg-title-screen'\n}\n","/**\n * Perlin Noise 2D Generator\n * \n * A simple, efficient, and performant implementation of 2D Perlin noise.\n * Perlin noise generates smooth, natural-looking random values that are coherent\n * across space, making it ideal for procedural generation and smooth random movements.\n * \n * ## Features\n * - **Deterministic**: Same seed and coordinates always produce the same value\n * - **Smooth**: Values change gradually, creating natural-looking patterns\n * - **Performant**: Optimized for real-time use in movement systems\n * - **Seeded**: Optional seed for reproducible results\n * \n * ## Usage\n * ```ts\n * const noise = new PerlinNoise2D();\n * const value = noise.get(x, y); // Returns value between -1 and 1\n * \n * // With seed for deterministic results\n * const seededNoise = new PerlinNoise2D(12345);\n * ```\n * \n * @example\n * ```ts\n * // Use in movement system for smooth random directions\n * const noise = new PerlinNoise2D();\n * const time = Date.now() * 0.001;\n * const direction = Math.floor(noise.get(player.x(), player.y(), time) * 4) % 4;\n * ```\n */\nexport class PerlinNoise2D {\n private readonly permutation: number[];\n private readonly p: number[];\n\n /**\n * Creates a new Perlin noise generator\n * \n * @param seed - Optional seed for deterministic noise generation. If not provided, uses a default seed.\n * \n * @example\n * ```ts\n * const noise = new PerlinNoise2D(12345);\n * const value = noise.get(10, 20);\n * ```\n */\n constructor(seed: number = 0) {\n // Create permutation table (256 values)\n this.permutation = this.generatePermutation(seed);\n \n // Double the permutation array for easier wrapping\n this.p = [...this.permutation, ...this.permutation];\n }\n\n /**\n * Generates a permutation table based on seed\n * \n * @param seed - Seed value for permutation generation\n * @returns Array of 256 shuffled values\n */\n private generatePermutation(seed: number): number[] {\n const p: number[] = [];\n \n // Initialize with sequential values\n for (let i = 0; i < 256; i++) {\n p[i] = i;\n }\n \n // Simple seeded shuffle using linear congruential generator\n let state = seed;\n const lcg = () => {\n state = (state * 1103515245 + 12345) & 0x7fffffff;\n return state;\n };\n \n // Fisher-Yates shuffle with seeded random\n for (let i = 255; i > 0; i--) {\n const j = lcg() % (i + 1);\n [p[i], p[j]] = [p[j], p[i]];\n }\n \n return p;\n }\n\n /**\n * Fade function for smooth interpolation (ease curve)\n * \n * @param t - Value between 0 and 1\n * @returns Smoothed value between 0 and 1\n */\n private fade(t: number): number {\n return t * t * t * (t * (t * 6 - 15) + 10);\n }\n\n /**\n * Linear interpolation\n * \n * @param a - Start value\n * @param b - End value\n * @param t - Interpolation factor (0 to 1)\n * @returns Interpolated value\n */\n private lerp(a: number, b: number, t: number): number {\n return a + t * (b - a);\n }\n\n /**\n * Gradient function - generates a pseudo-random gradient vector\n * \n * @param hash - Hash value from permutation table\n * @param x - X component\n * @param y - Y component\n * @returns Dot product of gradient and position\n */\n private grad(hash: number, x: number, y: number): number {\n // Convert hash to one of 4 gradient directions\n const h = hash & 3;\n \n // Return dot product with gradient vector\n switch (h) {\n case 0: return x + y; // (1, 1)\n case 1: return -x + y; // (-1, 1)\n case 2: return x - y; // (1, -1)\n case 3: return -x - y; // (-1, -1)\n default: return 0;\n }\n }\n\n /**\n * Gets the noise value at the specified 2D coordinates\n * \n * Returns a value between approximately -1 and 1, though values near the edges\n * are less common. For practical use, you may want to clamp or normalize the result.\n * \n * @param x - X coordinate\n * @param y - Y coordinate\n * @param scale - Optional scale factor (default: 0.1). Lower values create smoother, larger patterns.\n * @returns Noise value between approximately -1 and 1\n * \n * @example\n * ```ts\n * const noise = new PerlinNoise2D();\n * const value = noise.get(10, 20); // Basic usage\n * const scaled = noise.get(10, 20, 0.05); // Smoother pattern\n * ```\n */\n get(x: number, y: number, scale: number = 0.1): number {\n // Apply scale\n x *= scale;\n y *= scale;\n\n // Find unit grid cell containing point\n const X = Math.floor(x) & 255;\n const Y = Math.floor(y) & 255;\n\n // Get relative x,y coordinates within that cell\n x -= Math.floor(x);\n y -= Math.floor(y);\n\n // Compute fade curves for x and y\n const u = this.fade(x);\n const v = this.fade(y);\n\n // Hash coordinates of the 4 square corners\n const A = this.p[X] + Y;\n const AA = this.p[A];\n const AB = this.p[A + 1];\n const B = this.p[X + 1] + Y;\n const BA = this.p[B];\n const BB = this.p[B + 1];\n\n // And add blended results from 4 corners of the square\n return this.lerp(\n this.lerp(\n this.grad(this.p[AA], x, y),\n this.grad(this.p[BA], x - 1, y),\n u\n ),\n this.lerp(\n this.grad(this.p[AB], x, y - 1),\n this.grad(this.p[BB], x - 1, y - 1),\n u\n ),\n v\n );\n }\n\n /**\n * Gets a normalized noise value between 0 and 1\n * \n * Convenience method that normalizes the noise output to a 0-1 range.\n * \n * @param x - X coordinate\n * @param y - Y coordinate\n * @param scale - Optional scale factor (default: 0.1)\n * @returns Noise value between 0 and 1\n * \n * @example\n * ```ts\n * const noise = new PerlinNoise2D();\n * const normalized = noise.getNormalized(10, 20);\n * // Returns value between 0 and 1\n * ```\n */\n getNormalized(x: number, y: number, scale: number = 0.1): number {\n return (this.get(x, y, scale) + 1) * 0.5;\n }\n\n /**\n * Gets a noise value mapped to a specific range\n * \n * Maps the noise output to a custom min-max range.\n * \n * @param x - X coordinate\n * @param y - Y coordinate\n * @param min - Minimum output value\n * @param max - Maximum output value\n * @param scale - Optional scale factor (default: 0.1)\n * @returns Noise value between min and max\n * \n * @example\n * ```ts\n * const noise = new PerlinNoise2D();\n * const direction = noise.getRange(10, 20, 0, 3); // Returns 0, 1, 2, or 3\n * ```\n */\n getRange(x: number, y: number, min: number, max: number, scale: number = 0.1): number {\n const normalized = this.getNormalized(x, y, scale);\n return min + normalized * (max - min);\n }\n\n /**\n * Gets an integer noise value in a specific range (inclusive)\n * \n * Useful for selecting discrete values like array indices or enum values.\n * \n * @param x - X coordinate\n * @param y - Y coordinate\n * @param min - Minimum integer value (inclusive)\n * @param max - Maximum integer value (inclusive)\n * @param scale - Optional scale factor (default: 0.1)\n * @returns Integer noise value between min and max (inclusive)\n * \n * @example\n * ```ts\n * const noise = new PerlinNoise2D();\n * const directionIndex = noise.getInt(10, 20, 0, 3); // Returns 0, 1, 2, or 3\n * ```\n */\n getInt(x: number, y: number, min: number, max: number, scale: number = 0.1): number {\n const value = this.getRange(x, y, min, max + 1, scale);\n return Math.floor(value);\n }\n}\n\n/**\n * Creates a shared Perlin noise instance for global use\n * \n * Useful when you want consistent noise across different parts of your application\n * without passing the instance around.\n * \n * @param seed - Optional seed for the shared instance\n * @returns Shared PerlinNoise2D instance\n * \n * @example\n * ```ts\n * const noise = getSharedPerlinNoise(12345);\n * const value = noise.get(10, 20);\n * ```\n */\nlet sharedInstance: PerlinNoise2D | null = null;\n\nexport function getSharedPerlinNoise(seed?: number): PerlinNoise2D {\n if (!sharedInstance) {\n sharedInstance = new PerlinNoise2D(seed);\n }\n return sharedInstance;\n}\n\n/**\n * Resets the shared Perlin noise instance\n * \n * Useful for testing or when you need to change the seed.\n * \n * @param seed - Optional new seed for the instance\n * \n * @example\n * ```ts\n * resetSharedPerlinNoise(12345);\n * ```\n */\nexport function resetSharedPerlinNoise(seed?: number): void {\n sharedInstance = new PerlinNoise2D(seed);\n}\n\n","export const MAXHP: string = 'maxHp'\nexport const MAXSP: string = 'maxSp'\nexport const ATK: string = 'atk'\nexport const PDEF: string = 'pdef'\nexport const SDEF: string = 'sdef'\nexport const STR: string = 'str'\nexport const AGI: string = 'agi'\nexport const INT: string = 'int'\nexport const DEX: string = 'dex'","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\n// src/inject.ts\nvar DEFAULT_INSTANCE_KEY = \"__default__\";\nfunction toTokenName(token) {\n return typeof token === \"function\" ? token.name : token;\n}\n__name(toTokenName, \"toTokenName\");\nfunction toInstanceKey(name) {\n return name ?? DEFAULT_INSTANCE_KEY;\n}\n__name(toInstanceKey, \"toInstanceKey\");\nfunction getRecord(context, token) {\n return context.get(\"inject:\" + toTokenName(token));\n}\n__name(getRecord, \"getRecord\");\nfunction ensureRecord(context, token) {\n const key = \"inject:\" + toTokenName(token);\n let record = context.get(key);\n if (!record) {\n record = {\n multi: false,\n values: /* @__PURE__ */ new Map(),\n injected: /* @__PURE__ */ new Set()\n };\n }\n context.set(key, record);\n return record;\n}\n__name(ensureRecord, \"ensureRecord\");\nfunction provide(context, token, value, options = {}) {\n const record = ensureRecord(context, token);\n const instanceKey = toInstanceKey(options.name);\n if (options.multi) {\n record.multi = true;\n }\n if (!record.multi && instanceKey !== DEFAULT_INSTANCE_KEY) {\n record.multi = true;\n }\n record.values.set(instanceKey, value);\n return value;\n}\n__name(provide, \"provide\");\nfunction isInjected(context, token, options = {}) {\n const record = getRecord(context, token);\n if (!record) {\n return false;\n }\n if (options.name) {\n return record.injected.has(toInstanceKey(options.name));\n }\n if (record.multi) {\n return record.injected.size > 0;\n }\n return record.injected.has(DEFAULT_INSTANCE_KEY);\n}\n__name(isInjected, \"isInjected\");\nfunction isProvided(context, token, options = {}) {\n const record = getRecord(context, token);\n if (!record) {\n return false;\n }\n if (options.name) {\n return record.values.has(toInstanceKey(options.name));\n }\n if (record.multi) {\n return record.values.size > 0;\n }\n return record.values.has(DEFAULT_INSTANCE_KEY);\n}\n__name(isProvided, \"isProvided\");\nfunction hasInstance(context, token, options = {}) {\n return isProvided(context, token, options);\n}\n__name(hasInstance, \"hasInstance\");\nfunction handleMissingInjection(token, options) {\n const name = toTokenName(token);\n if (options.name) {\n throw new Error(`Injection provider ${name} with name ${options.name} not found`);\n }\n throw new Error(`Injection provider ${name} not found`);\n}\n__name(handleMissingInjection, \"handleMissingInjection\");\nfunction markInjected(record, key) {\n record.injected.add(key);\n}\n__name(markInjected, \"markInjected\");\nfunction markAllInjected(record) {\n for (const key of record.values.keys()) {\n record.injected.add(key);\n }\n}\n__name(markAllInjected, \"markAllInjected\");\nfunction inject(context, token, options = {}) {\n const record = getRecord(context, token);\n if (!record) {\n if (options.optional) {\n return options.multi ? [] : void 0;\n }\n return handleMissingInjection(token, options);\n }\n if (options.name) {\n const instanceKey = toInstanceKey(options.name);\n if (!record.values.has(instanceKey)) {\n if (options.optional) {\n return void 0;\n }\n return handleMissingInjection(token, options);\n }\n const value2 = record.values.get(instanceKey);\n markInjected(record, instanceKey);\n return value2;\n }\n if (options.multi || record.multi) {\n if (record.values.size === 0) {\n if (options.optional) {\n return [];\n }\n return handleMissingInjection(token, options);\n }\n markAllInjected(record);\n return Array.from(record.values.values());\n }\n const value = record.values.get(DEFAULT_INSTANCE_KEY);\n if (value === void 0) {\n if (options.optional) {\n return void 0;\n }\n return handleMissingInjection(token, options);\n }\n markInjected(record, DEFAULT_INSTANCE_KEY);\n return value;\n}\n__name(inject, \"inject\");\nfunction override(providers, newProvider, options) {\n let { upsert = false, key } = options ?? {};\n if (!key) {\n key = typeof newProvider === \"function\" ? newProvider.name : newProvider.provide;\n }\n const flatProviders = providers.flat();\n const exists = flatProviders.some((provider) => {\n if (typeof provider === \"function\") {\n return provider.name === key;\n } else if (typeof provider === \"object\") {\n return provider.provide === key;\n }\n return false;\n });\n const mappedProviders = flatProviders.map((provider) => {\n if (typeof provider === \"function\" && provider.name === key) {\n return newProvider;\n } else if (typeof provider === \"object\" && provider.provide === key) {\n return newProvider;\n }\n return provider;\n });\n if (upsert && !exists) {\n mappedProviders.push(newProvider);\n }\n return mappedProviders;\n}\n__name(override, \"override\");\nfunction findProviders(providers, name) {\n const results = [];\n for (const provider of providers) {\n if (Array.isArray(provider)) {\n results.push(...findProviders(provider, name));\n } else if (findProvider(provider, name)) {\n results.push(provider);\n }\n }\n return results;\n}\n__name(findProviders, \"findProviders\");\nfunction findProvider(providers, name) {\n if (!Array.isArray(providers)) {\n if (typeof providers === \"object\" && \"provide\" in providers) {\n const provider = providers;\n const providerName = typeof provider.provide === \"function\" ? provider.provide.name : provider.provide;\n if (name instanceof RegExp) {\n if (name.test(providerName)) return providers;\n } else {\n if (providerName === name) return providers;\n }\n }\n return null;\n }\n for (const provider of providers) {\n if (Array.isArray(provider)) {\n const found = findProvider(provider, name);\n if (found) return found;\n continue;\n }\n if (typeof provider === \"object\" && \"provide\" in provider) {\n const providerName = typeof provider.provide === \"function\" ? provider.provide.name : provider.provide;\n if (name instanceof RegExp) {\n if (name.test(providerName)) return provider;\n } else {\n if (providerName === name) return provider;\n }\n }\n }\n return null;\n}\n__name(findProvider, \"findProvider\");\n\n// src/merge-config.ts\nfunction processProvider(mergedConfig, baseConfig, provider) {\n if (Array.isArray(provider)) {\n for (const nestedProvider of provider) {\n processProvider(mergedConfig, baseConfig, nestedProvider);\n }\n return;\n }\n const existingProvider = findProvider(baseConfig.providers, provider.provide);\n if (existingProvider) {\n mergedConfig.providers = override(mergedConfig.providers, provider);\n } else {\n mergedConfig.providers.push(provider);\n }\n}\n__name(processProvider, \"processProvider\");\nfunction mergeConfig(baseConfig, config) {\n const mergedConfig = {\n ...baseConfig,\n ...config,\n providers: [\n ...baseConfig.providers\n ]\n // Start with a copy of base providers\n };\n for (const provider of config.providers) {\n processProvider(mergedConfig, baseConfig, provider);\n }\n return mergedConfig;\n}\n__name(mergeConfig, \"mergeConfig\");\n\n// src/provider.ts\nfunction extractProvideOptions(source) {\n if (!source) {\n return void 0;\n }\n const { multi, name } = source;\n if (multi === void 0 && name === void 0) {\n return void 0;\n }\n return {\n multi,\n name\n };\n}\n__name(extractProvideOptions, \"extractProvideOptions\");\nfunction getDeps(provider) {\n if (typeof provider === \"function\") {\n return provider.deps ?? [];\n }\n return provider.deps ?? [];\n}\n__name(getDeps, \"getDeps\");\nfunction sortProviders(providers) {\n const tokenName = /* @__PURE__ */ __name((t) => typeof t === \"function\" ? t.name : t, \"tokenName\");\n const map = /* @__PURE__ */ new Map();\n for (const p of providers) {\n const token = tokenName(typeof p === \"function\" ? p : p.provide);\n const list = map.get(token);\n if (list) {\n list.push(p);\n } else {\n map.set(token, [\n p\n ]);\n }\n }\n const result = [];\n const visited = /* @__PURE__ */ new Set();\n const stack = /* @__PURE__ */ new Set();\n const visit = /* @__PURE__ */ __name((token) => {\n const name = tokenName(token);\n if (visited.has(name)) return;\n if (stack.has(name)) {\n throw new Error(`Circular dependency detected for provider ${name}`);\n }\n stack.add(name);\n const providersForToken = map.get(name);\n if (providersForToken) {\n for (const provider of providersForToken) {\n for (const dep of getDeps(provider)) {\n visit(dep);\n }\n result.push(provider);\n }\n visited.add(name);\n }\n stack.delete(name);\n }, \"visit\");\n for (const p of providers) {\n const token = typeof p === \"function\" ? p : p.provide;\n visit(token);\n }\n return result;\n}\n__name(sortProviders, \"sortProviders\");\nasync function injector(context, providers) {\n providers = providers.flat();\n providers = sortProviders(providers);\n for (const provider of providers) {\n let token;\n let instance;\n let options;\n if (typeof provider === \"function\") {\n token = provider;\n instance = new provider(context);\n const diOptions = extractProvideOptions(provider.diOptions ?? provider.di);\n options = diOptions;\n } else {\n token = provider.provide;\n options = extractProvideOptions(provider);\n const provideUserClass = provider.useClass;\n const isClass = typeof provideUserClass === \"function\";\n if (isClass) {\n instance = new provideUserClass(context);\n } else if (\"useValue\" in provider) {\n instance = provider.useValue;\n } else if (\"useFactory\" in provider) {\n instance = provider.useFactory?.(context);\n if (instance instanceof Promise) {\n instance = await instance;\n }\n } else if (\"useExisting\" in provider) {\n instance = inject(context, provider.useExisting);\n }\n }\n provide(context, token, instance, options);\n }\n}\n__name(injector, \"injector\");\n\n// src/context.ts\nvar Context = class {\n static {\n __name(this, \"Context\");\n }\n /** Internal storage for injected values */\n values = {};\n /**\n * Sets a value in the context\n * @param key - Unique identifier for the value\n * @param value - Value to store\n */\n set(key, value) {\n this.values[key] = value;\n }\n /**\n * Retrieves a value from the context\n * @param key - Unique identifier for the value\n * @returns The stored value or undefined if not found\n */\n get(key) {\n return this.values[key];\n }\n};\nexport {\n Context,\n findProvider,\n findProviders,\n hasInstance,\n inject,\n injector,\n isInjected,\n isProvided,\n mergeConfig,\n override,\n provide\n};\n//# sourceMappingURL=index.js.map","import { Context, inject as injector } from \"@signe/di\";\n\nexport let context: Context | null = null\n\nexport function inject<T>(service: (new (...args: any[]) => T) | string, _context?: Context): T {\n const c = _context ?? context\n if (!c) throw new Error(\"Context is not set. use setInject() to set the context\");\n return injector(c, service);\n}\n\nexport function setInject(_context: Context) {\n context = _context;\n}\n\nexport function clearInject() {\n context = null\n}","import { Context } from \"@signe/di\";\n\nexport const context = new Context();\ncontext['side'] = 'server'","import type { RpgTransportServer } from \"./types\";\n\ninterface ResolveMapOptions {\n host?: string;\n headers?: Headers;\n mapUpdateToken?: string;\n tiledBasePaths?: string[];\n}\n\nexport const MAP_UPDATE_TOKEN_HEADER = \"x-rpgjs-map-update-token\";\nexport const MAP_UPDATE_TOKEN_ENV = \"RPGJS_MAP_UPDATE_TOKEN\";\n\ntype RuntimeProcess = {\n cwd?: () => string;\n env?: Record<string, string | undefined>;\n};\n\nfunction getRuntimeProcess(): RuntimeProcess | undefined {\n return (globalThis as { process?: RuntimeProcess }).process;\n}\n\nfunction readEnvVariable(name: string): string | undefined {\n const value = getRuntimeProcess()?.env?.[name];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction getWorkingDirectory(): string | undefined {\n const cwd = getRuntimeProcess()?.cwd;\n if (typeof cwd !== \"function\") {\n return undefined;\n }\n\n try {\n return cwd();\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeRoomMapId(roomId: string): string {\n return roomId.startsWith(\"map-\") ? roomId.slice(4) : roomId;\n}\n\nfunction toBasePathPrefix(basePath: string): string {\n const trimmed = basePath.trim();\n if (!trimmed) {\n return \"\";\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction extractFileLikeMapDefinition(maps: any[], mapId: string): any | null {\n for (const mapDef of maps) {\n if (typeof mapDef === \"object\" && mapDef) {\n const candidateId = typeof mapDef.id === \"string\" ? mapDef.id.replace(/^map-/, \"\") : \"\";\n if (candidateId === mapId) {\n return mapDef;\n }\n continue;\n }\n\n if (typeof mapDef === \"string\") {\n const fileName = mapDef.split(\"/\").pop()?.replace(/\\.tmx$/i, \"\");\n if (fileName === mapId) {\n return { id: mapId, file: mapDef };\n }\n }\n }\n\n return null;\n}\n\nasync function fetchTextByUrl(url: string): Promise<string | null> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n return null;\n }\n return await response.text();\n } catch {\n return null;\n }\n}\n\nasync function readTextByFilePath(pathLike: string): Promise<string | null> {\n try {\n const { readFile } = await import(\"node:fs/promises\");\n const { isAbsolute, join } = await import(\"node:path\");\n\n const cwd = getWorkingDirectory();\n const candidates = isAbsolute(pathLike) || !cwd ? [pathLike] : [pathLike, join(cwd, pathLike)];\n\n for (const candidate of candidates) {\n try {\n return await readFile(candidate, \"utf8\");\n } catch {\n continue;\n }\n }\n } catch {\n return null;\n }\n\n return null;\n}\n\nfunction getTiledBasePaths(paths?: string[]): string[] {\n const values = [\n ...(paths || []),\n readEnvVariable(\"RPGJS_TILED_BASE_PATH\"),\n \"map\",\n \"data\",\n \"assets/data\",\n \"assets/map\",\n ].filter((value): value is string => !!value);\n\n return Array.from(new Set(values));\n}\n\nexport function resolveMapUpdateToken(explicitToken?: string): string {\n return explicitToken ?? readEnvVariable(MAP_UPDATE_TOKEN_ENV) ?? \"\";\n}\n\nexport function createMapUpdateHeaders(\n token?: string,\n init?: HeadersInit,\n): Headers {\n const headers = new Headers(init);\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n const resolvedToken = resolveMapUpdateToken(token);\n if (resolvedToken) {\n headers.set(MAP_UPDATE_TOKEN_HEADER, resolvedToken);\n }\n return headers;\n}\n\nexport function readMapUpdateToken(headers: Headers): string {\n const directToken = headers.get(MAP_UPDATE_TOKEN_HEADER);\n if (directToken) {\n return directToken;\n }\n\n const authorization = headers.get(\"authorization\");\n if (!authorization) {\n return \"\";\n }\n\n const [scheme, value] = authorization.split(/\\s+/, 2);\n if (scheme?.toLowerCase() !== \"bearer\" || !value) {\n return \"\";\n }\n\n return value.trim();\n}\n\nexport function isMapUpdateAuthorized(headers: Headers, expectedToken?: string): boolean {\n const requiredToken = resolveMapUpdateToken(expectedToken);\n if (!requiredToken) {\n return true;\n }\n return readMapUpdateToken(headers) === requiredToken;\n}\n\nasync function resolveMapDocument(\n mapId: string,\n mapDefinition: any,\n options: ResolveMapOptions,\n): Promise<{ xml: string; sourceUrl?: string }> {\n if (typeof mapDefinition?.data === \"string\" && mapDefinition.data.includes(\"<map\")) {\n return { xml: mapDefinition.data };\n }\n\n if (typeof mapDefinition?.file === \"string\") {\n const file = mapDefinition.file.trim();\n if (file.includes(\"<map\")) {\n return { xml: file };\n }\n if (/^https?:\\/\\//i.test(file)) {\n const xml = await fetchTextByUrl(file);\n if (xml) {\n return { xml, sourceUrl: file };\n }\n }\n if (file.startsWith(\"/\") && options.host) {\n const sourceUrl = `http://${options.host}${file}`;\n const xml = await fetchTextByUrl(sourceUrl);\n if (xml) {\n return { xml, sourceUrl };\n }\n }\n const xmlFromFile = await readTextByFilePath(file);\n if (xmlFromFile) {\n return { xml: xmlFromFile };\n }\n }\n\n if (options.host) {\n for (const basePath of getTiledBasePaths(options.tiledBasePaths)) {\n const prefix = toBasePathPrefix(basePath);\n const sourceUrl = `http://${options.host}${prefix}/${mapId}.tmx`;\n const xml = await fetchTextByUrl(sourceUrl);\n if (xml) {\n return { xml, sourceUrl };\n }\n }\n }\n\n return { xml: \"\" };\n}\n\nexport async function enrichMapWithParsedTiledData(payload: any, options: ResolveMapOptions = {}): Promise<void> {\n if (payload?.parsedMap || typeof payload?.id !== \"string\") {\n return;\n }\n\n const maps = Array.isArray(payload.__maps) ? payload.__maps : [];\n const mapDefinition = extractFileLikeMapDefinition(maps, payload.id);\n const mapDoc = await resolveMapDocument(payload.id, mapDefinition, options);\n if (!mapDoc.xml) {\n return;\n }\n\n try {\n const tiledModuleName = \"@canvasengine/tiled\";\n const tiledModule = await import(/* @vite-ignore */ tiledModuleName);\n const TiledParser = tiledModule?.TiledParser;\n if (!TiledParser) {\n return;\n }\n\n const mapParser = new TiledParser(mapDoc.xml);\n const parsedMap = mapParser.parseMap();\n const tilesets = Array.isArray(parsedMap?.tilesets) ? parsedMap.tilesets : [];\n const mergedTilesets: any[] = [];\n\n for (const tileset of tilesets) {\n if (!tileset?.source) {\n mergedTilesets.push(tileset);\n continue;\n }\n\n let tilesetUrl: string | undefined;\n if (mapDoc.sourceUrl) {\n try {\n tilesetUrl = new URL(tileset.source, mapDoc.sourceUrl).toString();\n } catch {\n tilesetUrl = undefined;\n }\n } else if (options.host) {\n const prefix = toBasePathPrefix(getTiledBasePaths(options.tiledBasePaths)[0] || \"map\");\n const candidatePath = tileset.source.startsWith(\"/\")\n ? tileset.source\n : `${prefix}/${tileset.source}`.replace(/\\/{2,}/g, \"/\");\n tilesetUrl = `http://${options.host}${candidatePath.startsWith(\"/\") ? candidatePath : `/${candidatePath}`}`;\n }\n\n const tilesetRaw = tilesetUrl\n ? await fetchTextByUrl(tilesetUrl)\n : await readTextByFilePath(tileset.source);\n\n if (!tilesetRaw) {\n mergedTilesets.push(tileset);\n continue;\n }\n\n try {\n const tilesetParser = new TiledParser(tilesetRaw);\n const parsedTileset = tilesetParser.parseTileset();\n mergedTilesets.push({\n ...tileset,\n ...parsedTileset,\n });\n } catch {\n mergedTilesets.push(tileset);\n }\n }\n\n parsedMap.tilesets = mergedTilesets;\n payload.data = mapDoc.xml;\n payload.parsedMap = parsedMap;\n\n if (typeof parsedMap?.width === \"number\" && typeof parsedMap?.tilewidth === \"number\") {\n payload.width = parsedMap.width * parsedMap.tilewidth;\n }\n if (typeof parsedMap?.height === \"number\" && typeof parsedMap?.tileheight === \"number\") {\n payload.height = parsedMap.height * parsedMap.tileheight;\n }\n } catch {\n return;\n }\n}\n\nexport async function updateMap(roomId: string, rpgServer: RpgTransportServer, options: ResolveMapOptions = {}): Promise<void> {\n if (!roomId.startsWith(\"map-\")) {\n return;\n }\n\n try {\n const mapId = normalizeRoomMapId(roomId);\n const serverMaps = Array.isArray(rpgServer.maps) ? rpgServer.maps : [];\n const defaultMapPayload: any = {\n id: mapId,\n width: 0,\n height: 0,\n events: [],\n __maps: serverMaps,\n };\n\n await enrichMapWithParsedTiledData(defaultMapPayload, options);\n delete defaultMapPayload.__maps;\n\n const headers = createMapUpdateHeaders(options.mapUpdateToken, options.headers);\n\n await rpgServer.onRequest?.({\n url: `http://localhost/parties/main/${roomId}/map/update`,\n method: \"POST\",\n headers,\n json: async () => defaultMapPayload,\n text: async () => JSON.stringify(defaultMapPayload),\n });\n\n console.log(`Initialized map for room ${roomId} via POST /map/update`);\n } catch (error) {\n console.warn(`Failed initializing map for room ${roomId}:`, error);\n }\n}\n","import { findModules, provideModules } from \"@rpgjs/common\";\nimport { FactoryProvider } from \"@signe/di\";\nimport { RpgServerEngine } from \"./RpgServerEngine\";\nimport { RpgMap } from \"./rooms/map\";\nimport { RpgPlayer } from \"./Player/Player\";\nimport { RpgServer } from \"./RpgServer\";\n\n/**\n * Type for server modules that can be either:\n * - An object implementing RpgServer interface\n * - A class decorated with @RpgModule decorator\n */\nexport type RpgServerModule = RpgServer | (new () => any);\n\n/**\n * Provides server modules configuration to Angular Dependency Injection\n * \n * This function accepts an array of server modules that can be either:\n * - Objects implementing the RpgServer interface\n * - Classes decorated with the @RpgModule decorator (which will be instantiated)\n * \n * @param modules - Array of server modules (objects or classes)\n * @returns FactoryProvider configuration for Angular DI\n * @example\n * ```ts\n * // Using an object\n * provideServerModules([\n * {\n * player: {\n * onConnected(player) {\n * console.log('Player connected')\n * }\n * }\n * }\n * ])\n * \n * // Using a decorated class\n * @RpgModule<RpgServer>({\n * engine: {\n * onStart(server) {\n * console.log('Server started')\n * }\n * }\n * })\n * class MyServerModule {}\n * \n * provideServerModules([MyServerModule])\n * ```\n */\nexport function provideServerModules(modules: RpgServerModule[]): FactoryProvider {\n return provideModules(modules, \"server\", (modules, context) => {\n const mainModuleServer = findModules(context, 'Server')\n modules = [...mainModuleServer, ...modules]\n modules = modules.map((module) => {\n // If module is a class (constructor function), instantiate it\n // The RpgModule decorator adds properties to the prototype, which will be accessible via the instance\n if (typeof module === 'function') {\n const instance = new module() as any;\n // Copy all enumerable properties (including from prototype) to a plain object\n const moduleObj: any = {};\n for (const key in instance) {\n moduleObj[key] = instance[key];\n }\n module = moduleObj;\n }\n if ('server' in module) {\n module = module.server as any;\n }\n if (module.player?.props) {\n module = {\n ...module,\n playerProps: {\n load: (player: RpgPlayer) => {\n player.setSync(module.player.props)\n },\n }\n };\n }\n if (module.maps && Array.isArray(module.maps)) {\n const maps = [...module.maps];\n module = {\n ...module,\n maps: {\n load: (engine: RpgMap) => {\n maps.forEach((map) => {\n // If map is a class (constructor function), extract properties from class and prototype\n // Otherwise, use the object directly\n let mapInstance: any;\n if (typeof map === 'function') {\n // Extract properties from the class (static properties set by @MapData decorator)\n // and from the prototype (instance properties like _events)\n // The decorator sets properties on both the class and prototype, so we check both\n const MapClass = map as any;\n mapInstance = {\n id: MapClass.prototype?.id ?? MapClass.id,\n file: MapClass.prototype?.file ?? MapClass.file,\n type: MapClass.type,\n name: MapClass.prototype?.name,\n sounds: MapClass.prototype?.sounds,\n weather: MapClass.prototype?.weather,\n lowMemory: MapClass.prototype?.lowMemory,\n stopAllSoundsBeforeJoin: MapClass.prototype?.stopAllSoundsBeforeJoin,\n events: MapClass.prototype?._events,\n syncSchema: MapClass.prototype?.$schema,\n onLoad: MapClass.prototype?.onLoad,\n onJoin: MapClass.prototype?.onJoin,\n onLeave: MapClass.prototype?.onLeave,\n };\n } else {\n mapInstance = map;\n }\n engine.maps.push(mapInstance);\n });\n },\n }\n };\n }\n if (module.worldMaps && Array.isArray(module.worldMaps)) {\n const worldMaps = [...module.worldMaps];\n module = {\n ...module,\n worldMaps: {\n load: (engine: RpgMap) => {\n worldMaps.forEach((worldMap) => {\n engine.createDynamicWorldMaps(worldMap)\n });\n },\n }\n };\n }\n if (module.database) {\n const database = module.database;\n module = {\n ...module,\n databaseHooks: {\n load: async (engine: RpgMap) => {\n const data = typeof database === 'function'\n ? await database(engine)\n : database;\n if (!data || typeof data !== 'object') {\n return;\n }\n for (const key in data) {\n engine.addInDatabase(key, data[key]);\n }\n },\n }\n };\n }\n return module;\n })\n return modules\n });\n}\n \n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30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