Refactor physics

This commit is contained in:
schmelczerandras 2020-10-05 20:30:42 +02:00
parent 46a48e7c15
commit c5d97eeea6
40 changed files with 484 additions and 791 deletions

View file

@ -1,10 +1,8 @@
import { glMatrix } from 'gl-matrix';
import { Game } from './scripts/game';
import { Random } from './scripts/helper/random';
import './styles/main.scss';
glMatrix.setMatrixArrayType(Array);
Random.seed = 42;
const main = async () => {
try {

View file

@ -10,7 +10,13 @@ import {
renderNoise,
WrapOptions,
} from 'sdf-2d';
import { broadcastCommands, SetViewAreaActionCommand, TransportEvents } from 'shared';
import {
broadcastCommands,
prettyPrint,
settings,
SetViewAreaActionCommand,
TransportEvents,
} from 'shared';
import io from 'socket.io-client';
import { KeyboardListener } from './commands/generators/keyboard-listener';
import { MouseListener } from './commands/generators/mouse-listener';
@ -20,10 +26,8 @@ import { RenderCommand } from './commands/types/render';
import { StepCommand } from './commands/types/step';
import { Configuration } from './config/configuration';
import { DeltaTimeCalculator } from './helper/delta-time-calculator';
import { prettyPrint } from './helper/pretty-print';
import { rgb } from './helper/rgb';
import { GameObjectContainer } from './objects/game-object-container';
import { settings } from './settings';
import { BlobShape } from './shapes/blob-shape';
import { deserialize } from './transport/deserialize';
@ -69,7 +73,7 @@ export class Game {
}
private async setupRenderer(): Promise<void> {
const noiseTexture = await renderNoise([1024, 1], 60, 1 / 8);
const noiseTexture = await renderNoise([512, 1], 50, 1 / 10);
this.renderer = await compile(
this.canvas,
@ -96,7 +100,7 @@ export class Game {
},
],
{
shadowTraceCount: 12,
shadowTraceCount: 16,
paletteSize: 10,
enableStopwatch: true,
}

View file

@ -1,4 +0,0 @@
export const clamp = (value: number, min: number, max: number): number =>
Math.min(max, Math.max(min, value));
export const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));

View file

@ -1,3 +0,0 @@
export function last<T>(a: Array<T>): T | null {
return a.length > 0 ? a[a.length - 1] : null;
}

View file

@ -1 +0,0 @@
export const mix = (from: number, to: number, q: number) => from + (to - from) * q;

View file

@ -1,4 +0,0 @@
export const prettyPrint = (o: any): string =>
JSON.stringify(o, (_, v) => (v.toFixed ? Number(v.toFixed(3)) : v), ' ')
.replace(/("|,|{|^\n)/g, '')
.replace(/(\W*}\n?)+/g, '\n\n');

View file

@ -1,18 +0,0 @@
// src
// https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript
// Mulberry32
export abstract class Random {
private static _seed = Math.random();
public static set seed(value: number) {
Random._seed = value;
}
public static getRandom(): number {
let t = (Random._seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
}

View file

@ -1,3 +0,0 @@
import { vec2 } from 'gl-matrix';
export const rotate90Deg = (vec: vec2): vec2 => vec2.fromValues(-vec.y, vec.x);

View file

@ -1 +0,0 @@
export const toPercent = (value: number) => `${Math.round(value * 100)}%`;

View file

@ -1,3 +0,0 @@
export const wait = (ms: number): Promise<void> => {
return new Promise<void>((resolve, _) => setTimeout(resolve, ms));
};

View file

@ -1,181 +0,0 @@
/*import { vec2 } from 'gl-matrix';
import { Flashlight } from 'sdf-2d';
import { rgb } from '../../helper/rgb';
import { IGame } from '../../i-game';
import { BoundingBoxBase } from '../../physics/bounds/bounding-box-base';
import { BoundingCircle } from '../../physics/bounds/bounding-circle';
import { PhysicsCircle } from '../../physics/bounds/physics-circle';
import { PhysicalGameObject } from '../../physics/physical-object';
import { Physics } from '../../physics/physics';
import { settings } from '../../settings';
import { BlobShape } from '../../shapes/blob-shape';
import { Projectile } from './projectile';
export class Character extends PhysicalGameObject {
protected head: PhysicsCircle;
protected leftFoot: PhysicsCircle;
protected rightFoot: PhysicsCircle;
private keysDown: Set<string> = new Set();
private flashlight = new Flashlight(
vec2.create(),
rgb(1, 0.6, 0.45),
0.15,
vec2.fromValues(1, 0),
50
);
private static walkForce = 0.005;
private static jumpForce = 10;
private shape = new BlobShape();
private boundingCircle = new BoundingCircle(this, vec2.create(), 50);
private readonly headOffset = vec2.fromValues(0, 40);
private readonly leftFootOffset = vec2.fromValues(-20, -10);
private readonly rightFootOffset = vec2.fromValues(20, -10);
constructor(physics: Physics, private game: IGame) {
super(physics, true);
this.addCommandExecutor(RenderCommand, this.draw.bind(this));
this.addCommandExecutor(TeleportToCommand, (c) => this.setPosition(c.position));
this.addCommandExecutor(KeyDownCommand, (c) => this.keysDown.add(c.key));
this.addCommandExecutor(KeyUpCommand, (c) => this.keysDown.delete(c.key));
this.addCommandExecutor(StepCommand, this.stepHandler.bind(this));
this.addCommandExecutor(CursorMoveCommand, this.directLight.bind(this));
this.addCommandExecutor(PrimaryActionCommand, this.spawnProjectile.bind(this));
this.addCommandExecutor(SwipeCommand, (c) => {
//this.tryMoving(vec2.multiply(vec2.create(), c.delta, this.game.viewArea.size));
});
this.head = new PhysicsCircle(physics, this, vec2.clone(this.headOffset), 50);
this.leftFoot = new PhysicsCircle(physics, this, vec2.clone(this.leftFootOffset), 20);
this.rightFoot = new PhysicsCircle(
physics,
this,
vec2.clone(this.rightFootOffset),
20
);
this.shape.setCircles([this.head, this.leftFoot, this.rightFoot]);
this.addToPhysics(true);
}
public distance(target: vec2): number {
return this.shape.minDistance(target);
}
private draw(c: RenderCommand) {
c.renderer.addDrawable(this.shape);
c.renderer.addDrawable(this.flashlight);
}
private directLight(e: CursorMoveCommand) {
const pos = this.game.displayToWorldCoordinates(e.position);
vec2.sub(pos, pos, this.head.center);
this.flashlight.direction = pos;
}
private spawnProjectile(e: PrimaryActionCommand) {
const pos = this.game.displayToWorldCoordinates(e.position);
const direction = vec2.sub(vec2.create(), pos, this.head.center);
vec2.normalize(direction, direction);
const start = vec2.add(
vec2.create(),
this.head.center,
vec2.scale(vec2.create(), direction, this.head.radius)
);
vec2.scale(direction, direction, 5);
const projectile = new Projectile(this.game, this.physics, start, direction);
this.game.addObject(projectile);
}
public get position(): vec2 {
return this.head.center;
}
public getBoundingCircles(): Array<BoundingCircle> {
return [this.boundingCircle];
}
public getBoundingBox(): BoundingBoxBase {
return this.head.boundingBox;
}
private setPosition(value: vec2) {
this.head.center = vec2.clone(value);
this.leftFoot.center = vec2.clone(value);
this.rightFoot.center = vec2.clone(value);
}
public stepHandler(c: StepCommand) {
const deltaTime = c.deltaTimeInMiliseconds;
const isAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne;
const up =
~~(
!isAirborne &&
(this.keysDown.has('w') || this.keysDown.has('arrowup') || this.keysDown.has(' '))
) * Character.jumpForce;
const down = ~~(
!isAirborne &&
(this.keysDown.has('s') || this.keysDown.has('arrowdown'))
);
const left =
~~(this.keysDown.has('a') || this.keysDown.has('arrowleft')) *
Character.walkForce *
deltaTime;
const right =
~~(this.keysDown.has('d') || this.keysDown.has('arrowright')) *
Character.walkForce *
deltaTime;
const movementForce = vec2.fromValues(right - left, up - down);
this.head.applyForce(movementForce, deltaTime);
this.head.applyForce(settings.gravitationalForce, deltaTime);
const bodyCenter = vec2.sub(vec2.create(), this.head.center, this.headOffset);
const leftFootPositon = vec2.add(vec2.create(), bodyCenter, this.leftFootOffset);
const rightFootPositon = vec2.add(vec2.create(), bodyCenter, this.rightFootOffset);
const leftFootDelta = vec2.sub(vec2.create(), this.leftFoot.center, leftFootPositon);
const rightFootDelta = vec2.sub(
vec2.create(),
this.rightFoot.center,
rightFootPositon
);
vec2.scale(leftFootDelta, leftFootDelta, 0.0006);
vec2.scale(rightFootDelta, rightFootDelta, 0.0006);
this.head.applyForce(leftFootDelta, deltaTime);
this.head.applyForce(rightFootDelta, deltaTime);
vec2.scale(leftFootDelta, leftFootDelta, -0.5);
vec2.scale(rightFootDelta, rightFootDelta, -0.5);
this.leftFoot.applyForce(movementForce, deltaTime);
this.rightFoot.applyForce(movementForce, deltaTime);
this.leftFoot.applyForce(leftFootDelta, deltaTime);
this.rightFoot.applyForce(rightFootDelta, deltaTime);
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
this.head.step(deltaTime);
this.leftFoot.step(deltaTime);
this.rightFoot.step(deltaTime);
this.flashlight.center = vec2.add(
vec2.create(),
this.head.center,
vec2.fromValues(0, 0)
);
}
}
*/

View file

@ -1,55 +0,0 @@
/*import { vec2 } from 'gl-matrix';
import { Circle } from 'sdf-2d';
import { RenderCommand } from '../../commands/render';
import { StepCommand } from '../../commands/step';
import { IGame } from '../../i-game';
import { BoundingBoxBase } from '../../physics/bounds/bounding-box-base';
import { BoundingCircle } from '../../physics/bounds/bounding-circle';
import { PhysicsCircle } from '../../physics/bounds/physics-circle';
import { PhysicalGameObject } from '../../physics/physical-object';
import { Physics } from '../../physics/physics';
import { settings } from '../../settings';
export class Projectile extends PhysicalGameObject {
private shape: Circle;
private bounding: PhysicsCircle;
constructor(private game: IGame, physics: Physics, position: vec2, velocity: vec2) {
super(physics, true);
this.shape = new Circle(position, 20);
this.bounding = new PhysicsCircle(physics, this, position, 20);
this.bounding.applyForce(velocity, 100);
this.addCommandExecutor(RenderCommand, this.draw.bind(this));
this.addCommandExecutor(StepCommand, this.step.bind(this));
this.addToPhysics(true);
}
private draw(c: RenderCommand) {
c.renderer.addDrawable(this.shape);
}
private step(c: StepCommand) {
this.bounding.applyForce(settings.gravitationalForce, c.deltaTimeInMiliseconds);
if (this.bounding.step(c.deltaTimeInMiliseconds)) {
this.game.removeObject(this);
this.physics.removeDynamicBoundingBox(this.getBoundingBox());
}
}
public getBoundingCircles(): BoundingCircle[] {
return [this.bounding];
}
public getBoundingBox(): BoundingBoxBase {
return this.bounding.boundingBox;
}
public distance(target: vec2): number {
return this.bounding.distance(target);
}
}
*/

View file

@ -1,74 +0,0 @@
/*import { vec2 } from 'gl-matrix';
import { clamp } from '../../helper/clamp';
import { settings } from '../../settings';
import { PhysicalGameObject } from '../physical-object';
import { Physics } from '../physics';
import { BoundingCircle } from './bounding-circle';
export class PhysicsCircle extends BoundingCircle {
private velocity = vec2.create();
private _isAirborne = true;
public get isAirborne(): boolean {
return this._isAirborne;
}
constructor(
private readonly physics: Physics,
owner: PhysicalGameObject,
center: vec2,
radius: number
) {
super(owner, center, radius);
}
public resetVelocity() {
this.velocity = vec2.create();
}
public applyForce(force: vec2, timeInMilliseconds: number) {
vec2.add(
this.velocity,
this.velocity,
vec2.scale(vec2.create(), force, timeInMilliseconds)
);
vec2.set(
this.velocity,
clamp(this.velocity.x, -settings.maxVelocityX, settings.maxVelocityX),
clamp(this.velocity.y, -settings.maxVelocityY, settings.maxVelocityY)
);
}
public step(timeInMilliseconds: number): boolean {
vec2.scale(
this.velocity,
this.velocity,
Math.pow(settings.velocityAttenuation, timeInMilliseconds)
);
const distance = vec2.scale(vec2.create(), this.velocity, timeInMilliseconds);
const distanceLength = vec2.length(distance);
const stepCount = Math.ceil(distanceLength / settings.physicsMaxStep);
vec2.scale(distance, distance, 1 / stepCount);
let wasHit = false;
for (let i = 0; i < stepCount; i++) {
const { normal, tangent, hitSurface } = this.physics.tryMovingDynamicCircle(
this,
distance
);
if (hitSurface) {
vec2.scale(this.velocity, tangent, vec2.dot(tangent, this.velocity));
wasHit = true;
}
this._isAirborne = !(
hitSurface && vec2.dot(normal, settings.gravitationalForce) < 0
);
}
return wasHit;
}
}
*/

View file

@ -1,23 +0,0 @@
/*import { vec2 } from 'gl-matrix';
import { GameObject } from '../objects/game-object';
import { BoundingBoxBase } from './bounds/bounding-box-base';
import { Physics } from './physics';
export abstract class PhysicalGameObject extends GameObject {
public abstract getBoundingBox(): BoundingBoxBase;
public abstract distance(target: vec2): number;
public readonly isInverted: boolean = false;
constructor(protected physics: Physics, public readonly canCollide: boolean) {
super();
}
protected addToPhysics(isDynamic: boolean) {
if (isDynamic) {
this.physics.addDynamicBoundingBox(this.getBoundingBox());
} else {
this.physics.addStaticBoundingBox(this.getBoundingBox());
}
}
}
*/

View file

@ -1,121 +0,0 @@
/*import { vec2 } from 'gl-matrix';
import { rotate90Deg } from '../helper/rotate-90-deg';
import { settings } from '../settings';
import { BoundingBoxBase } from './bounds/bounding-box-base';
import { BoundingCircle } from './bounds/bounding-circle';
import { ImmutableBoundingBox } from './bounds/immutable-bounding-box';
import { BoundingBoxList } from './containers/bounding-box-list';
import { BoundingBoxTree } from './containers/bounding-box-tree';
export class Physics {
private isTreeInitialized = false;
private staticBoundingBoxesWaitList = [];
private staticBoundingBoxes = new BoundingBoxTree();
private dynamicBoundingBoxes = new BoundingBoxList();
public addStaticBoundingBox(boundingBox: ImmutableBoundingBox) {
if (!this.isTreeInitialized) {
this.staticBoundingBoxesWaitList.push(boundingBox);
} else {
this.staticBoundingBoxes.insert(boundingBox);
}
}
public addDynamicBoundingBox(boundingBox: BoundingBoxBase) {
this.dynamicBoundingBoxes.insert(boundingBox);
}
public removeDynamicBoundingBox(boundingBox: BoundingBoxBase) {
this.dynamicBoundingBoxes.remove(boundingBox);
}
public tryMovingDynamicCircle(
circle: BoundingCircle,
delta: vec2
): {
realDelta: vec2;
hitSurface: boolean;
normal?: vec2;
tangent?: vec2;
} {
circle.center = vec2.add(circle.center, circle.center, delta);
const intersecting = this.findIntersecting(circle.boundingBox).filter(
(b) =>
b.owner !== circle.owner && circle.areIntersecting(b.owner) && b.owner.canCollide
);
if (intersecting.length === 0) {
return {
realDelta: delta,
hitSurface: false,
};
}
const points = circle.getPerimeterPoints(settings.hitDetectionCirclePointCount);
const distancesOfPoints = points
.map((point) => ({
point,
closest: intersecting
.map((i) => ({
inverted: i.isInverted,
distance: i.owner.distance(point),
}))
.sort((a, b) => a.distance - b.distance)[0],
}))
.filter((i) => i.closest);
const distancesOfIntersectingPoints = distancesOfPoints.filter(
(d) =>
(d.closest.distance > 0 && d.closest.inverted) ||
(d.closest.distance < 0 && !d.closest.inverted)
);
if (distancesOfIntersectingPoints.length === 0) {
return {
realDelta: delta,
hitSurface: false,
};
}
const deltas = distancesOfIntersectingPoints.map((pointDistance) => {
vec2.subtract(pointDistance.point, circle.center, pointDistance.point);
vec2.normalize(pointDistance.point, pointDistance.point);
vec2.scale(
pointDistance.point,
pointDistance.point,
(pointDistance.closest.inverted ? 1 : -1) * pointDistance.closest.distance
);
return pointDistance.point;
});
const approxNormal = deltas.reduce(
(sum, current) => vec2.add(sum, sum, current),
vec2.create()
);
vec2.scale(approxNormal, approxNormal, 1 / deltas.length);
circle.center = vec2.add(circle.center, circle.center, approxNormal);
return {
realDelta: delta,
hitSurface: true,
normal: vec2.normalize(approxNormal, approxNormal),
tangent: rotate90Deg(approxNormal),
};
}
public findIntersecting(box: BoundingBoxBase): Array<BoundingBoxBase> {
return [
...this.staticBoundingBoxes.findIntersecting(box),
...this.dynamicBoundingBoxes.findIntersecting(box),
];
}
public start() {
this.staticBoundingBoxes.build(this.staticBoundingBoxesWaitList);
this.isTreeInitialized = true;
}
}
*/

View file

@ -1,12 +0,0 @@
import { vec2 } from 'gl-matrix';
export const settings = {
lightCutoffDistance: 600,
hitDetectionCirclePointCount: 32,
hitDetectionMaxOverlap: 0.01,
physicsMaxStep: 5,
gravitationalForce: vec2.fromValues(0, -0.015),
maxVelocityX: 1.5,
maxVelocityY: 8,
velocityAttenuation: 0.99,
};

View file

@ -1,7 +0,0 @@
export abstract class Typed {
public abstract get type(): string;
public toJSON() {
return { type: this.type, ...this };
}
}