Skip to content

Commit

Permalink
feat: inject function
Browse files Browse the repository at this point in the history
  • Loading branch information
RSamaium committed Nov 30, 2023
1 parent 3753c6a commit 902e62f
Show file tree
Hide file tree
Showing 21 changed files with 112 additions and 69 deletions.
4 changes: 3 additions & 1 deletion packages/client/src/Effects/TransitionScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ import { RpgClientEngine } from "../RpgClientEngine";
import { FrameOptions } from "../Sprite/Spritesheet";
import { Timeline } from "./Timeline";
import { Container } from "pixi.js"
import { inject } from "@rpgjs/common";

export class TransitionScene {
private frameIndex: number = 0
private animations: FrameOptions[][] = []
private updateSubscription: Subscription
private complete: Function = () => {}
private clientEngine: RpgClientEngine = inject(RpgClientEngine)

constructor(private clientEngine: RpgClientEngine, private container: Container) { }
constructor(private container: Container) { }

addFadeIn() {
return this.addFading(1, 0)
Expand Down
10 changes: 5 additions & 5 deletions packages/client/src/Gui/Gui.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RpgCommonPlayer, Utils } from '@rpgjs/common'
import { RpgCommonPlayer, Utils, inject } from '@rpgjs/common'
import { RpgSound } from '../Sound/RpgSound'
import { RpgClientEngine, RpgResource } from '../index'
import { RpgRenderer } from '../Renderer'
Expand Down Expand Up @@ -36,10 +36,10 @@ export class Gui {
public currentScene: Scene | null = null
private librariesInstances: any[] = []

async _initialize(clientEngine: RpgClientEngine, guiEl: HTMLDivElement) {
this.clientEngine = clientEngine
this.renderer = clientEngine.renderer
this.gameEngine = clientEngine.gameEngine
async _initialize(guiEl: HTMLDivElement) {
this.clientEngine = inject(RpgClientEngine)
this.renderer = inject(RpgRenderer)
this.gameEngine = inject(GameEngineClient)
const { gui } = this.renderer.options

for (let ui of gui) {
Expand Down
8 changes: 5 additions & 3 deletions packages/client/src/KeyboardControls.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DefaultInput, Direction, Input, Utils } from '@rpgjs/common'
import { DefaultInput, Direction, Input, Utils, inject } from '@rpgjs/common'
import { ControlOptions, Controls } from '@rpgjs/types';
import { RpgClientEngine } from './RpgClientEngine';

Expand Down Expand Up @@ -191,6 +191,8 @@ const inverseKeyCodeTable = inverse(keyCodeTable)
type BoundKey = { actionName: string, options: ControlOptions, parameters?: any }

export class KeyboardControls {
private clientEngine: RpgClientEngine = inject(RpgClientEngine)

private keyState: {
[keyName: string]: {
isDown: boolean,
Expand All @@ -204,8 +206,8 @@ export class KeyboardControls {
private lastKeyPressed: number | null = null
private _controlsOptions: Controls = {}

constructor(private clientEngine: RpgClientEngine) {
const { globalConfig } = clientEngine
constructor() {
const { globalConfig } = this.clientEngine
this.setupListeners();
this.setInputs({
...DefaultInput,
Expand Down
16 changes: 9 additions & 7 deletions packages/client/src/Renderer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RpgPlugin, HookClient, Utils } from '@rpgjs/common'
import { RpgPlugin, HookClient, Utils, inject } from '@rpgjs/common'
import { SceneMap } from './Scene/Map'
import { Scene } from './Scene/Scene'
import { Scene as PresetScene } from './Presets/Scene'
Expand All @@ -23,6 +23,9 @@ enum ContainerName {
}

export class RpgRenderer {
private clientEngine: RpgClientEngine = inject(RpgClientEngine)
private gameEngine: GameEngineClient = inject(GameEngineClient)

public vm: ComponentPublicInstance
public app: App
public readonly stage: Container = new Container()
Expand All @@ -38,7 +41,6 @@ export class RpgRenderer {
private _height: number = 400
private canvasEl: HTMLElement
private selector: HTMLElement
private gameEngine: GameEngineClient = this.clientEngine.gameEngine
private loadingScene = {
transitionIn: new Subject(),
transitionOut: new Subject()
Expand All @@ -47,7 +49,7 @@ export class RpgRenderer {
private prevObjectScene: any = {}
public transitionMode: TransitionMode = TransitionMode.Fading

constructor(private clientEngine: RpgClientEngine) {
constructor() {
this.clientEngine.tick.subscribe(({ timestamp, deltaRatio, frame, deltaTime }) => {
this.draw(timestamp, deltaTime, deltaRatio, frame)
})
Expand Down Expand Up @@ -135,7 +137,7 @@ export class RpgRenderer {
this.fadeContainer.visible = false
this.fadeContainer.alpha = 0

await RpgGui._initialize(this.clientEngine, this.guiEl)
await RpgGui._initialize(this.guiEl)

this.resize()
}
Expand Down Expand Up @@ -205,7 +207,7 @@ export class RpgRenderer {
this.loadingScene.transitionOut.complete()
}
if (this.transitionMode == TransitionMode.Fading) {
new TransitionScene(this.clientEngine, this.fadeContainer)
new TransitionScene(this.fadeContainer)
.addFadeOut()
.onComplete(finish)
.start()
Expand All @@ -232,7 +234,7 @@ export class RpgRenderer {
switch (name) {
case PresetScene.Map:
const sceneClass = scenes[PresetScene.Map] || SceneMap
this.scene = new sceneClass(this.gameEngine, this.renderer, {
this.scene = new sceneClass(this.renderer, {
screenWidth: this.renderer.screen.width,
screenHeight: this.renderer.screen.height,
drawMap: this.options.drawMap
Expand All @@ -248,7 +250,7 @@ export class RpgRenderer {
RpgPlugin.emit(HookClient.AfterSceneLoading, this.scene)
}
if (this.transitionMode == TransitionMode.Fading) {
new TransitionScene(this.clientEngine, this.fadeContainer)
new TransitionScene(this.fadeContainer)
.addFadeIn()
.onComplete(finish)
.start()
Expand Down
13 changes: 10 additions & 3 deletions packages/client/src/RpgClientEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
RpgCommonMap,
Scheduler,
Control,
inject,
} from '@rpgjs/common'
import { RpgSound } from './Sound/RpgSound'
import { SceneMap } from './Scene/Map'
Expand Down Expand Up @@ -48,6 +49,7 @@ export class RpgClientEngine {
*
* @prop {RpgRenderer} [renderer]
* @readonly
* @deprecated Use `inject(RpgRenderer)` instead. Will be removed in v5
* @memberof RpgClientEngine
* */
public renderer: RpgRenderer
Expand All @@ -74,6 +76,7 @@ export class RpgClientEngine {
* Get the class managing the keyboard
*
* @prop {KeyboardControls} [controls]
* @deprecated Use `inject(KeyboardControls)` instead. Will be removed in v5
* @readonly
* @memberof RpgClientEngine
* */
Expand Down Expand Up @@ -107,6 +110,10 @@ export class RpgClientEngine {
private serverFps: number = 60
private scheduler: Scheduler = new Scheduler()
private _serverUrl: string = ''
/**
* * @deprecated Use `inject(GameEngineClient)` instead. Will be removed in v5
*/
public gameEngine = inject(GameEngineClient)

/**
* Read objects synchronized with the server
Expand All @@ -124,15 +131,15 @@ export class RpgClientEngine {

envs?: object = {}

constructor(public gameEngine: GameEngineClient, private options) {
constructor(private options) {
this.envs = options.envs || {}
this.tick.subscribe(({ timestamp, deltaTime }) => {
if (timestamp != -1) this.step(timestamp, deltaTime)
})
}

private async _init() {
this.renderer = new RpgRenderer(this)
this.renderer = inject(RpgRenderer)

const pluginLoadRessource = async (hookName: string, type: string) => {
const resource = this.options[type] || []
Expand Down Expand Up @@ -180,7 +187,7 @@ export class RpgClientEngine {
}
}

this.controls = new KeyboardControls(this)
this.controls = inject(KeyboardControls)
}

private addResource(resourceClass, cb) {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/Scene/Map.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { RpgCommonMap, RpgPlugin, HookClient, RpgShape, Utils, RpgCommonPlayer } from '@rpgjs/common'
import { RpgCommonMap, RpgPlugin, HookClient, RpgShape, Utils, RpgCommonPlayer, inject } from '@rpgjs/common'
import TileMap from '../Tilemap'
import * as _PixiViewport from 'pixi-viewport'
import { type Viewport } from 'pixi-viewport'
import { Scene, SceneObservableData, SceneSpriteLogic } from './Scene'
import { spritesheets } from '../Sprite/Spritesheets'
import { RpgSound } from '../Sound/RpgSound'
import { GameEngineClient } from '../GameEngine'
import { TiledLayerType, TiledMap } from '@rpgjs/tiled'
import { RpgComponent } from '../Components/Component'
import { CameraOptions } from '@rpgjs/types'
import { type CameraOptions } from '@rpgjs/types'
import { Assets, Container, Point, IRenderer, DisplayObjectEvents, utils, FederatedPointerEvent } from 'pixi.js'
import { EventLayer } from './EventLayer'

Expand Down Expand Up @@ -53,10 +52,9 @@ export class SceneMap extends Scene {
shapes = {}

constructor(
public game: GameEngineClient,
private renderer: IRenderer,
private options: { screenWidth?: number, screenHeight?: number, drawMap?: boolean } = {}) {
super(game)
super()
if (options.drawMap === undefined) this.options.drawMap = true
this.onInit()
}
Expand Down Expand Up @@ -97,7 +95,7 @@ export class SceneMap extends Scene {

RpgCommonMap.bufferClient.set(obj.id, this.gameMap)

this.tilemap = new TileMap(this.gameMap.getData(), this.game.renderer)
this.tilemap = new TileMap(this.gameMap.getData())

// TODO: Remove this
Assets.reset()
Expand Down
12 changes: 8 additions & 4 deletions packages/client/src/Scene/Scene.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RpgPlugin, HookClient, DefaultInput } from '@rpgjs/common'
import { RpgPlugin, HookClient, DefaultInput, inject } from '@rpgjs/common'
import { KeyboardControls } from '../KeyboardControls'
import RpgSprite from '../Sprite/Character'
import { Animation } from '../Effects/Animation'
Expand Down Expand Up @@ -29,14 +29,19 @@ export abstract class Scene {
protected objects: Map<string, RpgComponent> = new Map()
protected animationLayer: Container = new Container()

private controls: KeyboardControls
private controls: KeyboardControls = inject(KeyboardControls)
private animations: Animation[] = []

private _data: BehaviorSubject<SceneObservableData> = new BehaviorSubject({
data: {},
partial: {}
})

/**
* @deprecated Use `inject(GameEngineClient)` instead. Will be removed in v5
*/
public game: GameEngineClient = inject(GameEngineClient)

/**
* Listen to the movement of objects on stage
*
Expand All @@ -63,9 +68,8 @@ export abstract class Scene {
[key: string]: any
}> = new Subject()

constructor(public game: GameEngineClient) {
constructor() {
const { globalConfig } = this.game.clientEngine
this.controls = this.game.clientEngine.controls
const mergeInputs = {
...DefaultInput,
...(globalConfig.inputs || {})
Expand Down
6 changes: 3 additions & 3 deletions packages/client/src/Tilemap/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Utils } from '@rpgjs/common'
import { Utils, inject } from '@rpgjs/common'
import ImageLayer from './ImageLayer'
import TileLayer from './TileLayer'
import TileSet from './TileSet'
Expand All @@ -25,9 +25,9 @@ export default class TileMap extends Container {
} = {}
private tilesLayer: Container = new Container()
private frameTile: number = 0
private renderer: RpgRenderer = inject(RpgRenderer)


constructor(private data: MapInfo, private renderer: RpgRenderer) {
constructor(private data: MapInfo) {
super()
this.x = 0
this.y = 0
Expand Down
6 changes: 2 additions & 4 deletions packages/client/src/clientEntryPoint.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HookClient, loadModules, ModuleType } from '@rpgjs/common'
import { HookClient, inject, loadModules, ModuleType } from '@rpgjs/common'
import { GameEngineClient } from './GameEngine'
import { RpgClientEngine } from './RpgClientEngine'

Expand Down Expand Up @@ -142,7 +142,5 @@ export default (modules: ModuleType[], options: RpgClientEntryPointOptions): Rpg
}
})

const gameEngine = new GameEngineClient()
const clientEngine = new RpgClientEngine(gameEngine, options)
return clientEngine
return inject(RpgClientEngine, [options])
}
4 changes: 3 additions & 1 deletion packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ export { SceneMap as RpgSceneMap } from './Scene/Map'
export { RpgGui } from './Gui/Gui';
export { Timeline, Ease } from './Effects/Timeline';
export { RpgComponent, RpgComponent as RpgSprite } from './Components/Component'
export { KeyboardControls } from './KeyboardControls'
export { World, room } from 'simple-room-client'

import { spritesheets } from './Sprite/Spritesheets'
import { sounds } from './Sound/Sounds'
export const RpgResource = {
spritesheets,
sounds
}
}
export { inject } from '@rpgjs/common'
3 changes: 1 addition & 2 deletions packages/common/src/AbstractObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,11 @@ export class AbstractObject {
// notifier for destroy
_destroy$: Subject<void> = new Subject()


static get ACTIONS() {
return ACTIONS
}

constructor(private gameEngine: RpgCommonGame, public playerId: string) {
constructor(public gameEngine: RpgCommonGame, public playerId: string) {
this._hitboxPos = new SAT.Vector(0, 0)
this.setHitbox(this.width, this.height)
this.position = { x: 0, y: 0, z: 0 }
Expand Down
7 changes: 6 additions & 1 deletion packages/common/src/Game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ export class RpgCommonGame extends EventEmitter {
let event
if (!playerId) playerId = generateUID()
if (isClass(_class)) {
event = new _class(this, playerId)
if (this.side == GameSide.Client) {
event = new _class(this, playerId)
}
else {
event = new _class(playerId)
}
}
else {
event = _class
Expand Down
15 changes: 15 additions & 0 deletions packages/common/src/Inject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const cacheInstances: { [key: string]: any } = {};

export function inject<T>(service: new (...args: any[]) => T, args: any[] = []): T {
if (cacheInstances[service.name]) {
return cacheInstances[service.name] as T;
}
const instance = new service(...args);
if (instance['initialize']) instance['initialize'](...args)
cacheInstances[service.name] = instance;
return instance;
}

export interface InjectInit {
initialize(...args: any[]): any
}
3 changes: 2 additions & 1 deletion packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ export { RpgCommonWorldMaps } from './WorldMaps'
export { Vector2d } from './Vector2d'
export { Direction } from '@rpgjs/types'
export { transitionColor } from './Color'
export { DefaultInput } from './DefaultInput'
export { DefaultInput } from './DefaultInput'
export { inject, InjectInit } from './Inject'
4 changes: 1 addition & 3 deletions packages/sample2/main/scene-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { RpgSceneMapHooks, RpgSceneMap, RpgGui } from '@rpgjs/client'

const sceneMap: RpgSceneMapHooks = {
onAfterLoading(scene) {
scene.on('click', (scene) => {
console.log(scene)
})

},
}

Expand Down
1 change: 0 additions & 1 deletion packages/server/src/Game/Map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,6 @@ export class RpgMap extends RpgCommonMap {
const ev = this.game.addEvent<RpgEvent>(event)
const _shape = shape || this.getEventShape(ev.name)
ev.map = this.id
ev.server = this._server
ev.width = event.width || this.tileWidth
ev.height = event.height || this.tileHeight
if (_shape && _shape.properties) ev.properties = _shape.properties
Expand Down
Loading

0 comments on commit 902e62f

Please sign in to comment.