Add files
This commit is contained in:
commit
77bde04db3
97 changed files with 10327 additions and 0 deletions
1
.eslintignore
Normal file
1
.eslintignore
Normal file
|
|
@ -0,0 +1 @@
|
|||
**/*.js
|
||||
29
.eslintrc.json
Normal file
29
.eslintrc.json
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"root": true,
|
||||
"env": {
|
||||
"browser": true,
|
||||
"es2020": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/eslint-recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier",
|
||||
"prettier/@typescript-eslint"
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 11,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["unused-imports", "@typescript-eslint", "prettier"],
|
||||
"rules": {
|
||||
"prettier/prettier": "error",
|
||||
"no-unused-vars": "off",
|
||||
"unused-imports/no-unused-imports-ts": "error",
|
||||
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }],
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "off"
|
||||
}
|
||||
}
|
||||
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
*.psd filter=lfs diff=lfs merge=lfs -text
|
||||
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
dist
|
||||
node_modules
|
||||
package-lock.json
|
||||
7
.prettierrc
Normal file
7
.prettierrc
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 90,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
8
.vscode/settings.json
vendored
Normal file
8
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"typescript.tsdk": "node_modules\\typescript\\lib",
|
||||
"editor.tabSize": 2,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.organizeImports": true
|
||||
}
|
||||
}
|
||||
7839
build/main-bundle.js
Normal file
7839
build/main-bundle.js
Normal file
File diff suppressed because it is too large
Load diff
0
build/src/game.d.ts
vendored
Normal file
0
build/src/game.d.ts
vendored
Normal file
7
build/src/graphics/drawables/i-drawable-descriptor.d.ts
vendored
Normal file
7
build/src/graphics/drawables/i-drawable-descriptor.d.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { IDrawable } from './i-drawable';
|
||||
export interface IDrawableDescriptor {
|
||||
uniformName: string;
|
||||
countMacroName: string;
|
||||
shaderCombinationSteps: Array<number>;
|
||||
readonly empty: IDrawable;
|
||||
}
|
||||
5
build/src/graphics/drawables/i-drawable.d.ts
vendored
Normal file
5
build/src/graphics/drawables/i-drawable.d.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { vec2, mat2d } from 'gl-matrix';
|
||||
export interface IDrawable {
|
||||
distance(target: vec2): number;
|
||||
serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void;
|
||||
}
|
||||
14
build/src/graphics/drawables/lights/circle-light.d.ts
vendored
Normal file
14
build/src/graphics/drawables/lights/circle-light.d.ts
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { mat2d, vec2, vec3 } from 'gl-matrix';
|
||||
import { IDrawableDescriptor } from '../i-drawable-descriptor';
|
||||
import { ILight } from './i-light';
|
||||
export declare class CircleLight implements ILight {
|
||||
center: vec2;
|
||||
lightDrop: number;
|
||||
color: vec3;
|
||||
lightness: number;
|
||||
static descriptor: IDrawableDescriptor;
|
||||
constructor(center: vec2, lightDrop: number, color: vec3, lightness: number);
|
||||
distance(_: vec2): number;
|
||||
serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void;
|
||||
get value(): vec3;
|
||||
}
|
||||
15
build/src/graphics/drawables/lights/flashlight.d.ts
vendored
Normal file
15
build/src/graphics/drawables/lights/flashlight.d.ts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { mat2d, vec2, vec3 } from 'gl-matrix';
|
||||
import { IDrawableDescriptor } from '../i-drawable-descriptor';
|
||||
import { ILight } from './i-light';
|
||||
export declare class Flashlight implements ILight {
|
||||
center: vec2;
|
||||
direction: vec2;
|
||||
lightDrop: number;
|
||||
color: vec3;
|
||||
lightness: number;
|
||||
static descriptor: IDrawableDescriptor;
|
||||
constructor(center: vec2, direction: vec2, lightDrop: number, color: vec3, lightness: number);
|
||||
distance(_: vec2): number;
|
||||
serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void;
|
||||
get value(): vec3;
|
||||
}
|
||||
2
build/src/graphics/drawables/lights/i-light.d.ts
vendored
Normal file
2
build/src/graphics/drawables/lights/i-light.d.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { IDrawable } from '../i-drawable';
|
||||
export declare type ILight = IDrawable;
|
||||
1
build/src/graphics/graphics-library/compiling/check-program.d.ts
vendored
Normal file
1
build/src/graphics/graphics-library/compiling/check-program.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const checkProgram: (gl: WebGL2RenderingContext, program: WebGLProgram) => void;
|
||||
1
build/src/graphics/graphics-library/compiling/check-shader.d.ts
vendored
Normal file
1
build/src/graphics/graphics-library/compiling/check-shader.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const checkShader: (gl: WebGL2RenderingContext, shader: WebGLShader) => void;
|
||||
3
build/src/graphics/graphics-library/compiling/create-program.d.ts
vendored
Normal file
3
build/src/graphics/graphics-library/compiling/create-program.d.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export declare const createProgram: (gl: WebGL2RenderingContext, vertexShaderSource: string, fragmentShaderSource: string, substitutions: {
|
||||
[name: string]: string;
|
||||
}) => Promise<WebGLProgram>;
|
||||
3
build/src/graphics/graphics-library/compiling/create-shader.d.ts
vendored
Normal file
3
build/src/graphics/graphics-library/compiling/create-shader.d.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export declare const createShader: (gl: WebGL2RenderingContext, type: GLenum, source: string, substitutions: {
|
||||
[name: string]: string;
|
||||
}) => WebGLShader;
|
||||
5
build/src/graphics/graphics-library/frame-buffer/default-frame-buffer.d.ts
vendored
Normal file
5
build/src/graphics/graphics-library/frame-buffer/default-frame-buffer.d.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { FrameBuffer } from './frame-buffer';
|
||||
export declare class DefaultFrameBuffer extends FrameBuffer {
|
||||
constructor(gl: WebGL2RenderingContext);
|
||||
setSize(): boolean;
|
||||
}
|
||||
12
build/src/graphics/graphics-library/frame-buffer/frame-buffer.d.ts
vendored
Normal file
12
build/src/graphics/graphics-library/frame-buffer/frame-buffer.d.ts
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
export declare abstract class FrameBuffer {
|
||||
protected gl: WebGL2RenderingContext;
|
||||
renderScale: number;
|
||||
enableHighDpiRendering: boolean;
|
||||
protected size: vec2;
|
||||
protected frameBuffer: WebGLFramebuffer | null;
|
||||
constructor(gl: WebGL2RenderingContext);
|
||||
bindAndClear(colorInput?: WebGLTexture): void;
|
||||
setSize(): boolean;
|
||||
getSize(): vec2;
|
||||
}
|
||||
10
build/src/graphics/graphics-library/frame-buffer/intermediate-frame-buffer.d.ts
vendored
Normal file
10
build/src/graphics/graphics-library/frame-buffer/intermediate-frame-buffer.d.ts
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { FrameBuffer } from './frame-buffer';
|
||||
export declare class IntermediateFrameBuffer extends FrameBuffer {
|
||||
private frameTexture;
|
||||
private floatLinearEnabled;
|
||||
constructor(gl: WebGL2RenderingContext);
|
||||
get colorTexture(): WebGLTexture;
|
||||
setSize(): boolean;
|
||||
private configureTexture;
|
||||
private configureFrameBuffer;
|
||||
}
|
||||
2
build/src/graphics/graphics-library/helper/enable-extension.d.ts
vendored
Normal file
2
build/src/graphics/graphics-library/helper/enable-extension.d.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export declare const tryEnableExtension: (gl: WebGL2RenderingContext, name: string) => any | null;
|
||||
export declare const enableExtension: (gl: WebGL2RenderingContext, name: string) => any;
|
||||
1
build/src/graphics/graphics-library/helper/get-webgl2-context.d.ts
vendored
Normal file
1
build/src/graphics/graphics-library/helper/get-webgl2-context.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const getWebGl2Context: (canvas: HTMLCanvasElement) => WebGL2RenderingContext;
|
||||
1
build/src/graphics/graphics-library/helper/load-uniform.d.ts
vendored
Normal file
1
build/src/graphics/graphics-library/helper/load-uniform.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const loadUniform: (gl: WebGL2RenderingContext, value: any, type: GLenum, location: WebGLUniformLocation) => any;
|
||||
11
build/src/graphics/graphics-library/helper/stopwatch.d.ts
vendored
Normal file
11
build/src/graphics/graphics-library/helper/stopwatch.d.ts
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
export declare class WebGlStopwatch {
|
||||
private gl;
|
||||
private timerExtension;
|
||||
private timerQuery?;
|
||||
private isReady;
|
||||
private resultsInNanoSeconds?;
|
||||
constructor(gl: WebGL2RenderingContext);
|
||||
start(): void;
|
||||
stop(): void;
|
||||
get resultsInMilliSeconds(): number;
|
||||
}
|
||||
11
build/src/graphics/graphics-library/program/fragment-shader-only-program.d.ts
vendored
Normal file
11
build/src/graphics/graphics-library/program/fragment-shader-only-program.d.ts
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import Program from './program';
|
||||
export declare class FragmentShaderOnlyProgram extends Program {
|
||||
private vao?;
|
||||
constructor(gl: WebGL2RenderingContext, sources: [string, string], substitutions: {
|
||||
[name: string]: string;
|
||||
});
|
||||
initialize(): Promise<void>;
|
||||
bind(): void;
|
||||
draw(): void;
|
||||
private prepareScreenQuad;
|
||||
}
|
||||
10
build/src/graphics/graphics-library/program/i-program.d.ts
vendored
Normal file
10
build/src/graphics/graphics-library/program/i-program.d.ts
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
export interface IProgram {
|
||||
initialize(): Promise<void>;
|
||||
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
|
||||
bindAndSetUniforms(values: {
|
||||
[name: string]: any;
|
||||
}): void;
|
||||
draw(): void;
|
||||
delete(): void;
|
||||
}
|
||||
25
build/src/graphics/graphics-library/program/program.d.ts
vendored
Normal file
25
build/src/graphics/graphics-library/program/program.d.ts
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IProgram } from './i-program';
|
||||
export default abstract class Program implements IProgram {
|
||||
protected gl: WebGL2RenderingContext;
|
||||
protected program?: WebGLProgram;
|
||||
private programPromise;
|
||||
private modelTransform;
|
||||
private readonly ndcToUv;
|
||||
private uniforms;
|
||||
constructor(gl: WebGL2RenderingContext, [vertexShaderSource, fragmentShaderSource]: [string, string], substitutions: {
|
||||
[name: string]: string;
|
||||
});
|
||||
initialize(): Promise<void>;
|
||||
bindAndSetUniforms(values: {
|
||||
[name: string]: any;
|
||||
}): void;
|
||||
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
|
||||
setUniforms(values: {
|
||||
[name: string]: any;
|
||||
}): void;
|
||||
delete(): void;
|
||||
abstract draw(): void;
|
||||
protected bind(): void;
|
||||
private queryUniforms;
|
||||
}
|
||||
20
build/src/graphics/graphics-library/program/uniform-array-autoscaling-program.d.ts
vendored
Normal file
20
build/src/graphics/graphics-library/program/uniform-array-autoscaling-program.d.ts
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawableDescriptor } from '../../drawables/i-drawable-descriptor';
|
||||
import { IProgram } from './i-program';
|
||||
export declare class UniformArrayAutoScalingProgram implements IProgram {
|
||||
private gl;
|
||||
private descriptors;
|
||||
private programs;
|
||||
private current?;
|
||||
private drawingRectangleBottomLeft;
|
||||
private drawingRectangleSize;
|
||||
constructor(gl: WebGL2RenderingContext, shaderSources: [string, string], descriptors: Array<IDrawableDescriptor>);
|
||||
initialize(): Promise<void>;
|
||||
bindAndSetUniforms(uniforms: {
|
||||
[name: string]: any;
|
||||
}): void;
|
||||
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
|
||||
draw(): void;
|
||||
delete(): void;
|
||||
private createProgram;
|
||||
}
|
||||
14
build/src/graphics/i-renderer.d.ts
vendored
Normal file
14
build/src/graphics/i-renderer.d.ts
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawable } from './drawables/i-drawable';
|
||||
import { ILight } from './drawables/lights/i-light';
|
||||
export interface IRenderer {
|
||||
initialize(): Promise<void>;
|
||||
startFrame(deltaTime: DOMHighResTimeStamp): void;
|
||||
finishFrame(): void;
|
||||
drawShape(drawable: IDrawable): void;
|
||||
drawLight(light: ILight): void;
|
||||
drawInfoText(text: string): void;
|
||||
readonly canvasSize: vec2;
|
||||
setViewArea(topLeft: vec2, size: vec2): void;
|
||||
setCursorPosition(position: vec2): void;
|
||||
}
|
||||
9
build/src/graphics/rendering/fps-autoscaler.d.ts
vendored
Normal file
9
build/src/graphics/rendering/fps-autoscaler.d.ts
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { Autoscaler as AutoScaler } from '../../helper/autoscaler';
|
||||
export declare class FpsAutoscaler extends AutoScaler {
|
||||
private timeSinceLastAdjusment;
|
||||
private exponentialDecayedDeltaTime;
|
||||
constructor(setters: {
|
||||
[key: string]: (value: number | boolean) => void;
|
||||
});
|
||||
autoscale(lastDeltaTime: DOMHighResTimeStamp): void;
|
||||
}
|
||||
12
build/src/graphics/rendering/rendering-pass.d.ts
vendored
Normal file
12
build/src/graphics/rendering/rendering-pass.d.ts
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { IDrawable } from '../drawables/i-drawable';
|
||||
import { IDrawableDescriptor } from '../drawables/i-drawable-descriptor';
|
||||
import { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer';
|
||||
export declare class RenderingPass {
|
||||
private frame;
|
||||
private drawables;
|
||||
private program;
|
||||
constructor(gl: WebGL2RenderingContext, shaderSources: [string, string], drawableDescriptors: Array<IDrawableDescriptor>, frame: FrameBuffer);
|
||||
initialize(): Promise<void>;
|
||||
addDrawable(drawable: IDrawable): void;
|
||||
render(commonUniforms: any, inputTexture?: WebGLTexture): void;
|
||||
}
|
||||
18
build/src/graphics/rendering/uniforms-provider.d.ts
vendored
Normal file
18
build/src/graphics/rendering/uniforms-provider.d.ts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
export declare class UniformsProvider {
|
||||
private gl;
|
||||
private scaleWorldLengthToNDC;
|
||||
private transformWorldToNDC;
|
||||
private viewAreaBottomLeft;
|
||||
private worldAreaInView;
|
||||
private squareToAspectRatio;
|
||||
private uvToWorld;
|
||||
private cursorPosition;
|
||||
softShadowsEnabled?: boolean;
|
||||
constructor(gl: WebGL2RenderingContext);
|
||||
getUniforms(uniforms: any): any;
|
||||
private getScreenToWorldTransform;
|
||||
uvToWorldCoordinate(screenUvPosition: vec2): vec2;
|
||||
setViewArea(topLeft: vec2, size: vec2): void;
|
||||
setCursorPosition(position: vec2): void;
|
||||
}
|
||||
27
build/src/graphics/rendering/webgl2-renderer.d.ts
vendored
Normal file
27
build/src/graphics/rendering/webgl2-renderer.d.ts
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawable } from '../drawables/i-drawable';
|
||||
import { ILight } from '../drawables/lights/i-light';
|
||||
import { IRenderer } from '../i-renderer';
|
||||
export declare class WebGl2Renderer implements IRenderer {
|
||||
private canvas;
|
||||
private overlay;
|
||||
private gl;
|
||||
private stopwatch?;
|
||||
private uniformsProvider;
|
||||
private distanceFieldFrameBuffer;
|
||||
private lightingFrameBuffer;
|
||||
private distancePass;
|
||||
private lightingPass;
|
||||
private autoscaler;
|
||||
private initializePromise;
|
||||
constructor(canvas: HTMLCanvasElement, overlay: HTMLElement);
|
||||
initialize(): Promise<void>;
|
||||
drawShape(shape: IDrawable): void;
|
||||
drawLight(light: ILight): void;
|
||||
startFrame(deltaTime: DOMHighResTimeStamp): void;
|
||||
finishFrame(): void;
|
||||
setViewArea(topLeft: vec2, size: vec2): void;
|
||||
setCursorPosition(position: vec2): void;
|
||||
get canvasSize(): vec2;
|
||||
drawInfoText(text: string): void;
|
||||
}
|
||||
27
build/src/graphics/settings.d.ts
vendored
Normal file
27
build/src/graphics/settings.d.ts
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
export declare const settings: {
|
||||
enableHighDpiRendering: boolean;
|
||||
qualityScaling: {
|
||||
targetDeltaTimeInMilliseconds: number;
|
||||
deltaTimeError: number;
|
||||
deltaTimeResponsiveness: number;
|
||||
adjusmentRateInMilliseconds: number;
|
||||
qualityTargets: {
|
||||
distanceRenderScale: number;
|
||||
finalRenderScale: number;
|
||||
softShadowsEnabled: boolean;
|
||||
}[];
|
||||
startingTargetIndex: number;
|
||||
scalingOptions: {
|
||||
additiveIncrease: number;
|
||||
multiplicativeDecrease: number;
|
||||
};
|
||||
};
|
||||
tileMultiplier: number;
|
||||
shaderMacros: {};
|
||||
shaderCombinations: {
|
||||
lineSteps: number[];
|
||||
blobSteps: number[];
|
||||
circleLightSteps: number[];
|
||||
flashlightSteps: number[];
|
||||
};
|
||||
};
|
||||
11
build/src/helper/array.d.ts
vendored
Normal file
11
build/src/helper/array.d.ts
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
declare global {
|
||||
interface Array<T> {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
interface Float32Array {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
}
|
||||
export declare const applyArrayPlugins: () => void;
|
||||
17
build/src/helper/autoscaler.d.ts
vendored
Normal file
17
build/src/helper/autoscaler.d.ts
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export declare class Autoscaler {
|
||||
private setters;
|
||||
private targets;
|
||||
private scalingOptions;
|
||||
private index;
|
||||
constructor(setters: {
|
||||
[key: string]: (value: number | boolean) => void;
|
||||
}, targets: Array<{
|
||||
[key: string]: number | boolean;
|
||||
}>, startingIndex: number, scalingOptions: {
|
||||
additiveIncrease: number;
|
||||
multiplicativeDecrease: number;
|
||||
});
|
||||
increase(): void;
|
||||
decrease(): void;
|
||||
private applyScaling;
|
||||
}
|
||||
2
build/src/helper/clamp.d.ts
vendored
Normal file
2
build/src/helper/clamp.d.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export declare const clamp: (value: number, min: number, max: number) => number;
|
||||
export declare const clamp01: (value: number) => number;
|
||||
1
build/src/helper/exponential-decay.d.ts
vendored
Normal file
1
build/src/helper/exponential-decay.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const exponentialDecay: (accumulator: number, nextValue: number, biasOfNextValue: number) => number;
|
||||
1
build/src/helper/get-combinations.d.ts
vendored
Normal file
1
build/src/helper/get-combinations.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const getCombinations: (values: Array<Array<number>>) => Array<Array<number>>;
|
||||
1
build/src/helper/last.d.ts
vendored
Normal file
1
build/src/helper/last.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare function last<T>(a: Array<T>): T | null;
|
||||
1
build/src/helper/mix.d.ts
vendored
Normal file
1
build/src/helper/mix.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const mix: (from: number, to: number, q: number) => number;
|
||||
5
build/src/helper/random.d.ts
vendored
Normal file
5
build/src/helper/random.d.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export declare abstract class Random {
|
||||
private static _seed;
|
||||
static set seed(value: number);
|
||||
static getRandom(): number;
|
||||
}
|
||||
2
build/src/helper/rotate-90-deg.d.ts
vendored
Normal file
2
build/src/helper/rotate-90-deg.d.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
export declare const rotate90Deg: (vec: vec2) => vec2;
|
||||
1
build/src/helper/timing.d.ts
vendored
Normal file
1
build/src/helper/timing.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare function timeIt(interval?: number): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
|
||||
1
build/src/helper/to-percent.d.ts
vendored
Normal file
1
build/src/helper/to-percent.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const toPercent: (value: number) => string;
|
||||
1
build/src/helper/wait-while-false.d.ts
vendored
Normal file
1
build/src/helper/wait-while-false.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const waitWhileFalse: (body: () => boolean) => Promise<void>;
|
||||
1
build/src/helper/wait.d.ts
vendored
Normal file
1
build/src/helper/wait.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export declare const wait: (ms: number) => Promise<void>;
|
||||
1
build/src/main.d.ts
vendored
Normal file
1
build/src/main.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
24
custom.d.ts
vendored
Normal file
24
custom.d.ts
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
declare module '*.glsl' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
/*
|
||||
declare module '*.png' {
|
||||
import { ResponsiveImage } from 'src/framework/model/misc';
|
||||
const content: ResponsiveImage;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.jpg' {
|
||||
import { ResponsiveImage } from 'src/framework/model/misc';
|
||||
const content: ResponsiveImage;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.jpeg' {
|
||||
import { ResponsiveImage } from 'src/framework/model/misc';
|
||||
const content: ResponsiveImage;
|
||||
export default content;
|
||||
}
|
||||
*/
|
||||
50
package.json
Normal file
50
package.json
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
{
|
||||
"name": "sdf-2d-gl",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"start": "webpack-dev-server --mode development",
|
||||
"lint": "npx eslint --fix \"src/**/*.ts\" && npx prettier --write \"src/**/*.ts\"",
|
||||
"build": "webpack && find dist -type f -not -name '*.html' | xargs rm"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "András Schmelczer",
|
||||
"postcss": {
|
||||
"plugins": {
|
||||
"autoprefixer": {}
|
||||
}
|
||||
},
|
||||
"browserslist": [
|
||||
"defaults"
|
||||
],
|
||||
"sideEffects": [
|
||||
"*.scss"
|
||||
],
|
||||
"main": "./dist/sdf-2d-gl.js",
|
||||
"types": "./dist/sdf-2d-gl.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"optimization": {
|
||||
"usedExports": true
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/gl-matrix": "^2.4.5",
|
||||
"@typescript-eslint/eslint-plugin": "^3.9.1",
|
||||
"@typescript-eslint/parser": "^3.9.1",
|
||||
"eslint": "^7.2.0",
|
||||
"eslint-config-prettier": "^6.11.0",
|
||||
"eslint-plugin-import": "^2.21.2",
|
||||
"eslint-plugin-prettier": "^3.1.4",
|
||||
"eslint-plugin-unused-imports": "^0.1.3",
|
||||
"gl-matrix": "^3.3.0",
|
||||
"prettier": "^2.0.5",
|
||||
"raw-loader": "^4.0.1",
|
||||
"resolve-url-loader": "^3.1.1",
|
||||
"terser-webpack-plugin": "^2.3.5",
|
||||
"ts-loader": "^8.0.1",
|
||||
"typescript": "^3.8.3",
|
||||
"webpack": "^4.43.0",
|
||||
"webpack-cli": "^3.3.12",
|
||||
"webpack-dev-server": "^3.10.3"
|
||||
}
|
||||
}
|
||||
121
src/game.ts
Normal file
121
src/game.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
export class Game implements IGame {
|
||||
public readonly objects = new Objects();
|
||||
public readonly physics = new Physics();
|
||||
public readonly camera = new Camera();
|
||||
private previousTime?: DOMHighResTimeStamp = null;
|
||||
private previousFpsValues: Array<number> = [];
|
||||
private infoText = new InfoText();
|
||||
private character: Character;
|
||||
private renderer: IRenderer;
|
||||
private initializeRendererPromise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
const canvas: HTMLCanvasElement = document.querySelector('canvas#main');
|
||||
const overlay: HTMLElement = document.querySelector('#overlay');
|
||||
|
||||
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
|
||||
|
||||
new CommandBroadcaster(
|
||||
[
|
||||
new KeyboardListener(document.body),
|
||||
new MouseListener(canvas),
|
||||
new TouchListener(canvas),
|
||||
],
|
||||
[this.objects]
|
||||
);
|
||||
|
||||
this.renderer = new WebGl2Renderer(canvas, overlay);
|
||||
this.initializeRendererPromise = this.renderer.initialize();
|
||||
this.initializeScene();
|
||||
this.physics.start();
|
||||
}
|
||||
|
||||
public async start(): Promise<void> {
|
||||
await this.initializeRendererPromise;
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
}
|
||||
|
||||
public addObject(o: GameObject) {
|
||||
this.objects.addObject(o);
|
||||
}
|
||||
|
||||
public get viewArea(): BoundingBoxBase {
|
||||
return this.camera.viewArea;
|
||||
}
|
||||
|
||||
public findIntersecting(box: BoundingBoxBase): Array<BoundingBoxBase> {
|
||||
return this.physics.findIntersecting(box);
|
||||
}
|
||||
|
||||
private initializeScene() {
|
||||
this.objects.addObject(this.infoText);
|
||||
|
||||
const start = createDungeon(this.objects, this.physics);
|
||||
createDungeon(this.objects, this.physics);
|
||||
|
||||
this.character = new Character(this);
|
||||
// this.physics.addDynamicBoundingBox(this.character.boundingBox);
|
||||
this.addObject(this.character);
|
||||
this.addObject(this.camera);
|
||||
let pos: any = localStorage.getItem('character-position');
|
||||
pos = pos ? JSON.parse(pos) : start.from;
|
||||
this.character.sendCommand(new TeleportToCommand(pos));
|
||||
}
|
||||
|
||||
private handleVisibilityChange() {
|
||||
if (!document.hidden) {
|
||||
this.previousTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
@timeIt()
|
||||
private gameLoop(time: DOMHighResTimeStamp) {
|
||||
if (this.previousTime === null) {
|
||||
this.previousTime = time;
|
||||
}
|
||||
|
||||
const deltaTime = time - this.previousTime;
|
||||
this.previousTime = time;
|
||||
this.calculateFps(deltaTime);
|
||||
|
||||
this.objects.sendCommand(new StepCommand(deltaTime));
|
||||
this.camera.sendCommand(new MoveToCommand(this.character.position));
|
||||
|
||||
this.renderer.startFrame(deltaTime);
|
||||
|
||||
this.camera.sendCommand(new BeforeRenderCommand(this.renderer));
|
||||
|
||||
const shouldBeDrawn = this.physics
|
||||
.findIntersecting(this.camera.viewArea)
|
||||
.map((b) => b.shape?.gameObject);
|
||||
|
||||
for (const object of shouldBeDrawn) {
|
||||
object?.sendCommand(new BeforeRenderCommand(this.renderer));
|
||||
object?.sendCommand(new RenderCommand(this.renderer));
|
||||
}
|
||||
|
||||
this.character.sendCommand(new RenderCommand(this.renderer));
|
||||
this.infoText.sendCommand(new RenderCommand(this.renderer));
|
||||
this.renderer.finishFrame();
|
||||
|
||||
localStorage.setItem('character-position', JSON.stringify(this.character.position));
|
||||
window.requestAnimationFrame(this.gameLoop.bind(this));
|
||||
}
|
||||
|
||||
private calculateFps(deltaTime: number) {
|
||||
this.previousFpsValues.push(1000 / deltaTime);
|
||||
if (this.previousFpsValues.length > 30) {
|
||||
this.previousFpsValues.sort();
|
||||
const min = this.previousFpsValues[0];
|
||||
const median = this.previousFpsValues[
|
||||
Math.floor(this.previousFpsValues.length / 2)
|
||||
];
|
||||
|
||||
InfoText.modifyRecord('FPS', { min, median });
|
||||
|
||||
this.previousFpsValues = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
8
src/graphics/drawables/i-drawable-descriptor.ts
Normal file
8
src/graphics/drawables/i-drawable-descriptor.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { IDrawable } from './i-drawable';
|
||||
|
||||
export interface IDrawableDescriptor {
|
||||
uniformName: string;
|
||||
countMacroName: string;
|
||||
shaderCombinationSteps: Array<number>;
|
||||
readonly empty: IDrawable;
|
||||
}
|
||||
6
src/graphics/drawables/i-drawable.ts
Normal file
6
src/graphics/drawables/i-drawable.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { vec2, mat2d } from 'gl-matrix';
|
||||
|
||||
export interface IDrawable {
|
||||
distance(target: vec2): number;
|
||||
serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void;
|
||||
}
|
||||
46
src/graphics/drawables/lights/circle-light.ts
Normal file
46
src/graphics/drawables/lights/circle-light.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { mat2d, vec2, vec3 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
import { IDrawableDescriptor } from '../i-drawable-descriptor';
|
||||
import { ILight } from './i-light';
|
||||
|
||||
export class CircleLight implements ILight {
|
||||
public static descriptor: IDrawableDescriptor = {
|
||||
uniformName: 'circleLights',
|
||||
countMacroName: 'circleLightCount',
|
||||
shaderCombinationSteps: settings.shaderCombinations.circleLightSteps,
|
||||
empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0),
|
||||
};
|
||||
|
||||
constructor(
|
||||
public center: vec2,
|
||||
public lightDrop: number,
|
||||
public color: vec3,
|
||||
public lightness: number
|
||||
) {}
|
||||
|
||||
public distance(_: vec2): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
|
||||
const { uniformName } = CircleLight.descriptor;
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
|
||||
uniforms[uniformName] = [];
|
||||
}
|
||||
|
||||
uniforms[uniformName].push({
|
||||
center: vec2.transformMat2d(vec2.create(), this.center, transform),
|
||||
lightDrop: this.lightDrop,
|
||||
value: this.value,
|
||||
});
|
||||
}
|
||||
|
||||
public get value(): vec3 {
|
||||
return vec3.scale(
|
||||
vec3.create(),
|
||||
vec3.normalize(this.color, this.color),
|
||||
this.lightness
|
||||
);
|
||||
}
|
||||
}
|
||||
50
src/graphics/drawables/lights/flashlight.ts
Normal file
50
src/graphics/drawables/lights/flashlight.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { mat2d, vec2, vec3 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
import { IDrawableDescriptor } from '../i-drawable-descriptor';
|
||||
import { ILight } from './i-light';
|
||||
|
||||
export class Flashlight implements ILight {
|
||||
public static descriptor: IDrawableDescriptor = {
|
||||
uniformName: 'flashlights',
|
||||
countMacroName: 'flashlightCount',
|
||||
shaderCombinationSteps: settings.shaderCombinations.flashlightSteps,
|
||||
empty: new Flashlight(
|
||||
vec2.fromValues(0, 0),
|
||||
vec2.fromValues(0, 0),
|
||||
0,
|
||||
vec3.fromValues(0, 0, 0),
|
||||
0
|
||||
),
|
||||
};
|
||||
|
||||
public constructor(
|
||||
public center: vec2,
|
||||
public direction: vec2,
|
||||
public lightDrop: number,
|
||||
public color: vec3,
|
||||
public lightness: number
|
||||
) {}
|
||||
|
||||
public distance(_: vec2): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
|
||||
const listName = Flashlight.descriptor.uniformName;
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(uniforms, listName)) {
|
||||
uniforms[listName] = [];
|
||||
}
|
||||
|
||||
uniforms[listName].push({
|
||||
center: vec2.transformMat2d(vec2.create(), this.center, transform),
|
||||
direction: this.direction,
|
||||
lightDrop: this.lightDrop,
|
||||
value: this.value,
|
||||
});
|
||||
}
|
||||
|
||||
public get value(): vec3 {
|
||||
return vec3.scale(vec3.create(), this.color, this.lightness);
|
||||
}
|
||||
}
|
||||
3
src/graphics/drawables/lights/i-light.ts
Normal file
3
src/graphics/drawables/lights/i-light.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { IDrawable } from '../i-drawable';
|
||||
|
||||
export type ILight = IDrawable;
|
||||
13
src/graphics/graphics-library/compiling/check-program.ts
Normal file
13
src/graphics/graphics-library/compiling/check-program.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { checkShader } from './check-shader';
|
||||
|
||||
export const checkProgram = (gl: WebGL2RenderingContext, program: WebGLProgram) => {
|
||||
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
|
||||
|
||||
if (!success) {
|
||||
gl.getAttachedShaders(program)?.forEach((s) => {
|
||||
checkShader(gl, s);
|
||||
});
|
||||
|
||||
throw new Error(gl.getProgramInfoLog(program)!);
|
||||
}
|
||||
};
|
||||
7
src/graphics/graphics-library/compiling/check-shader.ts
Normal file
7
src/graphics/graphics-library/compiling/check-shader.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export const checkShader = (gl: WebGL2RenderingContext, shader: WebGLShader) => {
|
||||
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
|
||||
|
||||
if (!success) {
|
||||
throw new Error(gl.getShaderInfoLog(shader)!);
|
||||
}
|
||||
};
|
||||
48
src/graphics/graphics-library/compiling/create-program.ts
Normal file
48
src/graphics/graphics-library/compiling/create-program.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { waitWhileFalse } from '../../../helper/wait-while-false';
|
||||
import { tryEnableExtension } from '../helper/enable-extension';
|
||||
import { checkProgram } from './check-program';
|
||||
import { createShader } from './create-shader';
|
||||
|
||||
export const createProgram = async (
|
||||
gl: WebGL2RenderingContext,
|
||||
vertexShaderSource: string,
|
||||
fragmentShaderSource: string,
|
||||
substitutions: { [name: string]: string }
|
||||
): Promise<WebGLProgram> => {
|
||||
const program = gl.createProgram();
|
||||
|
||||
if (!program) {
|
||||
throw new Error('Could not create program');
|
||||
}
|
||||
|
||||
const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
|
||||
|
||||
const vertexShader = createShader(
|
||||
gl,
|
||||
gl.VERTEX_SHADER,
|
||||
vertexShaderSource,
|
||||
substitutions
|
||||
);
|
||||
gl.attachShader(program, vertexShader);
|
||||
|
||||
const fragmentShader = createShader(
|
||||
gl,
|
||||
gl.FRAGMENT_SHADER,
|
||||
fragmentShaderSource,
|
||||
substitutions
|
||||
);
|
||||
gl.attachShader(program, fragmentShader);
|
||||
|
||||
gl.linkProgram(program);
|
||||
|
||||
if (extension) {
|
||||
const checkCompileStatus = () =>
|
||||
gl.getProgramParameter(program, extension.COMPLETION_STATUS_KHR);
|
||||
|
||||
await waitWhileFalse(checkCompileStatus);
|
||||
}
|
||||
|
||||
checkProgram(gl, program);
|
||||
|
||||
return program;
|
||||
};
|
||||
22
src/graphics/graphics-library/compiling/create-shader.ts
Normal file
22
src/graphics/graphics-library/compiling/create-shader.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
export const createShader = (
|
||||
gl: WebGL2RenderingContext,
|
||||
type: GLenum,
|
||||
source: string,
|
||||
substitutions: { [name: string]: string }
|
||||
): WebGLShader => {
|
||||
source = source.replace(/{(.+)}/gm, (_, name: string): string => {
|
||||
const value = substitutions[name];
|
||||
return Number.isInteger(value) ? `${value}.0` : value;
|
||||
});
|
||||
|
||||
const shader = gl.createShader(type);
|
||||
|
||||
if (!shader) {
|
||||
throw new Error('Could not create shader');
|
||||
}
|
||||
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
|
||||
return shader;
|
||||
};
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { FrameBuffer } from './frame-buffer';
|
||||
|
||||
export class DefaultFrameBuffer extends FrameBuffer {
|
||||
constructor(gl: WebGL2RenderingContext) {
|
||||
super(gl);
|
||||
this.frameBuffer = null;
|
||||
this.setSize();
|
||||
}
|
||||
|
||||
public setSize(): boolean {
|
||||
const hasChanged = super.setSize();
|
||||
if (hasChanged) {
|
||||
this.gl.canvas.width = this.size.x;
|
||||
this.gl.canvas.height = this.size.y;
|
||||
}
|
||||
|
||||
return hasChanged;
|
||||
}
|
||||
}
|
||||
46
src/graphics/graphics-library/frame-buffer/frame-buffer.ts
Normal file
46
src/graphics/graphics-library/frame-buffer/frame-buffer.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
export abstract class FrameBuffer {
|
||||
public renderScale = 1;
|
||||
public enableHighDpiRendering = settings.enableHighDpiRendering;
|
||||
|
||||
protected size = vec2.create();
|
||||
|
||||
// null means the default framebuffer
|
||||
protected frameBuffer: WebGLFramebuffer | null = null;
|
||||
|
||||
constructor(protected gl: WebGL2RenderingContext) {}
|
||||
|
||||
public bindAndClear(colorInput?: WebGLTexture) {
|
||||
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);
|
||||
|
||||
if (colorInput) {
|
||||
this.gl.bindTexture(this.gl.TEXTURE_2D, colorInput);
|
||||
}
|
||||
|
||||
this.gl.viewport(0, 0, this.size.x, this.size.y);
|
||||
this.gl.clearColor(0, 0, 0, 0);
|
||||
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
|
||||
}
|
||||
|
||||
public setSize(): boolean {
|
||||
const realToCssPixels =
|
||||
(this.enableHighDpiRendering ? window.devicePixelRatio : 1) * this.renderScale;
|
||||
|
||||
const canvasWidth = (this.gl.canvas as HTMLCanvasElement).clientWidth;
|
||||
const canvasHeight = (this.gl.canvas as HTMLCanvasElement).clientHeight;
|
||||
|
||||
const displayWidth = Math.floor(canvasWidth * realToCssPixels);
|
||||
const displayHeight = Math.floor(canvasHeight * realToCssPixels);
|
||||
|
||||
const oldSize = vec2.clone(this.getSize());
|
||||
this.size = vec2.fromValues(displayWidth, displayHeight);
|
||||
|
||||
return this.size.x != oldSize.x || this.size.y != oldSize.y;
|
||||
}
|
||||
|
||||
public getSize(): vec2 {
|
||||
return this.size;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import { enableExtension } from '../helper/enable-extension';
|
||||
import { FrameBuffer } from './frame-buffer';
|
||||
|
||||
export class IntermediateFrameBuffer extends FrameBuffer {
|
||||
private frameTexture: WebGLTexture;
|
||||
private floatLinearEnabled = false;
|
||||
|
||||
constructor(gl: WebGL2RenderingContext) {
|
||||
super(gl);
|
||||
|
||||
enableExtension(gl, 'EXT_color_buffer_float');
|
||||
|
||||
try {
|
||||
enableExtension(gl, 'OES_texture_float_linear');
|
||||
this.floatLinearEnabled = true;
|
||||
} catch {
|
||||
// it's okay
|
||||
}
|
||||
|
||||
const texture = this.gl.createTexture();
|
||||
if (!texture) {
|
||||
throw new Error('Could not create texture');
|
||||
}
|
||||
this.frameTexture = texture;
|
||||
this.configureTexture();
|
||||
|
||||
const frameBuffer = this.gl.createFramebuffer();
|
||||
if (!frameBuffer) {
|
||||
throw new Error('Could not create frame buffer');
|
||||
}
|
||||
this.frameBuffer = frameBuffer;
|
||||
this.configureFrameBuffer();
|
||||
|
||||
this.setSize();
|
||||
}
|
||||
|
||||
public get colorTexture(): WebGLTexture {
|
||||
return this.frameTexture;
|
||||
}
|
||||
|
||||
public setSize(): boolean {
|
||||
const hasChanged = super.setSize();
|
||||
if (hasChanged) {
|
||||
this.gl.bindTexture(this.gl.TEXTURE_2D, this.frameTexture);
|
||||
|
||||
this.gl.texImage2D(
|
||||
this.gl.TEXTURE_2D,
|
||||
0,
|
||||
this.gl.RG16F,
|
||||
this.size.x,
|
||||
this.size.y,
|
||||
0,
|
||||
this.gl.RG,
|
||||
this.gl.FLOAT,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
return hasChanged;
|
||||
}
|
||||
|
||||
private configureTexture() {
|
||||
this.gl.bindTexture(this.gl.TEXTURE_2D, this.frameTexture);
|
||||
this.gl.texParameteri(
|
||||
this.gl.TEXTURE_2D,
|
||||
this.gl.TEXTURE_MAG_FILTER,
|
||||
this.floatLinearEnabled ? this.gl.LINEAR : this.gl.NEAREST
|
||||
);
|
||||
this.gl.texParameteri(
|
||||
this.gl.TEXTURE_2D,
|
||||
this.gl.TEXTURE_MIN_FILTER,
|
||||
this.floatLinearEnabled ? this.gl.LINEAR : this.gl.NEAREST
|
||||
);
|
||||
this.gl.texParameteri(
|
||||
this.gl.TEXTURE_2D,
|
||||
this.gl.TEXTURE_WRAP_S,
|
||||
this.gl.CLAMP_TO_EDGE
|
||||
);
|
||||
this.gl.texParameteri(
|
||||
this.gl.TEXTURE_2D,
|
||||
this.gl.TEXTURE_WRAP_T,
|
||||
this.gl.CLAMP_TO_EDGE
|
||||
);
|
||||
}
|
||||
|
||||
private configureFrameBuffer() {
|
||||
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);
|
||||
const attachmentPoint = this.gl.COLOR_ATTACHMENT0;
|
||||
this.gl.framebufferTexture2D(
|
||||
this.gl.FRAMEBUFFER,
|
||||
attachmentPoint,
|
||||
this.gl.TEXTURE_2D,
|
||||
this.frameTexture,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
39
src/graphics/graphics-library/helper/enable-extension.ts
Normal file
39
src/graphics/graphics-library/helper/enable-extension.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
const extensions: Map<string, any> = new Map();
|
||||
|
||||
const printExtensions = () => {
|
||||
const values = {};
|
||||
for (const [k, v] of extensions.entries()) {
|
||||
values[k] = v !== null;
|
||||
}
|
||||
//InfoText.modifyRecord('extensions', values);
|
||||
};
|
||||
|
||||
export const tryEnableExtension = (
|
||||
gl: WebGL2RenderingContext,
|
||||
name: string
|
||||
): any | null => {
|
||||
if (extensions.has(name)) {
|
||||
return extensions.get(name);
|
||||
}
|
||||
|
||||
let extension = null;
|
||||
if (gl.getSupportedExtensions()!.indexOf(name) != -1) {
|
||||
extension = gl.getExtension(name);
|
||||
}
|
||||
|
||||
extensions.set(name, extension);
|
||||
|
||||
printExtensions();
|
||||
|
||||
return extension;
|
||||
};
|
||||
|
||||
export const enableExtension = (gl: WebGL2RenderingContext, name: string): any => {
|
||||
const extension = tryEnableExtension(gl, name);
|
||||
|
||||
if (extension === null) {
|
||||
throw new Error(`Unsupported extension ${name}`);
|
||||
}
|
||||
|
||||
return extension;
|
||||
};
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
export const getWebGl2Context = (canvas: HTMLCanvasElement): WebGL2RenderingContext => {
|
||||
const gl = canvas.getContext('webgl2');
|
||||
|
||||
if (!gl) {
|
||||
throw new Error('WebGl2 is not supported');
|
||||
}
|
||||
|
||||
return gl;
|
||||
};
|
||||
82
src/graphics/graphics-library/helper/load-uniform.ts
Normal file
82
src/graphics/graphics-library/helper/load-uniform.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { mat3, ReadonlyVec3, vec2, vec3 } from 'gl-matrix';
|
||||
|
||||
const loaderMat3 = mat3.create();
|
||||
|
||||
export const loadUniform = (
|
||||
gl: WebGL2RenderingContext,
|
||||
value: any,
|
||||
type: GLenum,
|
||||
location: WebGLUniformLocation
|
||||
): any => {
|
||||
const converters: Map<
|
||||
GLenum,
|
||||
(gl: WebGL2RenderingContext, value: any, location: WebGLUniformLocation) => void
|
||||
> = new Map();
|
||||
{
|
||||
converters.set(WebGL2RenderingContext.FLOAT, (gl, v, l) => {
|
||||
if (v instanceof Array) {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
gl.uniform1fv(l, new Float32Array(v));
|
||||
} else {
|
||||
gl.uniform1f(l, v);
|
||||
}
|
||||
});
|
||||
|
||||
converters.set(WebGL2RenderingContext.FLOAT_VEC2, (gl, v: vec2 | Array<vec2>, l) => {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (v[0] instanceof Array) {
|
||||
const result = new Float32Array(v.length * 2);
|
||||
|
||||
for (let i = 0; i < v.length; i++) {
|
||||
result[2 * i] = (v[i] as Array<number>).x;
|
||||
result[2 * i + 1] = (v[i] as Array<number>).y;
|
||||
}
|
||||
|
||||
gl.uniform2fv(l, result);
|
||||
} else {
|
||||
gl.uniform2fv(l, v as vec2);
|
||||
}
|
||||
});
|
||||
|
||||
converters.set(
|
||||
WebGL2RenderingContext.FLOAT_VEC3,
|
||||
(gl, v: ReadonlyVec3 | Array<vec3>, l) => {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (v[0] instanceof Array) {
|
||||
const result = new Float32Array(v.length * 3);
|
||||
|
||||
for (let i = 0; i < v.length; i++) {
|
||||
result[3 * i] = (v[i] as Array<number>)[0];
|
||||
result[3 * i + 1] = (v[i] as Array<number>)[1];
|
||||
result[3 * i + 2] = (v[i] as Array<number>)[2];
|
||||
}
|
||||
|
||||
gl.uniform3fv(l, result);
|
||||
} else {
|
||||
gl.uniform3fv(l, v as vec3);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
converters.set(WebGL2RenderingContext.FLOAT_MAT3, (gl, v, l) => {
|
||||
gl.uniformMatrix3fv(l, true, mat3.fromMat2d(loaderMat3, v));
|
||||
});
|
||||
|
||||
converters.set(WebGL2RenderingContext.BOOL, (gl, v, l) => gl.uniform1i(l, v));
|
||||
|
||||
if (!converters.has(type)) {
|
||||
throw new Error(`Unimplemented webgl type: ${type}`);
|
||||
}
|
||||
|
||||
converters.get(type)!(gl, value, location);
|
||||
}
|
||||
};
|
||||
49
src/graphics/graphics-library/helper/stopwatch.ts
Normal file
49
src/graphics/graphics-library/helper/stopwatch.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { enableExtension } from './enable-extension';
|
||||
|
||||
// https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query_webgl2/
|
||||
|
||||
export class WebGlStopwatch {
|
||||
private timerExtension: any;
|
||||
private timerQuery?: WebGLQuery;
|
||||
private isReady = true;
|
||||
private resultsInNanoSeconds?: number;
|
||||
|
||||
constructor(private gl: WebGL2RenderingContext) {
|
||||
this.timerExtension = enableExtension(gl, 'EXT_disjoint_timer_query_webgl2');
|
||||
}
|
||||
|
||||
public start() {
|
||||
if (this.isReady) {
|
||||
this.timerQuery = this.gl.createQuery()!;
|
||||
this.gl.beginQuery(this.timerExtension.TIME_ELAPSED_EXT, this.timerQuery);
|
||||
}
|
||||
}
|
||||
|
||||
public stop() {
|
||||
if (this.isReady) {
|
||||
this.gl.endQuery(this.timerExtension.TIME_ELAPSED_EXT);
|
||||
this.isReady = false;
|
||||
}
|
||||
|
||||
const available = this.gl.getQueryParameter(
|
||||
this.timerQuery!,
|
||||
this.gl.QUERY_RESULT_AVAILABLE
|
||||
);
|
||||
const disjoint = this.gl.getParameter(this.timerExtension.GPU_DISJOINT_EXT);
|
||||
|
||||
if (available && !disjoint) {
|
||||
this.resultsInNanoSeconds = this.gl.getQueryParameter(
|
||||
this.timerQuery!,
|
||||
this.gl.QUERY_RESULT
|
||||
);
|
||||
|
||||
//InfoText.modifyRecord('Draw time', `${this.resultsInMilliSeconds.toFixed(2)} ms`);
|
||||
|
||||
this.isReady = true;
|
||||
}
|
||||
}
|
||||
|
||||
public get resultsInMilliSeconds(): number {
|
||||
return this.resultsInNanoSeconds! / 1000 / 1000;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import Program from './program';
|
||||
|
||||
export class FragmentShaderOnlyProgram extends Program {
|
||||
private vao?: WebGLVertexArrayObject;
|
||||
|
||||
constructor(
|
||||
gl: WebGL2RenderingContext,
|
||||
sources: [string, string],
|
||||
substitutions: { [name: string]: string }
|
||||
) {
|
||||
super(gl, sources, substitutions);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
await super.initialize();
|
||||
this.prepareScreenQuad('vertexPosition');
|
||||
}
|
||||
|
||||
public bind() {
|
||||
super.bind();
|
||||
this.gl.bindVertexArray(this.vao!);
|
||||
}
|
||||
|
||||
public draw() {
|
||||
this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
private prepareScreenQuad(attributeName: string) {
|
||||
const positionAttributeLocation = this.gl.getAttribLocation(
|
||||
this.program!,
|
||||
attributeName
|
||||
);
|
||||
|
||||
const positionBuffer = this.gl.createBuffer();
|
||||
|
||||
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
|
||||
this.gl.bufferData(
|
||||
this.gl.ARRAY_BUFFER,
|
||||
new Float32Array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]),
|
||||
this.gl.STATIC_DRAW
|
||||
);
|
||||
const vao = this.gl.createVertexArray();
|
||||
if (!vao) {
|
||||
throw new Error('Could not create vertex array object');
|
||||
}
|
||||
this.vao = vao;
|
||||
|
||||
this.gl.bindVertexArray(this.vao);
|
||||
this.gl.enableVertexAttribArray(positionAttributeLocation);
|
||||
this.gl.vertexAttribPointer(positionAttributeLocation, 2, this.gl.FLOAT, false, 0, 0);
|
||||
}
|
||||
}
|
||||
9
src/graphics/graphics-library/program/i-program.ts
Normal file
9
src/graphics/graphics-library/program/i-program.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
|
||||
export interface IProgram {
|
||||
initialize(): Promise<void>;
|
||||
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
|
||||
bindAndSetUniforms(values: { [name: string]: any }): void;
|
||||
draw(): void;
|
||||
delete(): void;
|
||||
}
|
||||
102
src/graphics/graphics-library/program/program.ts
Normal file
102
src/graphics/graphics-library/program/program.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { mat2d, vec2 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
import { createProgram } from '../compiling/create-program';
|
||||
import { loadUniform } from '../helper/load-uniform';
|
||||
import { IProgram } from './i-program';
|
||||
|
||||
export default abstract class Program implements IProgram {
|
||||
protected program?: WebGLProgram;
|
||||
|
||||
private programPromise: Promise<WebGLProgram>;
|
||||
private modelTransform = mat2d.identity(mat2d.create());
|
||||
private readonly ndcToUv = mat2d.fromValues(0.5, 0, 0, 0.5, 0.5, 0.5);
|
||||
private uniforms: Array<{
|
||||
name: Array<string>;
|
||||
location: WebGLUniformLocation;
|
||||
type: GLenum;
|
||||
}> = [];
|
||||
|
||||
constructor(
|
||||
protected gl: WebGL2RenderingContext,
|
||||
[vertexShaderSource, fragmentShaderSource]: [string, string],
|
||||
substitutions: { [name: string]: string }
|
||||
) {
|
||||
substitutions = { ...settings.shaderMacros, ...substitutions };
|
||||
|
||||
this.programPromise = createProgram(
|
||||
this.gl,
|
||||
vertexShaderSource,
|
||||
fragmentShaderSource,
|
||||
substitutions
|
||||
);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
this.program = await this.programPromise;
|
||||
this.queryUniforms();
|
||||
}
|
||||
|
||||
public bindAndSetUniforms(values: { [name: string]: any }) {
|
||||
this.bind();
|
||||
this.setUniforms({ modelTransform: this.modelTransform, ...values });
|
||||
}
|
||||
|
||||
public setDrawingRectangleUV(bottomLeft: vec2, size: vec2) {
|
||||
mat2d.invert(this.modelTransform, this.ndcToUv);
|
||||
mat2d.translate(this.modelTransform, this.modelTransform, bottomLeft);
|
||||
mat2d.scale(this.modelTransform, this.modelTransform, size);
|
||||
mat2d.multiply(this.modelTransform, this.modelTransform, this.ndcToUv);
|
||||
}
|
||||
|
||||
public setUniforms(values: { [name: string]: any }) {
|
||||
this.uniforms.forEach(({ name, location, type }) => {
|
||||
const value = name.reduce(
|
||||
(prev, prop) => (prev !== null && prop in prev ? prev[prop] : null),
|
||||
values
|
||||
);
|
||||
|
||||
if (value !== null) {
|
||||
loadUniform(this.gl, value, type, location);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public delete() {
|
||||
this.gl.getAttachedShaders(this.program!)?.forEach((s) => this.gl.deleteShader(s));
|
||||
this.gl.deleteProgram(this.program!);
|
||||
}
|
||||
|
||||
public abstract draw(): void;
|
||||
|
||||
protected bind() {
|
||||
this.gl.useProgram(this.program!);
|
||||
}
|
||||
|
||||
private queryUniforms() {
|
||||
const uniformCount = this.gl.getProgramParameter(
|
||||
this.program!,
|
||||
WebGL2RenderingContext.ACTIVE_UNIFORMS
|
||||
);
|
||||
|
||||
for (let i = 0; i < uniformCount; i++) {
|
||||
const glUniform = this.gl.getActiveUniform(this.program!, i)!;
|
||||
|
||||
this.uniforms.push({
|
||||
name: glUniform.name.split(/\[|\]\.|\]|\./).filter((p) => p !== ''),
|
||||
location: this.gl.getUniformLocation(this.program!, glUniform.name)!,
|
||||
type: glUniform.type,
|
||||
});
|
||||
}
|
||||
|
||||
this.uniforms.map((u1) => {
|
||||
const isSingle =
|
||||
this.uniforms.filter((u2) => u2.name.includes(u1.name[0])).length == 1;
|
||||
|
||||
if (u1.name.includes('0') && isSingle) {
|
||||
u1.name = u1.name.slice(0, -1);
|
||||
}
|
||||
|
||||
return u1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
import { mat2d, vec2 } from 'gl-matrix';
|
||||
import { getCombinations } from '../../../helper/get-combinations';
|
||||
import { last } from '../../../helper/last';
|
||||
import { IDrawableDescriptor } from '../../drawables/i-drawable-descriptor';
|
||||
import { FragmentShaderOnlyProgram } from './fragment-shader-only-program';
|
||||
import { IProgram } from './i-program';
|
||||
|
||||
export class UniformArrayAutoScalingProgram implements IProgram {
|
||||
private programs: Array<{
|
||||
program: FragmentShaderOnlyProgram;
|
||||
values: Array<number>;
|
||||
}> = [];
|
||||
|
||||
private current?: FragmentShaderOnlyProgram;
|
||||
private drawingRectangleBottomLeft = vec2.fromValues(0, 0);
|
||||
private drawingRectangleSize = vec2.fromValues(1, 1);
|
||||
|
||||
constructor(
|
||||
private gl: WebGL2RenderingContext,
|
||||
shaderSources: [string, string],
|
||||
private descriptors: Array<IDrawableDescriptor>
|
||||
) {
|
||||
const names = descriptors.map((o) => o.countMacroName);
|
||||
for (const combination of getCombinations(
|
||||
descriptors.map((o) => o.shaderCombinationSteps)
|
||||
)) {
|
||||
this.createProgram(names, combination, shaderSources);
|
||||
}
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
await Promise.all(this.programs.map((p) => p.program.initialize()));
|
||||
}
|
||||
|
||||
public bindAndSetUniforms(uniforms: { [name: string]: any }): void {
|
||||
const values = this.descriptors.map((d) =>
|
||||
uniforms[d.uniformName] ? uniforms[d.uniformName].length : 0
|
||||
);
|
||||
|
||||
const closest = this.programs.find((p) => p.values.every((v, i) => v >= values[i]));
|
||||
|
||||
this.current = closest ? closest.program : last(this.programs)?.program;
|
||||
|
||||
if (closest) {
|
||||
this.descriptors.map((d, i) => {
|
||||
const difference = closest.values[i] - values[i];
|
||||
for (let i = 0; i < difference; i++) {
|
||||
d.empty.serializeToUniforms(uniforms, 0, mat2d.create());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
this.current?.setDrawingRectangleUV(
|
||||
this.drawingRectangleBottomLeft,
|
||||
this.drawingRectangleSize
|
||||
);
|
||||
this.current?.bindAndSetUniforms(uniforms);
|
||||
}
|
||||
|
||||
public setDrawingRectangleUV(bottomLeft: vec2, size: vec2) {
|
||||
this.drawingRectangleBottomLeft = bottomLeft;
|
||||
this.drawingRectangleSize = size;
|
||||
}
|
||||
|
||||
public draw(): void {
|
||||
if (!this.current) {
|
||||
throw new Error('Method bindAndSetUniforms have not been called yet');
|
||||
}
|
||||
|
||||
this.current.draw();
|
||||
}
|
||||
|
||||
public delete(): void {
|
||||
this.programs.forEach((p) => p.program.delete());
|
||||
}
|
||||
|
||||
private createProgram(
|
||||
names: Array<string>,
|
||||
combination: Array<number>,
|
||||
shaderSources: [string, string]
|
||||
): FragmentShaderOnlyProgram {
|
||||
const substitutions = {};
|
||||
names.forEach((v, i) => (substitutions[v] = combination[i].toString()));
|
||||
|
||||
const program = new FragmentShaderOnlyProgram(this.gl, shaderSources, substitutions);
|
||||
|
||||
this.programs.push({
|
||||
program,
|
||||
values: combination,
|
||||
});
|
||||
|
||||
return program;
|
||||
}
|
||||
}
|
||||
18
src/graphics/i-renderer.ts
Normal file
18
src/graphics/i-renderer.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawable } from './drawables/i-drawable';
|
||||
import { ILight } from './drawables/lights/i-light';
|
||||
|
||||
export interface IRenderer {
|
||||
initialize(): Promise<void>;
|
||||
|
||||
startFrame(deltaTime: DOMHighResTimeStamp): void;
|
||||
finishFrame(): void;
|
||||
|
||||
drawShape(drawable: IDrawable): void;
|
||||
drawLight(light: ILight): void;
|
||||
drawInfoText(text: string): void;
|
||||
|
||||
readonly canvasSize: vec2;
|
||||
setViewArea(topLeft: vec2, size: vec2): void;
|
||||
setCursorPosition(position: vec2): void;
|
||||
}
|
||||
45
src/graphics/rendering/fps-autoscaler.ts
Normal file
45
src/graphics/rendering/fps-autoscaler.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { Autoscaler as AutoScaler } from '../../helper/autoscaler';
|
||||
import { exponentialDecay } from '../../helper/exponential-decay';
|
||||
import { settings } from '../settings';
|
||||
|
||||
export class FpsAutoscaler extends AutoScaler {
|
||||
private timeSinceLastAdjusment = 0;
|
||||
private exponentialDecayedDeltaTime = 0.0;
|
||||
|
||||
constructor(setters: { [key: string]: (value: number | boolean) => void }) {
|
||||
super(
|
||||
setters,
|
||||
settings.qualityScaling.qualityTargets,
|
||||
settings.qualityScaling.startingTargetIndex,
|
||||
settings.qualityScaling.scalingOptions
|
||||
);
|
||||
}
|
||||
|
||||
public autoscale(lastDeltaTime: DOMHighResTimeStamp) {
|
||||
this.timeSinceLastAdjusment += lastDeltaTime;
|
||||
if (
|
||||
this.timeSinceLastAdjusment >= settings.qualityScaling.adjusmentRateInMilliseconds
|
||||
) {
|
||||
this.timeSinceLastAdjusment = 0;
|
||||
this.exponentialDecayedDeltaTime = exponentialDecay(
|
||||
this.exponentialDecayedDeltaTime,
|
||||
lastDeltaTime,
|
||||
settings.qualityScaling.deltaTimeResponsiveness
|
||||
);
|
||||
|
||||
if (
|
||||
this.exponentialDecayedDeltaTime <=
|
||||
settings.qualityScaling.targetDeltaTimeInMilliseconds -
|
||||
settings.qualityScaling.deltaTimeError
|
||||
) {
|
||||
this.increase();
|
||||
} else if (
|
||||
this.exponentialDecayedDeltaTime >
|
||||
settings.qualityScaling.targetDeltaTimeInMilliseconds +
|
||||
settings.qualityScaling.deltaTimeError
|
||||
) {
|
||||
this.decrease();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
86
src/graphics/rendering/rendering-pass.ts
Normal file
86
src/graphics/rendering/rendering-pass.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawable } from '../drawables/i-drawable';
|
||||
import { IDrawableDescriptor } from '../drawables/i-drawable-descriptor';
|
||||
import { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer';
|
||||
import { UniformArrayAutoScalingProgram } from '../graphics-library/program/uniform-array-autoscaling-program';
|
||||
import { settings } from '../settings';
|
||||
|
||||
export class RenderingPass {
|
||||
private drawables: Array<IDrawable> = [];
|
||||
private program: UniformArrayAutoScalingProgram;
|
||||
|
||||
constructor(
|
||||
gl: WebGL2RenderingContext,
|
||||
shaderSources: [string, string],
|
||||
drawableDescriptors: Array<IDrawableDescriptor>,
|
||||
private frame: FrameBuffer
|
||||
) {
|
||||
this.program = new UniformArrayAutoScalingProgram(
|
||||
gl,
|
||||
shaderSources,
|
||||
drawableDescriptors
|
||||
);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
await this.program.initialize();
|
||||
}
|
||||
|
||||
public addDrawable(drawable: IDrawable) {
|
||||
this.drawables.push(drawable);
|
||||
}
|
||||
|
||||
public render(commonUniforms: any, inputTexture?: WebGLTexture) {
|
||||
this.frame.bindAndClear(inputTexture);
|
||||
|
||||
const stepsInUV = 1 / settings.tileMultiplier;
|
||||
|
||||
const worldR =
|
||||
0.5 *
|
||||
vec2.length(vec2.scale(vec2.create(), commonUniforms.worldAreaInView, stepsInUV));
|
||||
|
||||
const radiusInNDC = worldR * commonUniforms.scaleWorldLengthToNDC;
|
||||
|
||||
const stepsInNDC = 2 * stepsInUV;
|
||||
|
||||
for (let x = -1; x < 1; x += stepsInNDC) {
|
||||
for (let y = -1; y < 1; y += stepsInNDC) {
|
||||
const uniforms = { ...commonUniforms, maxMinDistance: 0.0 };
|
||||
|
||||
const ndcBottomLeft = vec2.fromValues(x, y);
|
||||
|
||||
this.program.setDrawingRectangleUV(
|
||||
[(ndcBottomLeft.x + 1) / 2, (ndcBottomLeft.y + 1) / 2],
|
||||
vec2.fromValues(stepsInUV, stepsInUV)
|
||||
);
|
||||
|
||||
const tileCenterWorldCoordinates = vec2.transformMat2d(
|
||||
vec2.create(),
|
||||
vec2.add(
|
||||
vec2.create(),
|
||||
[(ndcBottomLeft.x + 1) / 2, (ndcBottomLeft.y + 1) / 2],
|
||||
vec2.fromValues(stepsInUV / 2, stepsInUV / 2)
|
||||
),
|
||||
uniforms.uvToWorld
|
||||
);
|
||||
|
||||
const primitivesNearTile = this.drawables.filter(
|
||||
(d) => d.distance(tileCenterWorldCoordinates) < 2 * worldR
|
||||
);
|
||||
|
||||
primitivesNearTile.forEach((p) =>
|
||||
p.serializeToUniforms(
|
||||
uniforms,
|
||||
uniforms.scaleWorldLengthToNDC,
|
||||
uniforms.transformWorldToNDC
|
||||
)
|
||||
);
|
||||
|
||||
this.program.bindAndSetUniforms(uniforms);
|
||||
this.program.draw();
|
||||
}
|
||||
}
|
||||
|
||||
this.drawables = [];
|
||||
}
|
||||
}
|
||||
94
src/graphics/rendering/uniforms-provider.ts
Normal file
94
src/graphics/rendering/uniforms-provider.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { mat2d, vec2 } from 'gl-matrix';
|
||||
|
||||
export class UniformsProvider {
|
||||
private scaleWorldLengthToNDC = 1;
|
||||
private transformWorldToNDC = mat2d.create();
|
||||
|
||||
private viewAreaBottomLeft = vec2.create();
|
||||
private worldAreaInView = vec2.create();
|
||||
private squareToAspectRatio = vec2.create();
|
||||
private uvToWorld = mat2d.create();
|
||||
private cursorPosition = vec2.create();
|
||||
|
||||
public softShadowsEnabled?: boolean;
|
||||
|
||||
public constructor(private gl: WebGL2RenderingContext) {}
|
||||
|
||||
public getUniforms(uniforms: any): any {
|
||||
const cursorPosition = this.uvToWorldCoordinate(this.cursorPosition);
|
||||
return {
|
||||
...uniforms,
|
||||
cursorPosition,
|
||||
uvToWorld: this.uvToWorld,
|
||||
worldAreaInView: this.worldAreaInView,
|
||||
squareToAspectRatio: this.squareToAspectRatio,
|
||||
scaleWorldLengthToNDC: this.scaleWorldLengthToNDC,
|
||||
transformWorldToNDC: this.transformWorldToNDC,
|
||||
squareToAspectRatioTimes2: vec2.scale(vec2.create(), this.squareToAspectRatio, 2),
|
||||
softShadowsEnabled: this.softShadowsEnabled,
|
||||
};
|
||||
}
|
||||
|
||||
private getScreenToWorldTransform(screenSize: vec2) {
|
||||
const transform = mat2d.fromTranslation(mat2d.create(), this.viewAreaBottomLeft);
|
||||
mat2d.scale(
|
||||
transform,
|
||||
transform,
|
||||
vec2.divide(vec2.create(), this.worldAreaInView, screenSize)
|
||||
);
|
||||
mat2d.translate(transform, transform, vec2.fromValues(0.5, 0.5));
|
||||
|
||||
return transform;
|
||||
}
|
||||
|
||||
public uvToWorldCoordinate(screenUvPosition: vec2): vec2 {
|
||||
const resolution = vec2.fromValues(this.gl.canvas.width, this.gl.canvas.height);
|
||||
|
||||
return vec2.transformMat2d(
|
||||
vec2.create(),
|
||||
vec2.multiply(vec2.create(), screenUvPosition, resolution),
|
||||
this.getScreenToWorldTransform(resolution)
|
||||
);
|
||||
}
|
||||
|
||||
public setViewArea(topLeft: vec2, size: vec2) {
|
||||
this.worldAreaInView = size;
|
||||
|
||||
// world coordinates
|
||||
this.viewAreaBottomLeft = vec2.add(
|
||||
vec2.create(),
|
||||
topLeft,
|
||||
vec2.fromValues(0, -size.y)
|
||||
);
|
||||
|
||||
const scaleLongerEdgeTo1 =
|
||||
1 / Math.max(this.worldAreaInView.x, this.worldAreaInView.y);
|
||||
|
||||
this.squareToAspectRatio = vec2.fromValues(
|
||||
this.worldAreaInView.x * scaleLongerEdgeTo1,
|
||||
this.worldAreaInView.y * scaleLongerEdgeTo1
|
||||
);
|
||||
|
||||
this.scaleWorldLengthToNDC = scaleLongerEdgeTo1 * 2;
|
||||
|
||||
mat2d.fromScaling(
|
||||
this.transformWorldToNDC,
|
||||
vec2.fromValues(this.scaleWorldLengthToNDC, this.scaleWorldLengthToNDC)
|
||||
);
|
||||
mat2d.translate(
|
||||
this.transformWorldToNDC,
|
||||
this.transformWorldToNDC,
|
||||
vec2.fromValues(
|
||||
-this.viewAreaBottomLeft.x - 0.5 * this.worldAreaInView.x,
|
||||
-this.viewAreaBottomLeft.y - 0.5 * this.worldAreaInView.y
|
||||
)
|
||||
);
|
||||
|
||||
this.uvToWorld = mat2d.fromTranslation(mat2d.create(), this.viewAreaBottomLeft);
|
||||
mat2d.scale(this.uvToWorld, this.uvToWorld, this.worldAreaInView);
|
||||
}
|
||||
|
||||
public setCursorPosition(position: vec2): void {
|
||||
this.cursorPosition = position;
|
||||
}
|
||||
}
|
||||
126
src/graphics/rendering/webgl2-renderer.ts
Normal file
126
src/graphics/rendering/webgl2-renderer.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { IDrawable } from '../drawables/i-drawable';
|
||||
import { CircleLight } from '../drawables/lights/circle-light';
|
||||
import { Flashlight } from '../drawables/lights/flashlight';
|
||||
import { ILight } from '../drawables/lights/i-light';
|
||||
import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer';
|
||||
import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer';
|
||||
import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context';
|
||||
import { WebGlStopwatch } from '../graphics-library/helper/stopwatch';
|
||||
import { IRenderer } from '../i-renderer';
|
||||
import distanceFragmentShader from '../shaders/distance-fs.glsl';
|
||||
import distanceVertexShader from '../shaders/distance-vs.glsl';
|
||||
import lightsFragmentShader from '../shaders/shading-fs.glsl';
|
||||
import lightsVertexShader from '../shaders/shading-vs.glsl';
|
||||
import { FpsAutoscaler } from './fps-autoscaler';
|
||||
import { RenderingPass } from './rendering-pass';
|
||||
import { UniformsProvider } from './uniforms-provider';
|
||||
|
||||
export class WebGl2Renderer implements IRenderer {
|
||||
private gl: WebGL2RenderingContext;
|
||||
private stopwatch?: WebGlStopwatch;
|
||||
private uniformsProvider: UniformsProvider;
|
||||
private distanceFieldFrameBuffer: IntermediateFrameBuffer;
|
||||
private lightingFrameBuffer: DefaultFrameBuffer;
|
||||
private distancePass: RenderingPass;
|
||||
private lightingPass: RenderingPass;
|
||||
private autoscaler: FpsAutoscaler;
|
||||
|
||||
private initializePromise: Promise<[void, void]>;
|
||||
|
||||
constructor(private canvas: HTMLCanvasElement, private overlay: HTMLElement) {
|
||||
this.gl = getWebGl2Context(canvas);
|
||||
|
||||
this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(this.gl);
|
||||
this.lightingFrameBuffer = new DefaultFrameBuffer(this.gl);
|
||||
|
||||
this.distancePass = new RenderingPass(
|
||||
this.gl,
|
||||
[distanceVertexShader, distanceFragmentShader],
|
||||
[],
|
||||
this.distanceFieldFrameBuffer
|
||||
);
|
||||
|
||||
this.lightingPass = new RenderingPass(
|
||||
this.gl,
|
||||
[lightsVertexShader, lightsFragmentShader],
|
||||
[CircleLight.descriptor, Flashlight.descriptor],
|
||||
this.lightingFrameBuffer
|
||||
);
|
||||
|
||||
this.initializePromise = Promise.all([
|
||||
this.distancePass.initialize(),
|
||||
this.lightingPass.initialize(),
|
||||
]);
|
||||
|
||||
this.uniformsProvider = new UniformsProvider(this.gl);
|
||||
|
||||
this.autoscaler = new FpsAutoscaler({
|
||||
distanceRenderScale: (v) =>
|
||||
(this.distanceFieldFrameBuffer.renderScale = v as number),
|
||||
finalRenderScale: (v) => (this.lightingFrameBuffer.renderScale = v as number),
|
||||
softShadowsEnabled: (v) =>
|
||||
(this.uniformsProvider.softShadowsEnabled = v as boolean),
|
||||
});
|
||||
|
||||
try {
|
||||
this.stopwatch = new WebGlStopwatch(this.gl);
|
||||
} catch {
|
||||
// no problem
|
||||
}
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
await this.initializePromise;
|
||||
}
|
||||
|
||||
public drawShape(shape: IDrawable) {
|
||||
this.distancePass.addDrawable(shape);
|
||||
}
|
||||
|
||||
public drawLight(light: ILight) {
|
||||
this.lightingPass.addDrawable(light);
|
||||
}
|
||||
|
||||
public startFrame(deltaTime: DOMHighResTimeStamp) {
|
||||
this.autoscaler.autoscale(deltaTime);
|
||||
|
||||
this.stopwatch?.start();
|
||||
|
||||
this.distanceFieldFrameBuffer.setSize();
|
||||
this.lightingFrameBuffer.setSize();
|
||||
}
|
||||
|
||||
public finishFrame() {
|
||||
const common = {
|
||||
distanceNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()),
|
||||
shadingNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()),
|
||||
};
|
||||
|
||||
this.distancePass.render(this.uniformsProvider.getUniforms(common));
|
||||
this.lightingPass.render(
|
||||
this.uniformsProvider.getUniforms(common),
|
||||
this.distanceFieldFrameBuffer.colorTexture
|
||||
);
|
||||
|
||||
this.stopwatch?.stop();
|
||||
}
|
||||
|
||||
public setViewArea(topLeft: vec2, size: vec2) {
|
||||
this.uniformsProvider.setViewArea(topLeft, size);
|
||||
}
|
||||
|
||||
public setCursorPosition(position: vec2) {
|
||||
this.uniformsProvider.setCursorPosition(position);
|
||||
}
|
||||
|
||||
public get canvasSize(): vec2 {
|
||||
return vec2.fromValues(this.canvas.clientWidth, this.canvas.clientHeight);
|
||||
}
|
||||
|
||||
public drawInfoText(text: string) {
|
||||
if (this.overlay.innerText != text) {
|
||||
this.overlay.innerText = text;
|
||||
}
|
||||
}
|
||||
}
|
||||
59
src/graphics/settings.ts
Normal file
59
src/graphics/settings.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
export const settings = {
|
||||
enableHighDpiRendering: true,
|
||||
qualityScaling: {
|
||||
targetDeltaTimeInMilliseconds: 20,
|
||||
deltaTimeError: 2,
|
||||
deltaTimeResponsiveness: 1 / 16,
|
||||
adjusmentRateInMilliseconds: 300,
|
||||
qualityTargets: [
|
||||
{
|
||||
distanceRenderScale: 0.1,
|
||||
finalRenderScale: 0.2,
|
||||
softShadowsEnabled: false,
|
||||
},
|
||||
{
|
||||
distanceRenderScale: 0.1,
|
||||
finalRenderScale: 0.6,
|
||||
softShadowsEnabled: false,
|
||||
},
|
||||
{
|
||||
distanceRenderScale: 0.3,
|
||||
finalRenderScale: 1.0,
|
||||
softShadowsEnabled: false,
|
||||
},
|
||||
{
|
||||
distanceRenderScale: 0.3,
|
||||
finalRenderScale: 1.0,
|
||||
softShadowsEnabled: true,
|
||||
},
|
||||
/*{
|
||||
distanceRenderScale: 1.0,
|
||||
finalRenderScale: 1.5,
|
||||
softShadowsEnabled: true,
|
||||
},
|
||||
{
|
||||
distanceRenderScale: 1.25,
|
||||
finalRenderScale: 1.75,
|
||||
softShadowsEnabled: true,
|
||||
},
|
||||
{
|
||||
distanceRenderScale: 2,
|
||||
finalRenderScale: 2,
|
||||
softShadowsEnabled: true,
|
||||
},*/
|
||||
],
|
||||
startingTargetIndex: 2,
|
||||
scalingOptions: {
|
||||
additiveIncrease: 0.2,
|
||||
multiplicativeDecrease: 1.05,
|
||||
},
|
||||
},
|
||||
tileMultiplier: 8,
|
||||
shaderMacros: {},
|
||||
shaderCombinations: {
|
||||
lineSteps: [0, 1, 2, 4, 8, 16, 128],
|
||||
blobSteps: [0, 1, 2, 8],
|
||||
circleLightSteps: [0, 1],
|
||||
flashlightSteps: [0, 1],
|
||||
},
|
||||
};
|
||||
109
src/graphics/shaders/distance-fs.glsl
Normal file
109
src/graphics/shaders/distance-fs.glsl
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
#version 300 es
|
||||
|
||||
precision lowp float;
|
||||
|
||||
#define LINE_COUNT {lineCount}
|
||||
#define BLOB_COUNT {blobCount}
|
||||
|
||||
#define SURFACE_OFFSET 0.001
|
||||
|
||||
uniform float maxMinDistance;
|
||||
uniform float distanceNdcPixelSize;
|
||||
|
||||
in vec2 position;
|
||||
|
||||
float smoothMin(float a, float b)
|
||||
{
|
||||
const float k = 2.0;
|
||||
|
||||
a = pow(a, k);
|
||||
b = pow(b, k);
|
||||
return pow((a * b) / (a + b), 1.0 / k);
|
||||
}
|
||||
|
||||
#if LINE_COUNT > 0
|
||||
uniform struct {
|
||||
vec2 from;
|
||||
vec2 toFromDelta;
|
||||
float fromRadius;
|
||||
float toRadius;
|
||||
}[LINE_COUNT] lines;
|
||||
|
||||
void lineMinDistance(inout float minDistance, inout float color) {
|
||||
float myMinDistance = maxMinDistance;
|
||||
for (int i = 0; i < LINE_COUNT; i++) {
|
||||
vec2 targetFromDelta = position - lines[i].from;
|
||||
vec2 toFromDelta = lines[i].toFromDelta;
|
||||
|
||||
float h = clamp(
|
||||
dot(targetFromDelta, toFromDelta) / dot(toFromDelta, toFromDelta),
|
||||
0.0, 1.0
|
||||
);
|
||||
|
||||
float lineDistance = -mix(
|
||||
lines[i].fromRadius, lines[i].toRadius, h
|
||||
) + distance(
|
||||
targetFromDelta, toFromDelta * h
|
||||
);
|
||||
|
||||
myMinDistance = min(myMinDistance, lineDistance);
|
||||
}
|
||||
|
||||
color = mix(0.0, color, step(distanceNdcPixelSize + SURFACE_OFFSET, -myMinDistance));
|
||||
minDistance = -myMinDistance;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if BLOB_COUNT > 0
|
||||
uniform struct {
|
||||
vec2 headCenter;
|
||||
vec2 leftFootCenter;
|
||||
vec2 rightFootCenter;
|
||||
float headRadius;
|
||||
float footRadius;
|
||||
float k;
|
||||
}[BLOB_COUNT] blobs;
|
||||
|
||||
float circleMinDistance(vec2 circleCenter, float radius) {
|
||||
return distance(position, circleCenter) - radius;
|
||||
}
|
||||
|
||||
void blobMinDistance(inout float minDistance, inout float color) {
|
||||
for (int i = 0; i < BLOB_COUNT; i++) {
|
||||
float headDistance = circleMinDistance(blobs[i].headCenter, blobs[i].headRadius);
|
||||
float leftFootDistance = circleMinDistance(blobs[i].leftFootCenter, blobs[i].footRadius);
|
||||
float rightFootDistance = circleMinDistance(blobs[i].rightFootCenter, blobs[i].footRadius);
|
||||
|
||||
float res = min(
|
||||
smoothMin(headDistance, leftFootDistance),
|
||||
smoothMin(headDistance, rightFootDistance)
|
||||
);
|
||||
|
||||
res = min(100.0, headDistance);
|
||||
res = min(res, leftFootDistance);
|
||||
res = min(res, rightFootDistance);
|
||||
//color = mix(2.0, color, step(distanceUvPixelSize + SURFACE_OFFSET, res));
|
||||
minDistance = min(minDistance, res);
|
||||
color = mix(2.0, color, step(distanceNdcPixelSize + SURFACE_OFFSET, res));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
out vec2 fragmentColor;
|
||||
|
||||
void main() {
|
||||
float minDistance = -maxMinDistance;
|
||||
float color = 0.0;
|
||||
|
||||
#if LINE_COUNT > 0
|
||||
lineMinDistance(minDistance, color);
|
||||
#endif
|
||||
|
||||
#if BLOB_COUNT > 0
|
||||
blobMinDistance(minDistance, color);
|
||||
#endif
|
||||
|
||||
|
||||
// minDistance / 2.0: NDC to UV scale
|
||||
fragmentColor = vec2((minDistance - SURFACE_OFFSET) / 2.0, color);
|
||||
}
|
||||
15
src/graphics/shaders/distance-vs.glsl
Normal file
15
src/graphics/shaders/distance-vs.glsl
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
#version 300 es
|
||||
|
||||
precision lowp float;
|
||||
|
||||
uniform mat3 modelTransform;
|
||||
uniform vec2 squareToAspectRatio;
|
||||
|
||||
in vec4 vertexPosition;
|
||||
out vec2 position;
|
||||
|
||||
void main() {
|
||||
vec3 vertexPosition2D = vec3(vertexPosition.xy, 1.0) * modelTransform;
|
||||
gl_Position = vec4(vertexPosition2D.xy, 0.0, 1.0);
|
||||
position = vertexPosition2D.xy * squareToAspectRatio;
|
||||
}
|
||||
176
src/graphics/shaders/shading-fs.glsl
Normal file
176
src/graphics/shaders/shading-fs.glsl
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
#version 300 es
|
||||
|
||||
precision lowp float;
|
||||
|
||||
#define INFINITY 1000.0
|
||||
#define LIGHT_DROP_INSIDE_RATIO 0.3
|
||||
#define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25)
|
||||
#define SHADOW_HARDNESS 150.0
|
||||
|
||||
#define CIRCLE_LIGHT_COUNT {circleLightCount}
|
||||
#define FLASHLIGHT_COUNT {flashlightCount}
|
||||
|
||||
uniform bool softShadowsEnabled;
|
||||
uniform vec2 squareToAspectRatioTimes2;
|
||||
uniform float shadingNdcPixelSize;
|
||||
uniform sampler2D distanceTexture;
|
||||
|
||||
in vec2 position;
|
||||
in vec2 uvCoordinates;
|
||||
|
||||
vec3[3] colors = vec3[](
|
||||
vec3(0.4, 0.35, 0.6), // cave color
|
||||
vec3(0.0, 1.0, 0.0),
|
||||
vec3(0.0, 0.0, 1.0)
|
||||
);
|
||||
|
||||
float getDistance(in vec2 target, out vec3 color) {
|
||||
vec4 values = texture(distanceTexture, target);
|
||||
color = colors[int(values[1])];
|
||||
return values[0];
|
||||
}
|
||||
|
||||
float getDistance(in vec2 target) {
|
||||
return texture(distanceTexture, target)[0];
|
||||
}
|
||||
|
||||
float softShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
|
||||
float rayLength = startingDistance;
|
||||
float q = 1.0 / SHADOW_HARDNESS;
|
||||
|
||||
for (int j = 0; j < 128; j++) {
|
||||
float minDistance = getDistance(uvCoordinates + direction * rayLength);
|
||||
|
||||
q = min(q, minDistance / rayLength);
|
||||
rayLength += minDistance / 2.5;
|
||||
|
||||
if (rayLength >= lightCenterDistance) {
|
||||
return q * SHADOW_HARDNESS;
|
||||
}
|
||||
}
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
float hardShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
|
||||
float rayLength = startingDistance;
|
||||
|
||||
for (int j = 0; j < 32; j++) {
|
||||
rayLength += getDistance(uvCoordinates + direction * rayLength);
|
||||
}
|
||||
|
||||
return step(lightCenterDistance, rayLength);
|
||||
}
|
||||
|
||||
float shadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
|
||||
return softShadowsEnabled ?
|
||||
softShadowTransparency(startingDistance, lightCenterDistance, direction) :
|
||||
hardShadowTransparency(startingDistance, lightCenterDistance, direction);
|
||||
}
|
||||
|
||||
|
||||
#if CIRCLE_LIGHT_COUNT > 0
|
||||
uniform struct CircleLight {
|
||||
vec2 center;
|
||||
float lightDrop;
|
||||
vec3 value;
|
||||
}[CIRCLE_LIGHT_COUNT] circleLights;
|
||||
|
||||
in vec2[CIRCLE_LIGHT_COUNT] circleLightDirections;
|
||||
|
||||
vec3 colorInPosition(CircleLight light, out float lightCenterDistance) {
|
||||
lightCenterDistance = distance(light.center, position);
|
||||
return light.value / pow(
|
||||
lightCenterDistance / light.lightDrop + 1.0, 2.0
|
||||
);
|
||||
}
|
||||
|
||||
vec3 colorInPositionInside(CircleLight light) {
|
||||
float lightCenterDistance = distance(light.center, position);
|
||||
return light.value / pow(
|
||||
lightCenterDistance / (light.lightDrop * LIGHT_DROP_INSIDE_RATIO) + 1.0, 2.0
|
||||
);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if FLASHLIGHT_COUNT > 0
|
||||
uniform struct Flashlight {
|
||||
vec2 center;
|
||||
vec2 direction;
|
||||
float lightDrop;
|
||||
vec3 value;
|
||||
}[FLASHLIGHT_COUNT] flashlights;
|
||||
|
||||
in vec2[FLASHLIGHT_COUNT] flashlightDirections;
|
||||
|
||||
float intensityInDirection(vec2 lightDirection, vec2 targetDirection) {
|
||||
return smoothstep(0.0, 1.0, 10.0 * max(0.0, dot(targetDirection, lightDirection) - 0.9));
|
||||
}
|
||||
|
||||
vec3 colorInPosition(Flashlight light, vec2 positionDirection, out float lightCenterDistance) {
|
||||
lightCenterDistance = distance(light.center, position);
|
||||
return intensityInDirection(light.direction, positionDirection) * light.value / pow(
|
||||
lightCenterDistance / light.lightDrop + 1.0, 2.0
|
||||
);
|
||||
}
|
||||
|
||||
vec3 colorInPositionInside(Flashlight light, vec2 positionDirection) {
|
||||
float lightCenterDistance = distance(light.center, position);
|
||||
return intensityInDirection(light.direction, positionDirection) * light.value / pow(
|
||||
lightCenterDistance / (light.lightDrop * LIGHT_DROP_INSIDE_RATIO) + 1.0, 2.0
|
||||
);
|
||||
}
|
||||
#endif
|
||||
|
||||
out vec4 fragmentColor;
|
||||
void main() {
|
||||
vec3 lighting = AMBIENT_LIGHT;
|
||||
|
||||
vec3 colorAtPosition;
|
||||
float startingDistance = getDistance(uvCoordinates, colorAtPosition);
|
||||
|
||||
if (startingDistance < 0.0) {
|
||||
#if CIRCLE_LIGHT_COUNT > 0
|
||||
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
|
||||
lighting += colorInPositionInside(circleLights[i]);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if FLASHLIGHT_COUNT > 0
|
||||
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
|
||||
lighting += colorInPositionInside(flashlights[i], normalize(flashlightDirections[i]));
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
colorAtPosition = vec3(1.0);
|
||||
|
||||
#if CIRCLE_LIGHT_COUNT > 0
|
||||
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
|
||||
vec2 direction = normalize(circleLightDirections[i]) / squareToAspectRatioTimes2;
|
||||
|
||||
float lightCenterDistance;
|
||||
vec3 lightColorAtPosition = colorInPosition(circleLights[i], lightCenterDistance);
|
||||
|
||||
lighting += lightColorAtPosition * shadowTransparency(startingDistance, lightCenterDistance, direction);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if FLASHLIGHT_COUNT > 0
|
||||
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
|
||||
vec2 originalDirection = normalize(flashlightDirections[i]);
|
||||
vec2 direction = originalDirection / squareToAspectRatioTimes2;
|
||||
|
||||
float lightCenterDistance;
|
||||
vec3 lightColorAtPosition = colorInPosition(flashlights[i], originalDirection, lightCenterDistance);
|
||||
|
||||
if (length(lightColorAtPosition) < 0.01) {
|
||||
continue;
|
||||
}
|
||||
|
||||
lighting += lightColorAtPosition * shadowTransparency(startingDistance, lightCenterDistance, direction);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
fragmentColor = vec4(colorAtPosition * lighting, 1.0);
|
||||
}
|
||||
59
src/graphics/shaders/shading-vs.glsl
Normal file
59
src/graphics/shaders/shading-vs.glsl
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
#version 300 es
|
||||
|
||||
precision lowp float;
|
||||
|
||||
#define CIRCLE_LIGHT_COUNT {circleLightCount}
|
||||
#define FLASHLIGHT_COUNT {flashlightCount}
|
||||
|
||||
uniform mat3 modelTransform;
|
||||
in vec4 vertexPosition;
|
||||
|
||||
out vec2 position;
|
||||
out vec2 uvCoordinates;
|
||||
|
||||
uniform vec2 squareToAspectRatio;
|
||||
|
||||
#if CIRCLE_LIGHT_COUNT > 0
|
||||
uniform struct CircleLight {
|
||||
vec2 center;
|
||||
float lightDrop;
|
||||
vec3 value;
|
||||
}[CIRCLE_LIGHT_COUNT] circleLights;
|
||||
|
||||
out vec2[CIRCLE_LIGHT_COUNT] circleLightDirections;
|
||||
#endif
|
||||
|
||||
#if FLASHLIGHT_COUNT > 0
|
||||
uniform struct Flashlight {
|
||||
vec2 center;
|
||||
vec2 direction;
|
||||
float lightDrop;
|
||||
vec3 value;
|
||||
}[FLASHLIGHT_COUNT] flashlights;
|
||||
|
||||
out vec2[FLASHLIGHT_COUNT] flashlightDirections;
|
||||
#endif
|
||||
|
||||
void main() {
|
||||
vec3 vertexPosition2D = vec3(vertexPosition.xy, 1.0) * modelTransform;
|
||||
gl_Position = vec4(vertexPosition2D.xy, 0.0, 1.0);
|
||||
position = vertexPosition2D.xy * squareToAspectRatio;
|
||||
|
||||
uvCoordinates = (vertexPosition2D * mat3(
|
||||
0.5, 0.0, 0.5,
|
||||
0.0, 0.5, 0.5,
|
||||
0.0, 0.0, 1.0
|
||||
)).xy;
|
||||
|
||||
#if CIRCLE_LIGHT_COUNT > 0
|
||||
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
|
||||
circleLightDirections[i] = circleLights[i].center - position;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if FLASHLIGHT_COUNT > 0
|
||||
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
|
||||
flashlightDirections[i] = flashlights[i].center - position;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
49
src/helper/array.ts
Normal file
49
src/helper/array.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
declare global {
|
||||
interface Array<T> {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface Float32Array {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
}
|
||||
|
||||
export const applyArrayPlugins = () => {
|
||||
Object.defineProperty(Array.prototype, 'x', {
|
||||
get() {
|
||||
return this[0];
|
||||
},
|
||||
set(value) {
|
||||
this[0] = value;
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(Array.prototype, 'y', {
|
||||
get() {
|
||||
return this[1];
|
||||
},
|
||||
set(value) {
|
||||
this[1] = value;
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(Float32Array.prototype, 'x', {
|
||||
get() {
|
||||
return this[0];
|
||||
},
|
||||
set(value) {
|
||||
this[0] = value;
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(Float32Array.prototype, 'y', {
|
||||
get() {
|
||||
return this[1];
|
||||
},
|
||||
set(value) {
|
||||
this[1] = value;
|
||||
},
|
||||
});
|
||||
};
|
||||
59
src/helper/autoscaler.ts
Normal file
59
src/helper/autoscaler.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { clamp } from './clamp';
|
||||
import { mix } from './mix';
|
||||
|
||||
export class Autoscaler {
|
||||
// can have fractions
|
||||
private index: number;
|
||||
|
||||
constructor(
|
||||
private setters: { [key: string]: (value: number | boolean) => void },
|
||||
private targets: Array<{ [key: string]: number | boolean }>,
|
||||
startingIndex: number,
|
||||
private scalingOptions: {
|
||||
additiveIncrease: number;
|
||||
multiplicativeDecrease: number;
|
||||
}
|
||||
) {
|
||||
this.index = startingIndex;
|
||||
this.applyScaling();
|
||||
}
|
||||
|
||||
public increase() {
|
||||
this.index += this.scalingOptions.additiveIncrease;
|
||||
this.applyScaling();
|
||||
}
|
||||
|
||||
public decrease() {
|
||||
this.index /= this.scalingOptions.multiplicativeDecrease;
|
||||
this.applyScaling();
|
||||
}
|
||||
|
||||
private applyScaling() {
|
||||
this.index = clamp(this.index, 0, this.targets.length - 1);
|
||||
|
||||
const floor = Math.floor(this.index);
|
||||
const fract = this.index - floor;
|
||||
|
||||
const previousTarget = this.targets[floor];
|
||||
const nextTarget =
|
||||
floor + 1 == this.targets.length ? previousTarget : this.targets[floor + 1];
|
||||
|
||||
const result = {};
|
||||
for (const key in this.setters) {
|
||||
const previous = previousTarget[key];
|
||||
const next = nextTarget[key];
|
||||
let current: number | boolean;
|
||||
if (typeof previous == 'number') {
|
||||
current = mix(previous, next as number, fract);
|
||||
} else {
|
||||
current = next;
|
||||
}
|
||||
|
||||
result[key] = current;
|
||||
|
||||
this.setters[key](current);
|
||||
}
|
||||
|
||||
//InfoText.modifyRecord('quality', result);
|
||||
}
|
||||
}
|
||||
4
src/helper/clamp.ts
Normal file
4
src/helper/clamp.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
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));
|
||||
5
src/helper/exponential-decay.ts
Normal file
5
src/helper/exponential-decay.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export const exponentialDecay = (
|
||||
accumulator: number,
|
||||
nextValue: number,
|
||||
biasOfNextValue: number
|
||||
) => accumulator * (1 - biasOfNextValue) + nextValue * biasOfNextValue;
|
||||
29
src/helper/get-combinations.ts
Normal file
29
src/helper/get-combinations.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
export const getCombinations = (values: Array<Array<number>>): Array<Array<number>> => {
|
||||
if (!values.every((a) => a.length > 0)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: Array<Array<number>> = [];
|
||||
const counters = values.map((_) => 0);
|
||||
|
||||
const increaseCounter = (i: number) => {
|
||||
if (i >= counters.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
counters[i]++;
|
||||
|
||||
if (counters[i] >= values[i].length) {
|
||||
counters[i] = 0;
|
||||
return increaseCounter(i + 1);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
do {
|
||||
result.push(values.map((v, i) => v[counters[i]]));
|
||||
} while (increaseCounter(0));
|
||||
|
||||
return result;
|
||||
};
|
||||
3
src/helper/last.ts
Normal file
3
src/helper/last.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export function last<T>(a: Array<T>): T | null {
|
||||
return a.length > 0 ? a[a.length - 1] : null;
|
||||
}
|
||||
1
src/helper/mix.ts
Normal file
1
src/helper/mix.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export const mix = (from: number, to: number, q: number) => from + (to - from) * q;
|
||||
18
src/helper/random.ts
Normal file
18
src/helper/random.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// 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;
|
||||
}
|
||||
}
|
||||
3
src/helper/rotate-90-deg.ts
Normal file
3
src/helper/rotate-90-deg.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
|
||||
export const rotate90Deg = (vec: vec2): vec2 => vec2.fromValues(-vec.y, vec.x);
|
||||
32
src/helper/timing.ts
Normal file
32
src/helper/timing.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
export function timeIt(interval = 60) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
let i = 0;
|
||||
let previousTimes: Array<DOMHighResTimeStamp> = [];
|
||||
|
||||
const targetFunction = descriptor.value;
|
||||
|
||||
descriptor.value = function (...values) {
|
||||
const start = performance.now();
|
||||
targetFunction.bind(this)(...values);
|
||||
const end = performance.now();
|
||||
|
||||
previousTimes.push(end - start);
|
||||
|
||||
if (i++ % interval == 0) {
|
||||
previousTimes = previousTimes.sort();
|
||||
|
||||
/*const text = `Max: ${last(previousTimes).toFixed(
|
||||
2
|
||||
)} ms\n\tMedian: ${previousTimes[Math.floor(previousTimes.length / 2)].toFixed(
|
||||
2
|
||||
)} ms`;*/
|
||||
|
||||
//InfoText.modifyRecord(propertyKey, text);
|
||||
|
||||
previousTimes = [];
|
||||
}
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
};
|
||||
}
|
||||
1
src/helper/to-percent.ts
Normal file
1
src/helper/to-percent.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export const toPercent = (value: number) => `${Math.round(value * 100)}%`;
|
||||
29
src/helper/wait-while-false.ts
Normal file
29
src/helper/wait-while-false.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
export const waitWhileFalse = (body: () => boolean): Promise<void> => {
|
||||
let resolveOnDone: () => void;
|
||||
let rejectOnDone: (e: Error) => void;
|
||||
|
||||
const onDone = new Promise<void>((resolve, reject) => {
|
||||
resolveOnDone = resolve;
|
||||
rejectOnDone = reject;
|
||||
});
|
||||
|
||||
const waiter = () => {
|
||||
let success: boolean;
|
||||
|
||||
try {
|
||||
success = body();
|
||||
} catch (e) {
|
||||
rejectOnDone(e);
|
||||
return;
|
||||
}
|
||||
|
||||
if (success) {
|
||||
resolveOnDone();
|
||||
} else {
|
||||
requestAnimationFrame(waiter);
|
||||
}
|
||||
};
|
||||
|
||||
waiter();
|
||||
return onDone;
|
||||
};
|
||||
3
src/helper/wait.ts
Normal file
3
src/helper/wait.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export const wait = (ms: number): Promise<void> => {
|
||||
return new Promise<void>((resolve, _) => setTimeout(resolve, ms));
|
||||
};
|
||||
18
src/main.ts
Normal file
18
src/main.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { glMatrix } from 'gl-matrix';
|
||||
import { applyArrayPlugins } from './helper/array';
|
||||
import { Random } from './helper/random';
|
||||
|
||||
glMatrix.setMatrixArrayType(Array);
|
||||
applyArrayPlugins();
|
||||
|
||||
const main = async () => {
|
||||
try {
|
||||
Random.seed = 42;
|
||||
//await new Game().start();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(e);
|
||||
}
|
||||
};
|
||||
|
||||
main();
|
||||
17
tsconfig.json
Normal file
17
tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
"sourceMap": true,
|
||||
"noImplicitAny": false,
|
||||
"target": "es5",
|
||||
"downlevelIteration": true,
|
||||
"allowJs": true,
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"experimentalDecorators": true,
|
||||
"moduleResolution": "Node",
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"lib": ["es2015", "dom"]
|
||||
}
|
||||
}
|
||||
73
webpack.config.js
Normal file
73
webpack.config.js
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
const path = require('path');
|
||||
const TerserJSPlugin = require('terser-webpack-plugin');
|
||||
|
||||
const isProduction = process.env.NODE_ENV == 'production';
|
||||
const isDevelopment = !isProduction;
|
||||
|
||||
module.exports = {
|
||||
devtool: 'inline-source-map',
|
||||
optimization: {
|
||||
minimize: true,
|
||||
minimizer: [
|
||||
new TerserJSPlugin({
|
||||
sourceMap: isDevelopment,
|
||||
cache: true,
|
||||
test: /\.ts$/i,
|
||||
terserOptions: {
|
||||
ecma: 5,
|
||||
warnings: true,
|
||||
parse: {},
|
||||
compress: { defaults: true },
|
||||
mangle: true,
|
||||
module: false,
|
||||
output: null,
|
||||
toplevel: true,
|
||||
nameCache: null,
|
||||
ie8: false,
|
||||
keep_classnames: false,
|
||||
keep_fnames: false,
|
||||
safari10: false,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
plugins: [],
|
||||
entry: {
|
||||
main: './src/main.ts',
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.(glsl)$/,
|
||||
use: {
|
||||
loader: 'raw-loader',
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(woff2?|ttf|eot|svg)(?:[?#].+)?$/,
|
||||
use: {
|
||||
loader: 'file-loader',
|
||||
options: {
|
||||
name: '[name].[ext]',
|
||||
outputPath: 'static/fonts/',
|
||||
},
|
||||
},
|
||||
include: /fonts/,
|
||||
},
|
||||
{
|
||||
test: /\.ts$/,
|
||||
use: {
|
||||
loader: 'ts-loader',
|
||||
},
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.ts', '.js', '.glsl'],
|
||||
},
|
||||
output: {
|
||||
filename: '[name]-bundle.js',
|
||||
path: path.resolve(__dirname, 'build'),
|
||||
},
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue