├── README.md ├── .gitignore ├── example ├── assets │ ├── 1000.png │ └── test.wav ├── tsconfig.json ├── src │ ├── declarations.d.ts │ ├── DrawingScene.ts │ ├── UIScene.ts │ ├── index.ts │ ├── index.html │ ├── widgets │ │ ├── AnimationWidget.ts │ │ └── PathOnGridWidget.ts │ ├── DrawingEntity.ts │ └── scenes │ │ └── GridScene.ts ├── package.json └── dist │ ├── index.html │ ├── index.js │ ├── index.js.map │ └── src.8e541c7a.js ├── src ├── assetLoader │ ├── assetTypes │ │ ├── index.ts │ │ ├── ImageAsset.ts │ │ └── SoundAsset.ts │ ├── index.ts │ ├── AssetDefinition.ts │ ├── Asset.ts │ └── AssetLoader.ts ├── widgets │ ├── Widget.ts │ └── MousePath.ts ├── index.ts ├── ticker │ ├── Ticker.ts │ └── AnimationFrameTicker.ts ├── entity │ ├── TextEntity.ts │ └── Entity.ts ├── inputManager │ ├── InputState.ts │ ├── Key.ts │ └── InputManager.ts ├── scene │ └── Scene.ts ├── math │ └── Vector2.ts └── engine │ └── Engine.ts ├── test └── blah.test.ts ├── .github └── workflows │ ├── size.yml │ └── main.yml ├── tsconfig.json ├── package.json └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | #
🚂 `@are/engine`
2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | dist 5 | !example/dist 6 | .cache -------------------------------------------------------------------------------- /example/assets/1000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ARE/engine/main/example/assets/1000.png -------------------------------------------------------------------------------- /example/assets/test.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ARE/engine/main/example/assets/test.wav -------------------------------------------------------------------------------- /src/assetLoader/assetTypes/index.ts: -------------------------------------------------------------------------------- 1 | export * from './ImageAsset' 2 | export * from './SoundAsset' 3 | -------------------------------------------------------------------------------- /src/assetLoader/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Asset' 2 | export * from './AssetDefinition' 3 | export * from './AssetLoader' 4 | export * from './assetTypes' 5 | -------------------------------------------------------------------------------- /test/blah.test.ts: -------------------------------------------------------------------------------- 1 | import { sum } from '../src' 2 | 3 | describe('blah', () => { 4 | it('works', () => { 5 | expect(sum(1, 1)).toEqual(2) 6 | }) 7 | }) 8 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": ["ESNext", "DOM"], 4 | "target": "ES6", 5 | "moduleResolution": "node", 6 | "allowSyntheticDefaultImports": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/assetLoader/AssetDefinition.ts: -------------------------------------------------------------------------------- 1 | export enum AssetType { 2 | image, 3 | sound, 4 | } 5 | 6 | export class AssetDefinition { 7 | constructor(public type: AssetType, public source: string) {} 8 | } 9 | -------------------------------------------------------------------------------- /.github/workflows/size.yml: -------------------------------------------------------------------------------- 1 | name: size 2 | on: [pull_request] 3 | jobs: 4 | size: 5 | runs-on: ubuntu-latest 6 | env: 7 | CI_JOB_NUMBER: 1 8 | steps: 9 | - uses: actions/checkout@v1 10 | - uses: andresz1/size-limit-action@v1 11 | with: 12 | github_token: ${{ secrets.GITHUB_TOKEN }} 13 | -------------------------------------------------------------------------------- /src/assetLoader/assetTypes/ImageAsset.ts: -------------------------------------------------------------------------------- 1 | import { Asset } from '../Asset' 2 | import { AssetDefinition, AssetType } from '../AssetDefinition' 3 | 4 | export class ImageAsset extends Asset { 5 | type = AssetType.image 6 | 7 | constructor(definition: AssetDefinition, public image: HTMLImageElement) { 8 | super(definition) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/assetLoader/assetTypes/SoundAsset.ts: -------------------------------------------------------------------------------- 1 | import { Asset } from '../Asset' 2 | import { AssetDefinition, AssetType } from '../AssetDefinition' 3 | 4 | export class SoundAsset extends Asset { 5 | type = AssetType.image 6 | 7 | constructor(definition: AssetDefinition, public audio: HTMLAudioElement) { 8 | super(definition) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/widgets/Widget.ts: -------------------------------------------------------------------------------- 1 | import { EntityDrawContext, EntityUpdateContext } from '../entity/Entity' 2 | 3 | export abstract class Widget { 4 | willUpdate(_context: EntityUpdateContext): void {} 5 | didUpdate(_context: EntityUpdateContext): void {} 6 | 7 | willDraw(_context: EntityDrawContext): void {} 8 | didDraw(_context: EntityDrawContext): void {} 9 | } 10 | -------------------------------------------------------------------------------- /example/src/declarations.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.png' 2 | declare module '*.wav' 3 | 4 | declare module 'simplify-js' { 5 | interface Point { 6 | x: number 7 | y: number 8 | } 9 | 10 | function simplify( 11 | points: T[], 12 | tolerance?: number, 13 | highQuality?: boolean 14 | ): T[] 15 | namespace simplify {} 16 | 17 | export = simplify 18 | } 19 | -------------------------------------------------------------------------------- /example/src/DrawingScene.ts: -------------------------------------------------------------------------------- 1 | import { EntityDrawContext } from '../../src/entity/Entity' 2 | import { Scene } from '../../src/scene/Scene' 3 | import { DrawingEntity } from './DrawingEntity' 4 | 5 | export class DrawingScene extends Scene { 6 | willMount() { 7 | this.add(new DrawingEntity()) 8 | } 9 | 10 | willDraw({ ctx }: EntityDrawContext) { 11 | ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/src/UIScene.ts: -------------------------------------------------------------------------------- 1 | import { Scene } from '../../src/scene/Scene' 2 | import { TextEntity } from '../../src/entity/TextEntity' 3 | import { vec2 } from '../../src/math/Vector2' 4 | 5 | export class UIScene extends Scene { 6 | willMount() { 7 | this.add( 8 | new TextEntity({ 9 | text: 'Hello world!', 10 | position: vec2(100, 100), 11 | style: 'black', 12 | font: '16px monospace', 13 | }) 14 | ) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /example/src/index.ts: -------------------------------------------------------------------------------- 1 | import { AnimationFrameTicker, Engine, vec2 } from '../../src' 2 | import { GridScene } from './scenes/GridScene' 3 | 4 | const canvas = document.querySelector('#app') 5 | 6 | const engine = new Engine({ 7 | canvas: canvas, 8 | size: vec2(window.innerWidth, window.innerHeight), 9 | ticker: new AnimationFrameTicker(), 10 | }) 11 | 12 | engine.registerScene('grid', GridScene) 13 | 14 | engine.start() 15 | 16 | engine.pushScene('grid') 17 | -------------------------------------------------------------------------------- /src/assetLoader/Asset.ts: -------------------------------------------------------------------------------- 1 | import { AssetDefinition, AssetType } from './AssetDefinition' 2 | 3 | export abstract class Asset { 4 | abstract type: AssetType 5 | 6 | constructor(public definition: AssetDefinition) {} 7 | 8 | static image(source: string): AssetDefinition { 9 | return new AssetDefinition(AssetType.image, source) 10 | } 11 | 12 | static sound(source: string): AssetDefinition { 13 | return new AssetDefinition(AssetType.sound, source) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "private": true, 4 | "version": "1.0.0", 5 | "browserslist": [ 6 | "last 1 Chrome version" 7 | ], 8 | "scripts": { 9 | "start": "parcel src/index.html", 10 | "build": "parcel build src/index.html" 11 | }, 12 | "devDependencies": { 13 | "parcel-bundler": "^1.12.4", 14 | "typescript": "^4.1.2" 15 | }, 16 | "dependencies": { 17 | "@tweenjs/tween.js": "^18.6.4", 18 | "simplify-js": "^1.2.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './assetLoader/index' 2 | export * from './engine/Engine' 3 | export * from './entity/Entity' 4 | export * from './entity/TextEntity' 5 | export * from './inputManager/InputManager' 6 | export * from './inputManager/InputState' 7 | export * from './inputManager/Key' 8 | export * from './math/Vector2' 9 | export * from './scene/Scene' 10 | export * from './ticker/Ticker' 11 | export * from './ticker/AnimationFrameTicker' 12 | export * from './widgets/Widget' 13 | export * from './widgets/MousePath' 14 | -------------------------------------------------------------------------------- /src/ticker/Ticker.ts: -------------------------------------------------------------------------------- 1 | export type TickerState = { 2 | frameNumber: number 3 | 4 | startTimestamp: number 5 | lastTimestamp: number 6 | currentTimestamp: number 7 | 8 | delta: number 9 | } 10 | 11 | export type TickerListener = (state: TickerState) => void 12 | 13 | export type CancelTickerListener = () => void 14 | 15 | export abstract class Ticker { 16 | abstract start(): void 17 | abstract stop(): void 18 | 19 | abstract get isRunning(): boolean 20 | 21 | abstract listen(listener: TickerListener): CancelTickerListener 22 | } 23 | -------------------------------------------------------------------------------- /example/dist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "types"], 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "lib": ["dom", "esnext"], 6 | "target": "ESNext", 7 | "importHelpers": true, 8 | "declaration": true, 9 | "sourceMap": true, 10 | "rootDir": "./src", 11 | "strict": true, 12 | "strictNullChecks": true, 13 | "noImplicitReturns": true, 14 | "noFallthroughCasesInSwitch": true, 15 | "noUnusedLocals": true, 16 | "noUnusedParameters": true, 17 | "moduleResolution": "node", 18 | "esModuleInterop": true, 19 | "skipLibCheck": true, 20 | "forceConsistentCasingInFileNames": true, 21 | "noEmit": true, 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push] 3 | jobs: 4 | build: 5 | name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }} 6 | 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | node: ['10.x', '12.x', '14.x'] 11 | os: [ubuntu-latest, windows-latest, macOS-latest] 12 | 13 | steps: 14 | - name: Checkout repo 15 | uses: actions/checkout@v2 16 | 17 | - name: Use Node ${{ matrix.node }} 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: ${{ matrix.node }} 21 | 22 | - name: Install deps and build (with cache) 23 | uses: bahmutov/npm-install@v1 24 | 25 | - name: Lint 26 | run: yarn lint 27 | 28 | - name: Test 29 | run: yarn test --ci --coverage --maxWorkers=2 30 | 31 | - name: Build 32 | run: yarn build 33 | -------------------------------------------------------------------------------- /src/entity/TextEntity.ts: -------------------------------------------------------------------------------- 1 | import { Entity, EntityDrawContext } from '../../src/entity/Entity' 2 | import { Vector2 } from '../../src/math/Vector2' 3 | 4 | interface TextOptions { 5 | text: string 6 | font: string 7 | style: string 8 | position: Vector2 9 | 10 | vertical?: CanvasTextBaseline 11 | horizontal?: CanvasTextAlign 12 | } 13 | 14 | export class TextEntity extends Entity { 15 | constructor(private options: TextOptions) { 16 | super() 17 | } 18 | 19 | update() {} 20 | 21 | draw({ ctx }: EntityDrawContext): void { 22 | const { font, style, horizontal, vertical, position, text } = this.options 23 | 24 | ctx.save() 25 | ctx.font = font 26 | ctx.fillStyle = style 27 | 28 | ctx.textAlign = horizontal ?? 'center' 29 | ctx.textBaseline = vertical ?? 'middle' 30 | 31 | ctx.fillText(text, position.x, position.y) 32 | 33 | ctx.restore() 34 | } 35 | 36 | widgets = [] 37 | } 38 | -------------------------------------------------------------------------------- /src/inputManager/InputState.ts: -------------------------------------------------------------------------------- 1 | import { Key } from './Key' 2 | import { Vector2 } from '../math/Vector2' 3 | 4 | export interface KeyState { 5 | re: boolean 6 | fe: boolean 7 | 8 | pressed: boolean 9 | } 10 | 11 | const emptyKeyState: KeyState = { re: false, fe: false, pressed: false } 12 | 13 | export class InputState { 14 | constructor( 15 | private keyState: Map, 16 | private mousePosition: Vector2 17 | ) {} 18 | 19 | private getKeyState(keyCode: Key): KeyState { 20 | return this.keyState.get(keyCode) ?? emptyKeyState 21 | } 22 | 23 | isPressed(keyCode: Key): boolean { 24 | return this.getKeyState(keyCode).pressed 25 | } 26 | 27 | isReleased(keyCode: Key): boolean { 28 | return !this.getKeyState(keyCode).pressed 29 | } 30 | 31 | isJustPressed(keyCode: Key): boolean { 32 | return this.getKeyState(keyCode).re 33 | } 34 | 35 | isJustReleased(keyCode: Key): boolean { 36 | return this.getKeyState(keyCode).fe 37 | } 38 | 39 | get mouse(): Vector2 { 40 | return this.mousePosition 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@are/engine", 3 | "author": "Artur Wojciechowski ", 4 | "version": "0.1.0", 5 | "license": "Hippocratic-2.1", 6 | "engines": { 7 | "node": ">=10" 8 | }, 9 | "main": "dist/index.js", 10 | "typings": "dist/index.d.ts", 11 | "module": "dist/engine.esm.js", 12 | "files": [ 13 | "dist", 14 | "src" 15 | ], 16 | "scripts": { 17 | "start": "tsdx watch", 18 | "build": "tsdx build", 19 | "test": "tsdx test", 20 | "lint": "tsdx lint", 21 | "size": "size-limit", 22 | "analyze": "size-limit --why" 23 | }, 24 | "devDependencies": { 25 | "@size-limit/preset-small-lib": "^4.9.0", 26 | "husky": "^4.3.0", 27 | "size-limit": "^4.9.0", 28 | "tsdx": "^0.14.1", 29 | "tslib": "^2.0.3", 30 | "typescript": "^4.1.2" 31 | }, 32 | "peerDependencies": {}, 33 | "husky": { 34 | "hooks": { 35 | "pre-commit": "tsdx lint" 36 | } 37 | }, 38 | "prettier": { 39 | "printWidth": 80, 40 | "semi": false, 41 | "singleQuote": true, 42 | "trailingComma": "es5" 43 | }, 44 | "size-limit": [ 45 | { 46 | "path": "dist/engine.cjs.production.min.js", 47 | "limit": "10 KB" 48 | }, 49 | { 50 | "path": "dist/engine.esm.js", 51 | "limit": "10 KB" 52 | } 53 | ] 54 | } 55 | -------------------------------------------------------------------------------- /example/src/widgets/AnimationWidget.ts: -------------------------------------------------------------------------------- 1 | import { EntityUpdateContext, Widget } from '../../../src' 2 | 3 | import { Tween, Group, Easing } from '@tweenjs/tween.js' 4 | 5 | export class AnimatedValueWidget extends Widget { 6 | private group: Group = new Group() 7 | 8 | private tween: Tween 9 | 10 | constructor(public state: T) { 11 | super() 12 | this.state = state 13 | } 14 | 15 | set(newState: T) { 16 | this.group.removeAll() 17 | for (let tween of this.group.getAll()) { 18 | tween.stop().stopChainedTweens() 19 | } 20 | 21 | this.state = newState 22 | } 23 | 24 | update(newState: T, time: number) { 25 | this.group.removeAll() 26 | for (let tween of this.group.getAll()) { 27 | tween.stop().stopChainedTweens() 28 | } 29 | 30 | this.tween = new Tween(this.state, this.group) 31 | .easing(Easing.Quadratic.Out) 32 | .to(newState, time) 33 | .start() 34 | .onComplete(result => { 35 | this.state = result 36 | this.tween = null 37 | }) 38 | .onStop(result => { 39 | this.state = newState 40 | this.tween = null 41 | }) 42 | 43 | return this.tween 44 | } 45 | 46 | willUpdate({ tickerState }: EntityUpdateContext) { 47 | this.group.update(tickerState.currentTimestamp) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/entity/Entity.ts: -------------------------------------------------------------------------------- 1 | import { InputState } from '../inputManager/InputState' 2 | import { Vector2 } from '../math/Vector2' 3 | import { Scene } from '../scene/Scene' 4 | import { TickerState } from '../ticker/Ticker' 5 | import { Widget } from '../widgets/Widget' 6 | 7 | export type EntityUpdateContext = { 8 | matrix: DOMMatrix 9 | inputState: InputState 10 | tickerState: TickerState 11 | canvasSize: Vector2 12 | } 13 | export type EntityDrawContext = { 14 | ctx: CanvasRenderingContext2D 15 | tickerState: TickerState 16 | canvasSize: Vector2 17 | } 18 | 19 | export abstract class Entity { 20 | abstract widgets: Widget[] 21 | 22 | protected scene: Scene | null = null 23 | 24 | _mount(scene: Scene) { 25 | this.scene = scene 26 | } 27 | 28 | _unmount() { 29 | this.scene = null 30 | } 31 | 32 | _update(context: EntityUpdateContext) { 33 | for (let widget of Object.values(this.widgets)) { 34 | widget.willUpdate(context) 35 | } 36 | 37 | this.update(context) 38 | 39 | for (let widget of Object.values(this.widgets)) { 40 | widget.didUpdate(context) 41 | } 42 | } 43 | 44 | _draw(context: EntityDrawContext) { 45 | for (let widget of Object.values(this.widgets)) { 46 | widget.willDraw(context) 47 | } 48 | 49 | this.draw(context) 50 | 51 | for (let widget of Object.values(this.widgets)) { 52 | widget.didDraw(context) 53 | } 54 | } 55 | 56 | abstract update(context: EntityUpdateContext): void 57 | abstract draw(context: EntityDrawContext): void 58 | } 59 | -------------------------------------------------------------------------------- /src/ticker/AnimationFrameTicker.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CancelTickerListener, 3 | Ticker, 4 | TickerListener, 5 | TickerState, 6 | } from './Ticker' 7 | 8 | export class AnimationFrameTicker extends Ticker { 9 | private listeners: Set = new Set() 10 | 11 | private afId: number | null = null 12 | 13 | private frameNumber: number = 0 14 | private startTimestamp: number = 0 15 | private lastTimestamp: number = 0 16 | 17 | get isRunning(): boolean { 18 | return this.afId !== null 19 | } 20 | 21 | start(): void { 22 | if (this.afId === null) { 23 | this.frameNumber = 0 24 | 25 | this.scheduleNextAnimationFrame() 26 | } 27 | } 28 | 29 | stop(): void { 30 | if (this.afId !== null) { 31 | cancelAnimationFrame(this.afId) 32 | this.afId = null 33 | } 34 | } 35 | 36 | private scheduleNextAnimationFrame(): void { 37 | this.afId = requestAnimationFrame(this.tick.bind(this)) 38 | } 39 | 40 | private tick(currentTimestamp: number): void { 41 | this.scheduleNextAnimationFrame() 42 | 43 | if (this.frameNumber === 0) { 44 | this.startTimestamp = currentTimestamp 45 | this.lastTimestamp = currentTimestamp 46 | } 47 | 48 | const tickerState: TickerState = { 49 | frameNumber: this.frameNumber, 50 | startTimestamp: this.startTimestamp, 51 | lastTimestamp: this.lastTimestamp, 52 | currentTimestamp: currentTimestamp, 53 | delta: currentTimestamp - this.lastTimestamp, 54 | } 55 | 56 | for (let listener of this.listeners) { 57 | listener(tickerState) 58 | } 59 | 60 | this.lastTimestamp = currentTimestamp 61 | this.frameNumber += 1 62 | } 63 | 64 | listen(listener: TickerListener): CancelTickerListener { 65 | this.listeners.add(listener) 66 | 67 | return () => { 68 | this.listeners.delete(listener) 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/scene/Scene.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | EntityDrawContext, 4 | EntityUpdateContext, 5 | } from '../entity/Entity' 6 | 7 | export abstract class Scene { 8 | private entities: Set = new Set() 9 | 10 | protected add(entity: Entity) { 11 | this.entities.add(entity) 12 | } 13 | 14 | protected addAll(entities: Entity[]) { 15 | for (let entity of entities) { 16 | this.entities.add(entity) 17 | } 18 | } 19 | 20 | protected remove(entity: Entity) { 21 | this.entities.delete(entity) 22 | } 23 | 24 | willMount(): void {} 25 | didUnmount(): void {} 26 | 27 | prepare( 28 | _updateContext: EntityUpdateContext, 29 | _drawContext: EntityDrawContext 30 | ): void {} 31 | 32 | cleanup( 33 | _updateContext: EntityUpdateContext, 34 | _drawContext: EntityDrawContext 35 | ): void {} 36 | 37 | willUpdate(_context: EntityUpdateContext): void {} 38 | didUpdate(_context: EntityUpdateContext): void {} 39 | willDraw(_context: EntityDrawContext): void {} 40 | didDraw(_context: EntityDrawContext): void {} 41 | 42 | update(context: EntityUpdateContext) { 43 | this.willUpdate(context) 44 | 45 | for (let entity of this.entities) { 46 | entity._update(context) 47 | } 48 | 49 | this.didUpdate(context) 50 | } 51 | 52 | draw(context: EntityDrawContext) { 53 | this.willDraw(context) 54 | 55 | for (let entity of this.entities) { 56 | context.ctx.save() 57 | entity._draw(context) 58 | context.ctx.restore() 59 | } 60 | 61 | this.didDraw(context) 62 | } 63 | 64 | mount(): void { 65 | this.willMount() 66 | 67 | for (let entity of this.entities) { 68 | entity._mount(this) 69 | } 70 | } 71 | 72 | unmount(): void { 73 | for (let entity of this.entities) { 74 | entity._unmount() 75 | } 76 | 77 | this.entities.clear() 78 | 79 | this.didUnmount() 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/widgets/MousePath.ts: -------------------------------------------------------------------------------- 1 | import { EntityUpdateContext } from '../entity/Entity' 2 | import { Key } from '../inputManager/Key' 3 | import { Vector2 } from '../math/Vector2' 4 | import { Widget } from './Widget' 5 | 6 | export type PathStartedCallback = (start: Vector2, key: Key) => void 7 | export type PathEndedCallback = (path: Array, key: Key) => void 8 | 9 | export class MousePathWidget extends Widget { 10 | public isTracking = false 11 | public state: Array = [] 12 | 13 | constructor(public keys: Key[]) { 14 | super() 15 | } 16 | 17 | private shouldNotifyPathStarted: boolean = false 18 | private shouldNotifyPathEnded: boolean = false 19 | private key: Key | null = null 20 | 21 | willUpdate({ inputState }: EntityUpdateContext) { 22 | if (this.isTracking === false) { 23 | const key = this.keys.find(inputState.isJustPressed.bind(inputState)) 24 | 25 | if (key) { 26 | this.state = [] 27 | this.isTracking = true 28 | 29 | this.key = key 30 | this.shouldNotifyPathStarted = true 31 | } 32 | } 33 | 34 | if ( 35 | this.isTracking === true && 36 | this.key && 37 | inputState.isPressed(this.key) 38 | ) { 39 | this.state.push(inputState.mouse.clone()) 40 | } 41 | 42 | if ( 43 | this.isTracking === true && 44 | this.key && 45 | inputState.isJustReleased(this.key) 46 | ) { 47 | this.isTracking = false 48 | this.shouldNotifyPathEnded = true 49 | } 50 | } 51 | 52 | onPathStarted(callback: PathStartedCallback) { 53 | if (this.shouldNotifyPathStarted) { 54 | this.shouldNotifyPathStarted = false 55 | 56 | callback(this.state[0], this.key!) 57 | } 58 | } 59 | 60 | onPathEnded(callback: PathEndedCallback) { 61 | if (this.shouldNotifyPathEnded) { 62 | this.shouldNotifyPathEnded = false 63 | 64 | const state = this.state 65 | this.state = [] 66 | 67 | callback(state, this.key!) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/math/Vector2.ts: -------------------------------------------------------------------------------- 1 | export class Vector2 { 2 | constructor(private _x: number = 0, private _y: number = 0) {} 3 | 4 | get x(): number { 5 | return this._x 6 | } 7 | 8 | get y(): number { 9 | return this._y 10 | } 11 | 12 | get e(): [number, number] { 13 | return [this._x, this._y] 14 | } 15 | 16 | get o(): { x: number; y: number } { 17 | return { x: this._x, y: this._y } 18 | } 19 | 20 | static from({ x, y }: { x: number; y: number }) { 21 | return Vector2.of(x, y) 22 | } 23 | 24 | clone = () => Vector2.of(this.x, this.y) 25 | simpleProduct = () => this.x * this.y 26 | asStride = (index: number) => 27 | Vector2.of(index % this.x, (index - (index % this.x)) / this.x) 28 | 29 | add(other: Vector2): Vector2 30 | add(x: number, y?: number): Vector2 31 | add(x: number | Vector2, y?: number): Vector2 { 32 | if (x instanceof Vector2) { 33 | return Vector2.of(this._x + x._x, this._y + x._y) 34 | } 35 | 36 | return Vector2.of(this._x + x, this._y + (y ?? x)) 37 | } 38 | 39 | mul = (x: number, y?: number) => Vector2.of(this.x * x, this.y * (y ?? x)) 40 | 41 | div(other: Vector2): Vector2 42 | div(x: number, y?: number): Vector2 43 | div(x: number | Vector2, y?: number): Vector2 { 44 | if (x instanceof Vector2) { 45 | return Vector2.of(this._x / x._x, this._y / x._y) 46 | } 47 | 48 | return Vector2.of(this._x / x, this._y / (y ?? x)) 49 | } 50 | 51 | pipe = (fn: (value: Vector2) => Vector2) => fn(this) 52 | 53 | equals = (other: Vector2) => this.x === other.x && this.y === other.y 54 | 55 | distance = (other: Vector2) => 56 | Math.sqrt(Math.pow(other.x - this.x, 2) + Math.pow(other.y - this.y, 2)) 57 | 58 | snapToGrid = (size: Vector2) => 59 | Vector2.of( 60 | Math.round(this.x / size.x) * size.x, 61 | Math.round(this.y / size.y) * size.y 62 | ) 63 | 64 | transform = (matrix: DOMMatrix) => 65 | Vector2.fromDOMPoint(matrix.transformPoint({ x: this._x, y: this._y })) 66 | 67 | floor = () => Vector2.of(Math.floor(this._x), Math.floor(this._y)) 68 | 69 | static fromDOMPoint(point: DOMPoint) { 70 | return new Vector2(point.x, point.y) 71 | } 72 | 73 | static zero(): Vector2 { 74 | return new Vector2(0, 0) 75 | } 76 | 77 | static of(x: number, y?: number) { 78 | return new Vector2(x, y ?? x) 79 | } 80 | } 81 | 82 | export const vec2 = (x: number, y?: number) => Vector2.of(x, y ?? x) 83 | -------------------------------------------------------------------------------- /src/inputManager/Key.ts: -------------------------------------------------------------------------------- 1 | export enum Key { 2 | LMB = 0, 3 | MMB = 1, 4 | RMB = 2, 5 | MB3 = 3, 6 | MB4 = 4, 7 | 8 | Backspace = 8, 9 | Tab = 9, 10 | Enter = 13, 11 | Shift = 16, 12 | Ctrl = 17, 13 | Alt = 18, 14 | PauseBreak = 19, 15 | CapsLock = 20, 16 | Escape = 27, 17 | Space = 32, 18 | PageUp = 33, 19 | PageDown = 34, 20 | End = 35, 21 | Home = 36, 22 | 23 | LeftArrow = 37, 24 | UpArrow = 38, 25 | RightArrow = 39, 26 | DownArrow = 40, 27 | 28 | Insert = 45, 29 | Delete = 46, 30 | 31 | Zero = 48, 32 | ClosedParen = Zero, 33 | One = 49, 34 | ExclamationMark = One, 35 | Two = 50, 36 | AtSign = Two, 37 | Three = 51, 38 | PoundSign = Three, 39 | Hash = PoundSign, 40 | Four = 52, 41 | DollarSign = Four, 42 | Five = 53, 43 | PercentSign = Five, 44 | Six = 54, 45 | Caret = Six, 46 | Hat = Caret, 47 | Seven = 55, 48 | Ampersand = Seven, 49 | Eight = 56, 50 | Star = Eight, 51 | Asterik = Star, 52 | Nine = 57, 53 | OpenParen = Nine, 54 | 55 | A = 65, 56 | B = 66, 57 | C = 67, 58 | D = 68, 59 | E = 69, 60 | F = 70, 61 | G = 71, 62 | H = 72, 63 | I = 73, 64 | J = 74, 65 | K = 75, 66 | L = 76, 67 | M = 77, 68 | N = 78, 69 | O = 79, 70 | P = 80, 71 | Q = 81, 72 | R = 82, 73 | S = 83, 74 | T = 84, 75 | U = 85, 76 | V = 86, 77 | W = 87, 78 | X = 88, 79 | Y = 89, 80 | Z = 90, 81 | 82 | LeftWindowKey = 91, 83 | RightWindowKey = 92, 84 | SelectKey = 93, 85 | 86 | Numpad0 = 96, 87 | Numpad1 = 97, 88 | Numpad2 = 98, 89 | Numpad3 = 99, 90 | Numpad4 = 100, 91 | Numpad5 = 101, 92 | Numpad6 = 102, 93 | Numpad7 = 103, 94 | Numpad8 = 104, 95 | Numpad9 = 105, 96 | 97 | Multiply = 106, 98 | Add = 107, 99 | Subtract = 109, 100 | DecimalPoint = 110, 101 | Divide = 111, 102 | 103 | F1 = 112, 104 | F2 = 113, 105 | F3 = 114, 106 | F4 = 115, 107 | F5 = 116, 108 | F6 = 117, 109 | F7 = 118, 110 | F8 = 119, 111 | F9 = 120, 112 | F10 = 121, 113 | F11 = 122, 114 | F12 = 123, 115 | 116 | NumLock = 144, 117 | ScrollLock = 145, 118 | 119 | SemiColon = 186, 120 | Equals = 187, 121 | Comma = 188, 122 | Dash = 189, 123 | Period = 190, 124 | UnderScore = Dash, 125 | PlusSign = Equals, 126 | ForwardSlash = 191, 127 | Tilde = 192, 128 | GraveAccent = Tilde, 129 | 130 | OpenBracket = 219, 131 | ClosedBracket = 221, 132 | Quote = 222, 133 | } 134 | 135 | export function isKey(keyCode: number): keyCode is Key { 136 | return keyCode <= Key.Backspace && keyCode >= Key.Quote 137 | } 138 | -------------------------------------------------------------------------------- /src/inputManager/InputManager.ts: -------------------------------------------------------------------------------- 1 | import { InputState, KeyState } from './InputState' 2 | import { Key } from './Key' 3 | import { vec2, Vector2 } from '../math/Vector2' 4 | 5 | export class InputManager { 6 | private state: Map = new Map() 7 | private mousePosition: Vector2 = vec2(0, 0) 8 | 9 | private element: HTMLElement | null = null 10 | 11 | getState(): InputState { 12 | return new InputState( 13 | new Map(this.state.entries()), 14 | this.mousePosition.clone() 15 | ) 16 | } 17 | 18 | processTick(): void { 19 | for (let key of this.state.keys()) { 20 | const state = this.state.get(key)! 21 | 22 | this.state.set(key, { 23 | pressed: state.pressed, 24 | fe: false, 25 | re: false, 26 | }) 27 | } 28 | } 29 | 30 | mount(element: HTMLElement): void { 31 | this.element = element 32 | window.addEventListener('keydown', this.handleKeydown) 33 | window.addEventListener('keyup', this.handleKeyup) 34 | window.addEventListener('mousedown', this.handleMousedown) 35 | window.addEventListener('mouseup', this.handleMouseup) 36 | window.addEventListener('mousemove', this.handleMousemove) 37 | } 38 | 39 | unmount(): void { 40 | this.element = null 41 | window.removeEventListener('keydown', this.handleKeydown) 42 | window.removeEventListener('keyup', this.handleKeyup) 43 | window.removeEventListener('mousedown', this.handleMousedown) 44 | window.removeEventListener('mouseup', this.handleMouseup) 45 | window.removeEventListener('mousemove', this.handleMousemove) 46 | } 47 | 48 | private handleKeydown = (event: KeyboardEvent) => { 49 | const state = this.state.get(event.keyCode) 50 | 51 | if (!state?.pressed) { 52 | this.state.set(event.keyCode, { 53 | re: true, 54 | fe: false, 55 | pressed: true, 56 | }) 57 | } 58 | } 59 | 60 | private handleKeyup = (event: KeyboardEvent) => { 61 | this.state.set(event.keyCode, { 62 | re: false, 63 | fe: true, 64 | pressed: false, 65 | }) 66 | } 67 | 68 | private handleMousedown = (event: MouseEvent) => { 69 | const state = this.state.get(event.button) 70 | 71 | if (!state?.pressed) { 72 | this.state.set(event.button, { 73 | re: true, 74 | fe: false, 75 | pressed: true, 76 | }) 77 | } 78 | } 79 | private handleMouseup = (event: MouseEvent) => { 80 | this.state.set(event.button, { 81 | re: false, 82 | fe: true, 83 | pressed: false, 84 | }) 85 | } 86 | private handleMousemove = (event: MouseEvent) => { 87 | const boundingRect = this.element?.getBoundingClientRect() 88 | 89 | this.mousePosition = vec2( 90 | event.clientX - (boundingRect?.left ?? 0), 91 | event.clientY - (boundingRect?.top ?? 0) 92 | ) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/engine/Engine.ts: -------------------------------------------------------------------------------- 1 | import { vec2, Vector2 } from '../math/Vector2' 2 | import { Scene } from '../scene/Scene' 3 | import { Ticker, TickerState } from '../ticker/Ticker' 4 | import { InputManager } from '../inputManager/InputManager' 5 | import { EntityDrawContext, EntityUpdateContext } from '../entity/Entity' 6 | 7 | type SceneConstructor = { new (): Scene } 8 | 9 | type EngineOptions = { 10 | canvas: HTMLCanvasElement 11 | size: Vector2 12 | ticker: Ticker 13 | } 14 | 15 | export class Engine { 16 | public ticker: Ticker 17 | 18 | private canvas: HTMLCanvasElement 19 | private context: CanvasRenderingContext2D 20 | 21 | private canvasSize!: Vector2 22 | private input = new InputManager() 23 | 24 | private scenes: Map = new Map() 25 | private stack: Scene[] = [] 26 | 27 | constructor({ canvas, size, ticker }: EngineOptions) { 28 | this.ticker = ticker 29 | 30 | this.canvas = canvas 31 | this.context = this.canvas.getContext('2d')! 32 | this.resize(size) 33 | 34 | this.input.mount(canvas) 35 | ticker.listen(this.tick.bind(this)) 36 | 37 | window.addEventListener('resize', () => { 38 | this.resize(vec2(window.innerWidth, window.innerHeight)) 39 | }) 40 | } 41 | 42 | registerScene(name: string, Constructor: SceneConstructor) { 43 | this.scenes.set(name, Constructor) 44 | } 45 | 46 | getScene(name: string) { 47 | const Scene = this.scenes.get(name) 48 | 49 | if (!Scene) { 50 | throw new Error(`Requested to mount unregistered scene '${name}'`) 51 | } 52 | 53 | return new Scene() 54 | } 55 | 56 | pushScene(name: string) { 57 | const scene = this.getScene(name) 58 | 59 | this.stack.unshift(scene) 60 | 61 | scene.mount() 62 | } 63 | 64 | resize(newSize: Vector2) { 65 | this.canvasSize = newSize 66 | 67 | this.canvas.width = newSize.x 68 | this.canvas.height = newSize.y 69 | } 70 | 71 | private tick(tickerState: TickerState): void { 72 | this.context.clearRect(0, 0, this.canvasSize.x, this.canvasSize.y) 73 | 74 | const inputState = this.input.getState() 75 | 76 | let updateContext: EntityUpdateContext = { 77 | matrix: this.context.getTransform(), 78 | inputState: inputState, 79 | tickerState: tickerState, 80 | canvasSize: this.canvasSize, 81 | } 82 | 83 | let drawContext: EntityDrawContext = { 84 | ctx: this.context, 85 | tickerState: tickerState, 86 | canvasSize: this.canvasSize, 87 | } 88 | 89 | for (let scene of this.stack) { 90 | scene.prepare(updateContext, drawContext) 91 | } 92 | 93 | for (let scene of this.stack) { 94 | scene.update(updateContext) 95 | } 96 | 97 | for (let scene of this.stack) { 98 | scene.draw(drawContext) 99 | } 100 | 101 | for (let scene of this.stack) { 102 | scene.cleanup(updateContext, drawContext) 103 | } 104 | 105 | this.input.processTick() 106 | } 107 | 108 | start(): void { 109 | this.ticker.start() 110 | } 111 | 112 | stop(): void { 113 | this.ticker.stop() 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /example/src/DrawingEntity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | EntityDrawContext, 4 | EntityUpdateContext, 5 | } from '../../src/entity/Entity' 6 | import { Key } from '../../src/inputManager/Key' 7 | import { vec2, Vector2 } from '../../src/math/Vector2' 8 | import { MousePathWidget } from '../../src/widgets/MousePath' 9 | 10 | import simplify from 'simplify-js' 11 | 12 | function shakey(path: Vector2[], amount: number = 2): Vector2[] { 13 | return path.map(point => 14 | vec2( 15 | point.x + (Math.random() - 0.5) * amount, 16 | point.y + (Math.random() - 0.5) * amount 17 | ) 18 | ) 19 | } 20 | 21 | function distance(a: Vector2, b: Vector2): number { 22 | return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2) 23 | } 24 | 25 | export class DrawingEntity extends Entity { 26 | path = new MousePathWidget([Key.Q, Key.W, Key.E]) 27 | 28 | paths: { color: string; path: Vector2[]; closed: boolean }[] = [] 29 | 30 | point: [string, Vector2] | null 31 | 32 | getColor(key: Key): string { 33 | let color: string 34 | switch (key) { 35 | case Key.Q: 36 | color = 'black' 37 | break 38 | case Key.W: 39 | color = 'darkgreen' 40 | break 41 | case Key.E: 42 | color = 'blue' 43 | break 44 | } 45 | return color 46 | } 47 | 48 | update(_context: EntityUpdateContext): void { 49 | this.path.onPathStarted((point, key) => { 50 | const color = this.getColor(key) 51 | this.point = [color, point] 52 | }) 53 | 54 | this.path.onPathEnded((path, key) => { 55 | this.point = null 56 | 57 | const color = this.getColor(key) 58 | 59 | this.paths.push({ 60 | color: color, 61 | path: simplify(path, 2).map(point => vec2(point.x, point.y)), 62 | closed: distance(path[path.length - 1], path[0]) < 10, 63 | }) 64 | }) 65 | } 66 | 67 | draw({ ctx }: EntityDrawContext): void { 68 | ctx.lineWidth = 2 69 | 70 | for (let { path, color, closed } of this.paths) { 71 | ctx.strokeStyle = color 72 | ctx.fillStyle = color 73 | ctx.beginPath() 74 | ctx.moveTo(path[0].x, path[0].y) 75 | 76 | for (let point of shakey(path.slice(1) as Vector2[], 2)) { 77 | ctx.lineTo(point.x, point.y) 78 | } 79 | 80 | if (closed) { 81 | ctx.closePath() 82 | ctx.fill() 83 | } else { 84 | ctx.stroke() 85 | } 86 | } 87 | 88 | if (this.point) { 89 | ctx.save() 90 | ctx.globalAlpha = 0.4 91 | ctx.beginPath() 92 | ctx.fillStyle = this.point[0] 93 | ctx.arc(this.point[1].x, this.point[1].y, 10, 0, Math.PI * 2) 94 | 95 | ctx.closePath() 96 | ctx.fill() 97 | ctx.restore() 98 | } 99 | 100 | if (this.path.isTracking) { 101 | ctx.strokeStyle = 'red' 102 | 103 | ctx.beginPath() 104 | ctx.moveTo(this.path.state[0].x, this.path.state[0].y) 105 | 106 | for (let point of shakey(simplify(this.path.state.slice(1), 2), 2)) { 107 | ctx.lineTo(point.x, point.y) 108 | } 109 | 110 | ctx.stroke() 111 | } 112 | } 113 | 114 | widgets = [this.path] 115 | } 116 | -------------------------------------------------------------------------------- /src/assetLoader/AssetLoader.ts: -------------------------------------------------------------------------------- 1 | import { Asset } from './Asset' 2 | import { AssetDefinition, AssetType } from './AssetDefinition' 3 | 4 | import { ImageAsset, SoundAsset } from './assetTypes' 5 | 6 | export class AssetMap { 7 | constructor(private map: Record) {} 8 | 9 | get(name: string) { 10 | return this.map[name] as T 11 | } 12 | } 13 | 14 | export class AssetLoader { 15 | private cache: Map> = new Map() 16 | 17 | async loadAssetMap( 18 | assetMap: Record, 19 | onProgress: (percentageLoaded: number) => void = () => {} 20 | ): Promise { 21 | const totalAmount = Object.keys(assetMap).length 22 | let currentAmount = 0 23 | 24 | const updateProgress = () => { 25 | currentAmount += 1 26 | 27 | onProgress(currentAmount / totalAmount) 28 | } 29 | 30 | onProgress(0) 31 | 32 | return new AssetMap( 33 | Object.fromEntries( 34 | await Promise.all( 35 | Object.entries(assetMap).map(([name, assetDef]) => { 36 | return this.loadAsset(assetDef).then(asset => { 37 | updateProgress() 38 | 39 | return [name, asset] 40 | }) 41 | }) 42 | ) 43 | ) 44 | ) 45 | } 46 | 47 | async loadAsset( 48 | assetDefinition: AssetDefinition 49 | ): Promise { 50 | let asset: Asset | null = null 51 | 52 | const assetMap = this.cache.get(assetDefinition.source) ?? new Map() 53 | 54 | if (assetMap.has(assetDefinition.type)) { 55 | asset = assetMap.get(assetDefinition.type) 56 | } 57 | 58 | if (asset !== null) { 59 | return (asset as unknown) as T 60 | } 61 | 62 | switch (assetDefinition.type) { 63 | case AssetType.image: 64 | asset = await this.loadImageAsset(assetDefinition) 65 | break 66 | case AssetType.sound: 67 | asset = await this.loadSoundAsset(assetDefinition) 68 | break 69 | default: 70 | throw new Error(`Unknown asset type: '${assetDefinition.type}'`) 71 | } 72 | 73 | assetMap.set(assetDefinition.type, asset) 74 | this.cache.set(assetDefinition.source, assetMap) 75 | 76 | return (asset as unknown) as T 77 | } 78 | 79 | private loadImageAsset( 80 | assetDefinition: AssetDefinition 81 | ): Promise { 82 | const imageElement = new Image() 83 | 84 | return new Promise((resolve, reject) => { 85 | imageElement.addEventListener('error', reject, { once: true }) 86 | imageElement.addEventListener( 87 | 'load', 88 | () => { 89 | resolve(new ImageAsset(assetDefinition, imageElement)) 90 | }, 91 | { once: true } 92 | ) 93 | 94 | imageElement.src = assetDefinition.source 95 | }) 96 | } 97 | 98 | private loadSoundAsset( 99 | assetDefinition: AssetDefinition 100 | ): Promise { 101 | const soundElement = new Audio() 102 | 103 | return new Promise((resolve, reject) => { 104 | soundElement.addEventListener('error', reject, { once: true }) 105 | soundElement.addEventListener( 106 | 'canplaythrough', 107 | () => { 108 | resolve(new SoundAsset(assetDefinition, soundElement)) 109 | }, 110 | { once: true } 111 | ) 112 | 113 | soundElement.src = assetDefinition.source 114 | }) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /example/src/widgets/PathOnGridWidget.ts: -------------------------------------------------------------------------------- 1 | import { Entity, EntityUpdateContext, Key, Vector2, Widget } from '../../../src' 2 | 3 | export class TrackingPathOnGridWidget extends Widget { 4 | public isTracking = false 5 | 6 | constructor(public gridSize: Vector2, public tileSize: Vector2) { 7 | super() 8 | } 9 | 10 | public startPoint: Vector2 | null = null 11 | public endPoint: Vector2 | null = null 12 | 13 | public path: Vector2[] = [] 14 | 15 | private shouldNotifyPathStart = false 16 | private shouldNotifyPathUpdated = false 17 | private shouldNotifyPathEnd = false 18 | 19 | willUpdate(context: EntityUpdateContext) { 20 | const { inputState } = context 21 | 22 | if (this.isTracking === false && inputState.isJustPressed(Key.LMB)) { 23 | return this.handlePathStart(context) 24 | } else if (this.isTracking === true && inputState.isPressed(Key.LMB)) { 25 | return this.handlePath(context) 26 | } else if (this.isTracking === true && inputState.isJustReleased(Key.LMB)) { 27 | return this.handlePathEnd(context) 28 | } 29 | } 30 | 31 | whenPathStarts(callback: () => void): void { 32 | if (this.shouldNotifyPathStart) { 33 | this.shouldNotifyPathStart = false 34 | callback() 35 | } 36 | } 37 | 38 | whenPathEnds(callback: () => void): void { 39 | if (this.shouldNotifyPathEnd) { 40 | this.shouldNotifyPathEnd = false 41 | callback() 42 | } 43 | } 44 | 45 | whenPathUpdates(callback: () => void): void { 46 | if (this.shouldNotifyPathUpdated) { 47 | this.shouldNotifyPathUpdated = false 48 | callback() 49 | } 50 | } 51 | 52 | clear(): void { 53 | this.isTracking = false 54 | this.path = [] 55 | this.startPoint = null 56 | this.endPoint = null 57 | } 58 | 59 | private handlePathStart({ inputState, matrix }: EntityUpdateContext) { 60 | const candidate = this.transformMousePosition(inputState.mouse, matrix) 61 | 62 | if (this.isPointContainedInTheGrid(candidate)) { 63 | this.isTracking = true 64 | this.path = [candidate] 65 | this.startPoint = candidate 66 | this.shouldNotifyPathStart = true 67 | } 68 | } 69 | 70 | private handlePath({ inputState, matrix }: EntityUpdateContext) { 71 | const candidate = this.transformMousePosition(inputState.mouse, matrix) 72 | 73 | if ( 74 | this.isPointContainedInTheGrid(candidate) && 75 | !this.lastPathPoint.equals(candidate) && 76 | this.lastPathPoint.distance(candidate) === 1 77 | ) { 78 | const index = this.path.findIndex(candidate.equals, candidate) 79 | 80 | const isPenultimate = index === this.path.length - 2 81 | 82 | if (isPenultimate && index !== -1) { 83 | this.path = this.path.slice(0, index) 84 | } 85 | 86 | if (index === -1 || isPenultimate) { 87 | this.endPoint = candidate 88 | this.path.push(candidate) 89 | this.shouldNotifyPathUpdated = true 90 | } 91 | } 92 | } 93 | 94 | private handlePathEnd(_context: EntityUpdateContext) { 95 | this.isTracking = false 96 | this.shouldNotifyPathEnd = true 97 | } 98 | 99 | private get lastPathPoint(): Vector2 { 100 | return this.path[this.path.length - 1] 101 | } 102 | 103 | private isPointContainedInTheGrid(point: Vector2) { 104 | return ( 105 | point.x >= 0 && 106 | point.x < this.gridSize.x && 107 | point.y >= 0 && 108 | point.y < this.gridSize.y 109 | ) 110 | } 111 | 112 | private transformMousePosition(initial: Vector2, matrix: DOMMatrix) { 113 | return initial 114 | .transform(matrix.inverse()) 115 | .snapToGrid(this.tileSize) 116 | .div(this.tileSize) 117 | .add(this.gridSize.div(2).floor()) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /example/src/scenes/GridScene.ts: -------------------------------------------------------------------------------- 1 | import { Easing } from '@tweenjs/tween.js' 2 | import { 3 | Entity, 4 | EntityDrawContext, 5 | EntityUpdateContext, 6 | Key, 7 | Scene, 8 | vec2, 9 | Vector2, 10 | } from '../../../src' 11 | import { AnimatedValueWidget } from '../widgets/AnimationWidget' 12 | import { TrackingPathOnGridWidget } from '../widgets/PathOnGridWidget' 13 | 14 | export class GridEntity extends Entity { 15 | widgets = [] 16 | 17 | constructor(private position: Vector2) { 18 | super() 19 | } 20 | 21 | update() {} 22 | 23 | draw({ ctx }: EntityDrawContext) { 24 | ctx.fillStyle = 'rgba(0, 0, 0, 0.1)' 25 | ctx.beginPath() 26 | ctx.arc(this.position.x, this.position.y, 5, 0, Math.PI * 2) 27 | ctx.closePath() 28 | ctx.fill() 29 | } 30 | } 31 | 32 | const prepare = (v: Vector2) => v.add(-6, -4).mul(100) 33 | 34 | class CreateTrackEntity extends Entity { 35 | trackWidget = new TrackingPathOnGridWidget(vec2(13, 9), vec2(100)) 36 | 37 | tween = new AnimatedValueWidget({ size: 0 }) 38 | lastPoint = new AnimatedValueWidget({ x: 0, y: 0 }) 39 | 40 | widgets = [this.trackWidget, this.tween, this.lastPoint] 41 | 42 | path: Vector2[] = [] 43 | 44 | update({ inputState, matrix }: EntityUpdateContext) { 45 | this.trackWidget.whenPathStarts(() => { 46 | console.log('tarl') 47 | this.lastPoint.set(this.trackWidget.path[0].o) 48 | }) 49 | 50 | this.trackWidget.whenPathUpdates(() => { 51 | const oldPath = this.path 52 | const newPath = this.trackWidget.path.slice(0) 53 | if (newPath.length > 1) { 54 | this.tween.update({ size: 26 }, 250) 55 | 56 | if (oldPath.length > newPath.length) { 57 | this.lastPoint.set(oldPath[oldPath.length - 1].o) 58 | this.lastPoint 59 | .update(newPath[newPath.length - 1].o, 50) 60 | .onComplete(() => { 61 | this.path = newPath 62 | }) 63 | .onStop(() => { 64 | this.path = newPath 65 | }) 66 | } else if (oldPath.length < newPath.length) { 67 | this.path = newPath 68 | this.lastPoint.set(newPath[newPath.length - 2].o) 69 | this.lastPoint.update(newPath[newPath.length - 1].o, 150) 70 | } 71 | } 72 | }) 73 | 74 | this.trackWidget.whenPathEnds(() => { 75 | this.tween.update({ size: 0 }, 150).onComplete(() => { 76 | this.trackWidget.clear() 77 | this.path = [] 78 | }) 79 | }) 80 | } 81 | draw({ ctx }: EntityDrawContext) { 82 | if (this.path.length > 1) { 83 | const path = this.path.slice(0, this.path.length - 1) 84 | ctx.beginPath() 85 | ctx.strokeStyle = 'black' 86 | ctx.lineWidth = this.tween.state.size * 2 87 | ctx.lineJoin = 'round' 88 | ctx.lineCap = 'round' 89 | 90 | ctx.moveTo(...path[0].pipe(prepare).e) 91 | 92 | for (let point of path.slice(1)) { 93 | ctx.lineTo(...point.pipe(prepare).e) 94 | } 95 | 96 | const lastPoint = Vector2.from(this.lastPoint.state).pipe(prepare) 97 | 98 | ctx.lineTo(...lastPoint.e) 99 | 100 | ctx.stroke() 101 | } 102 | } 103 | } 104 | 105 | export class GridScene extends Scene { 106 | gridSize = 100 107 | grid: GridEntity[] = [] 108 | size: Vector2 = vec2(13, 9) 109 | 110 | willMount() { 111 | for (let i = 0; i < this.size.simpleProduct(); i++) { 112 | const position = this.size.asStride(i).pipe(prepare) 113 | 114 | const entity = new GridEntity(position) 115 | 116 | this.grid.push(entity) 117 | } 118 | 119 | this.addAll(this.grid) 120 | 121 | this.add(new CreateTrackEntity()) 122 | } 123 | 124 | prepare( 125 | updateContext: EntityUpdateContext, 126 | { ctx, canvasSize }: EntityDrawContext 127 | ) { 128 | ctx.save() 129 | const half = canvasSize.div(2) 130 | 131 | ctx.translate(half.x, half.y) 132 | 133 | updateContext.matrix = ctx.getTransform() 134 | } 135 | 136 | cleanup(updateContext: EntityUpdateContext, { ctx }: EntityDrawContext) { 137 | ctx.restore() 138 | 139 | updateContext.matrix = ctx.getTransform() 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | @are/engine Copyright 2020 Artur Wojciechowski (“Licensor”) 2 | 3 | Hippocratic License Version Number: 2.1. 4 | 5 | Purpose. The purpose of this License is for the Licensor named above to permit the Licensee (as defined below) broad permission, if consistent with Human Rights Laws and Human Rights Principles (as each is defined below), to use and work with the Software (as defined below) within the full scope of Licensor’s copyright and patent rights, if any, in the Software, while ensuring attribution and protecting the Licensor from liability. 6 | 7 | Permission and Conditions. The Licensor grants permission by this license (“License”), free of charge, to the extent of Licensor’s rights under applicable copyright and patent law, to any person or entity (the “Licensee”) obtaining a copy of this software and associated documentation files (the “Software”), to do everything with the Software that would otherwise infringe (i) the Licensor’s copyright in the Software or (ii) any patent claims to the Software that the Licensor can license or becomes able to license, subject to all of the following terms and conditions: 8 | 9 | * Acceptance. This License is automatically offered to every person and entity subject to its terms and conditions. Licensee accepts this License and agrees to its terms and conditions by taking any action with the Software that, absent this License, would infringe any intellectual property right held by Licensor. 10 | 11 | * Notice. Licensee must ensure that everyone who gets a copy of any part of this Software from Licensee, with or without changes, also receives the License and the above copyright notice (and if included by the Licensor, patent, trademark and attribution notice). Licensee must cause any modified versions of the Software to carry prominent notices stating that Licensee changed the Software. For clarity, although Licensee is free to create modifications of the Software and distribute only the modified portion created by Licensee with additional or different terms, the portion of the Software not modified must be distributed pursuant to this License. If anyone notifies Licensee in writing that Licensee has not complied with this Notice section, Licensee can keep this License by taking all practical steps to comply within 30 days after the notice. If Licensee does not do so, Licensee’s License (and all rights licensed hereunder) shall end immediately. 12 | 13 | * Compliance with Human Rights Principles and Human Rights Laws. 14 | 15 | 1. Human Rights Principles. 16 | 17 | (a) Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights and the United Nations Global Compact that define recognized principles of international human rights (the “Human Rights Principles”). Licensee shall use the Software in a manner consistent with Human Rights Principles. 18 | 19 | (b) Unless the Licensor and Licensee agree otherwise, any dispute, controversy, or claim arising out of or relating to (i) Section 1(a) regarding Human Rights Principles, including the breach of Section 1(a), termination of this License for breach of the Human Rights Principles, or invalidity of Section 1(a) or (ii) a determination of whether any Law is consistent or in conflict with Human Rights Principles pursuant to Section 2, below, shall be settled by arbitration in accordance with the Hague Rules on Business and Human Rights Arbitration (the “Rules”); provided, however, that Licensee may elect not to participate in such arbitration, in which event this License (and all rights licensed hereunder) shall end immediately. The number of arbitrators shall be one unless the Rules require otherwise. 20 | 21 | Unless both the Licensor and Licensee agree to the contrary: (1) All documents and information concerning the arbitration shall be public and may be disclosed by any party; (2) The repository referred to under Article 43 of the Rules shall make available to the public in a timely manner all documents concerning the arbitration which are communicated to it, including all submissions of the parties, all evidence admitted into the record of the proceedings, all transcripts or other recordings of hearings and all orders, decisions and awards of the arbitral tribunal, subject only to the arbitral tribunal's powers to take such measures as may be necessary to safeguard the integrity of the arbitral process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3) Article 26(6) of the Rules shall not apply. 22 | 23 | 2. Human Rights Laws. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any Human Rights Laws. “Human Rights Laws” means any applicable laws, regulations, or rules (collectively, “Laws”) that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights; provided, however, that such Laws are consistent and not in conflict with Human Rights Principles (a dispute over the consistency or a conflict between Laws and Human Rights Principles shall be determined by arbitration as stated above). Where the Human Rights Laws of more than one jurisdiction are applicable or in conflict with respect to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply. 24 | 25 | 3. Indemnity. Licensee shall hold harmless and indemnify Licensor (and any other contributor) against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor’s reasonable attorneys’ fees, arising out of or relating to Licensee’s use of the Software in violation of Human Rights Laws or Human Rights Principles. 26 | 27 | * Failure to Comply. Any failure of Licensee to act according to the terms and conditions of this License is both a breach of the License and an infringement of the intellectual property rights of the Licensor (subject to exceptions under Laws, e.g., fair use). In the event of a breach or infringement, the terms and conditions of this License may be enforced by Licensor under the Laws of any jurisdiction to which Licensee is subject. Licensee also agrees that the Licensor may enforce the terms and conditions of this License against Licensee through specific performance (or similar remedy under Laws) to the extent permitted by Laws. For clarity, except in the event of a breach of this License, infringement, or as otherwise stated in this License, Licensor may not terminate this License with Licensee. 28 | 29 | * Enforceability and Interpretation. If any term or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction; provided, however, subject to a court modification pursuant to the immediately following sentence, if any term or provision of this License pertaining to Human Rights Laws or Human Rights Principles is deemed invalid, illegal, or unenforceable against Licensee by a court of competent jurisdiction, all rights in the Software granted to Licensee shall be deemed null and void as between Licensor and Licensee. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by Laws, the court may modify this License to affect the original purpose that the Software be used in compliance with Human Rights Principles and Human Rights Laws as closely as possible. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party. 30 | 31 | * Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES “AS IS,” WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM. 32 | 33 | This Hippocratic License is an Ethical Source license (https://ethicalsource.dev) and is offered for use by licensors and licensees at their own risk, on an “AS IS” basis, and with no warranties express or implied, to the maximum extent permitted by Laws. 34 | -------------------------------------------------------------------------------- /example/dist/index.js: -------------------------------------------------------------------------------- 1 | // modules are defined as an array 2 | // [ module function, map of requires ] 3 | // 4 | // map of requires is short require name -> numeric require 5 | // 6 | // anything defined in a previous bundle is accessed via the 7 | // orig method which is the require for previous bundles 8 | parcelRequire = (function (modules, cache, entry, globalName) { 9 | // Save the require from previous bundle to this closure if any 10 | var previousRequire = typeof parcelRequire === 'function' && parcelRequire; 11 | var nodeRequire = typeof require === 'function' && require; 12 | 13 | function newRequire(name, jumped) { 14 | if (!cache[name]) { 15 | if (!modules[name]) { 16 | // if we cannot find the module within our internal map or 17 | // cache jump to the current global require ie. the last bundle 18 | // that was added to the page. 19 | var currentRequire = typeof parcelRequire === 'function' && parcelRequire; 20 | if (!jumped && currentRequire) { 21 | return currentRequire(name, true); 22 | } 23 | 24 | // If there are other bundles on this page the require from the 25 | // previous one is saved to 'previousRequire'. Repeat this as 26 | // many times as there are bundles until the module is found or 27 | // we exhaust the require chain. 28 | if (previousRequire) { 29 | return previousRequire(name, true); 30 | } 31 | 32 | // Try the node require function if it exists. 33 | if (nodeRequire && typeof name === 'string') { 34 | return nodeRequire(name); 35 | } 36 | 37 | var err = new Error('Cannot find module \'' + name + '\''); 38 | err.code = 'MODULE_NOT_FOUND'; 39 | throw err; 40 | } 41 | 42 | localRequire.resolve = resolve; 43 | localRequire.cache = {}; 44 | 45 | var module = cache[name] = new newRequire.Module(name); 46 | 47 | modules[name][0].call(module.exports, localRequire, module, module.exports, this); 48 | } 49 | 50 | return cache[name].exports; 51 | 52 | function localRequire(x){ 53 | return newRequire(localRequire.resolve(x)); 54 | } 55 | 56 | function resolve(x){ 57 | return modules[name][1][x] || x; 58 | } 59 | } 60 | 61 | function Module(moduleName) { 62 | this.id = moduleName; 63 | this.bundle = newRequire; 64 | this.exports = {}; 65 | } 66 | 67 | newRequire.isParcelRequire = true; 68 | newRequire.Module = Module; 69 | newRequire.modules = modules; 70 | newRequire.cache = cache; 71 | newRequire.parent = previousRequire; 72 | newRequire.register = function (id, exports) { 73 | modules[id] = [function (require, module) { 74 | module.exports = exports; 75 | }, {}]; 76 | }; 77 | 78 | var error; 79 | for (var i = 0; i < entry.length; i++) { 80 | try { 81 | newRequire(entry[i]); 82 | } catch (e) { 83 | // Save first error but execute all entries 84 | if (!error) { 85 | error = e; 86 | } 87 | } 88 | } 89 | 90 | if (entry.length) { 91 | // Expose entry point to Node, AMD or browser globals 92 | // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js 93 | var mainExports = newRequire(entry[entry.length - 1]); 94 | 95 | // CommonJS 96 | if (typeof exports === "object" && typeof module !== "undefined") { 97 | module.exports = mainExports; 98 | 99 | // RequireJS 100 | } else if (typeof define === "function" && define.amd) { 101 | define(function () { 102 | return mainExports; 103 | }); 104 | 105 | //