Improve API

This commit is contained in:
schmelczerandras 2020-09-16 11:31:26 +02:00
parent b2c2cfcb41
commit 78444d8cc6
24 changed files with 193 additions and 325 deletions

20
custom.d.ts vendored
View file

@ -2,23 +2,3 @@ declare module '*.glsl' {
const content: string; const content: string;
export default content; 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;
}
*/

View file

@ -3,6 +3,7 @@
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"clean": "shx rm -rf _bundles lib lib-esm", "clean": "shx rm -rf _bundles lib lib-esm",
"start": "shx rm -rf lib/* && webpack --watch",
"build": "npm run clean && tsc && tsc -m es6 --outDir lib-esm && webpack" "build": "npm run clean && tsc && tsc -m es6 --outDir lib-esm && webpack"
}, },
"keywords": [], "keywords": [],
@ -10,9 +11,6 @@
"browserslist": [ "browserslist": [
"defaults" "defaults"
], ],
"sideEffects": [
"*.scss"
],
"main": "lib/sdf-2d.js", "main": "lib/sdf-2d.js",
"types": "lib/src/main.d.ts", "types": "lib/src/main.d.ts",
"files": [ "files": [
@ -28,7 +26,7 @@
"eslint-plugin-prettier": "^3.1.4", "eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-unused-imports": "^0.1.3", "eslint-plugin-unused-imports": "^0.1.3",
"gl-matrix": "^3.3.0", "gl-matrix": "^3.3.0",
"prettier": "^2.1.1", "prettier": "^2.1.2",
"raw-loader": "^4.0.1", "raw-loader": "^4.0.1",
"resolve-url-loader": "^3.1.1", "resolve-url-loader": "^3.1.1",
"shx": "^0.3.2", "shx": "^0.3.2",

View file

@ -2,7 +2,11 @@ import { Drawable } from './drawable';
export interface DrawableDescriptor { export interface DrawableDescriptor {
uniformName: string; uniformName: string;
countMacroName: string; uniformCountMacroName: string;
sdf?: {
shader: string;
distanceFunctionName: string;
};
shaderCombinationSteps: Array<number>; shaderCombinationSteps: Array<number>;
readonly empty: Drawable; readonly empty: Drawable;
} }

View file

@ -7,9 +7,20 @@ export abstract class Drawable {
} }
public abstract distance(target: vec2): number; public abstract distance(target: vec2): number;
public abstract serializeToUniforms(
protected abstract getObjectToSerialize(transform2d: mat2d, transform1d: number): any;
public serializeToUniforms(
uniforms: any, uniforms: any,
scale: number, transform2d: mat2d,
transform: mat2d transform1d: number
): void; ): void {
const { uniformName } = (this.constructor as typeof Drawable).descriptor;
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
uniforms[uniformName] = [];
}
uniforms[uniformName].push(this.getObjectToSerialize(transform2d, transform1d));
}
} }

View file

@ -7,7 +7,7 @@ export class CircleLight extends Drawable {
public static get descriptor(): DrawableDescriptor { public static get descriptor(): DrawableDescriptor {
return { return {
uniformName: 'circleLights', uniformName: 'circleLights',
countMacroName: 'circleLightCount', uniformCountMacroName: 'CIRCLE_LIGHT_COUNT',
shaderCombinationSteps: settings.shaderCombinations.circleLightSteps, shaderCombinationSteps: settings.shaderCombinations.circleLightSteps,
empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0), empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0),
}; };
@ -26,18 +26,12 @@ export class CircleLight extends Drawable {
return 0; return 0;
} }
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void { protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {
const { uniformName } = CircleLight.descriptor; return {
center: vec2.transformMat2d(vec2.create(), this.center, transform2d),
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
uniforms[uniformName] = [];
}
uniforms[uniformName].push({
center: vec2.transformMat2d(vec2.create(), this.center, transform),
lightDrop: this.lightDrop, lightDrop: this.lightDrop,
value: this.value, value: this.value,
}); };
} }
public get value(): vec3 { public get value(): vec3 {

View file

@ -7,7 +7,7 @@ export class Flashlight extends Drawable {
public static get descriptor(): DrawableDescriptor { public static get descriptor(): DrawableDescriptor {
return { return {
uniformName: 'flashlights', uniformName: 'flashlights',
countMacroName: 'flashlightCount', uniformCountMacroName: 'FLASHLIGHT_COUNT',
shaderCombinationSteps: settings.shaderCombinations.flashlightSteps, shaderCombinationSteps: settings.shaderCombinations.flashlightSteps,
empty: new Flashlight( empty: new Flashlight(
vec2.fromValues(0, 0), vec2.fromValues(0, 0),
@ -33,19 +33,13 @@ export class Flashlight extends Drawable {
return 0; return 0;
} }
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void { protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {
const listName = Flashlight.descriptor.uniformName; return {
center: vec2.transformMat2d(vec2.create(), this.center, transform2d),
if (!Object.prototype.hasOwnProperty.call(uniforms, listName)) {
uniforms[listName] = [];
}
uniforms[listName].push({
center: vec2.transformMat2d(vec2.create(), this.center, transform),
direction: this.direction, direction: this.direction,
lightDrop: this.lightDrop, lightDrop: this.lightDrop,
value: this.value, value: this.value,
}); };
} }
public get value(): vec3 { public get value(): vec3 {

View file

@ -1,14 +1,29 @@
import { mat2d, vec2 } from 'gl-matrix'; import { mat2d, vec2 } from 'gl-matrix';
import { settings } from '../../graphics/settings';
import { Drawable } from '../drawable'; import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor'; import { DrawableDescriptor } from '../drawable-descriptor';
export class Circle extends Drawable { export class Circle extends Drawable {
public static get descriptor(): DrawableDescriptor { public static get descriptor(): DrawableDescriptor {
return { return {
sdf: {
shader: `
uniform struct {
vec2 center;
float radius;
}[CIRCLE_COUNT] circles;
void circleMinDistance(inout float minDistance, inout float color) {
for (int i = 0; i < CIRCLE_COUNT; i++) {
float dist = distance(circles[i].center, position) - circles[i].radius;
minDistance = min(minDistance, dist);
}
}
`,
distanceFunctionName: 'circleMinDistance',
},
uniformName: 'circles', uniformName: 'circles',
countMacroName: 'circleCount', uniformCountMacroName: 'CIRCLE_COUNT',
shaderCombinationSteps: settings.shaderCombinations.circleSteps, shaderCombinationSteps: [0, 1, 2, 3, 16, 32],
empty: new Circle(vec2.fromValues(0, 0), 0), empty: new Circle(vec2.fromValues(0, 0), 0),
}; };
} }
@ -18,19 +33,13 @@ export class Circle extends Drawable {
} }
public distance(position: vec2): number { public distance(position: vec2): number {
return 0; return vec2.dist(this.center, position) - this.radius;
} }
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void { protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {
const { uniformName } = Circle.descriptor; return {
center: vec2.transformMat2d(vec2.create(), this.center, transform2d),
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) { radius: this.radius * transform1d,
uniforms[uniformName] = []; };
}
uniforms[uniformName].push({
center: vec2.transformMat2d(vec2.create(), this.center, transform),
radius: this.radius * scale,
});
} }
} }

View file

@ -1,121 +0,0 @@
/*
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 = [];
}
}
}
*/

View file

@ -1,21 +1,19 @@
import { waitWhileFalse } from '../../../helper/wait-while-false';
import { tryEnableExtension } from '../helper/enable-extension';
import { checkProgram } from './check-program'; import { checkProgram } from './check-program';
import { createShader } from './create-shader'; import { createShader } from './create-shader';
export const createProgram = async ( export const createProgram = (
gl: WebGL2RenderingContext, gl: WebGL2RenderingContext,
vertexShaderSource: string, vertexShaderSource: string,
fragmentShaderSource: string, fragmentShaderSource: string,
substitutions: { [name: string]: string } substitutions: { [name: string]: string }
): Promise<WebGLProgram> => { ): WebGLProgram => {
const program = gl.createProgram(); const program = gl.createProgram();
if (!program) { if (!program) {
throw new Error('Could not create program'); throw new Error('Could not create program');
} }
const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile'); // const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
const vertexShader = createShader( const vertexShader = createShader(
gl, gl,
@ -31,16 +29,17 @@ export const createProgram = async (
fragmentShaderSource, fragmentShaderSource,
substitutions substitutions
); );
gl.attachShader(program, fragmentShader); gl.attachShader(program, fragmentShader);
gl.linkProgram(program); gl.linkProgram(program);
if (extension) { /*if (extension) {
const checkCompileStatus = () => const checkCompileStatus = () =>
gl.getProgramParameter(program, extension.COMPLETION_STATUS_KHR); gl.getProgramParameter(program, extension.COMPLETION_STATUS_KHR);
await waitWhileFalse(checkCompileStatus); await waitWhileFalse(checkCompileStatus);
} }*/
checkProgram(gl, program); checkProgram(gl, program);

View file

@ -9,10 +9,6 @@ export class FragmentShaderOnlyProgram extends Program {
substitutions: { [name: string]: string } substitutions: { [name: string]: string }
) { ) {
super(gl, sources, substitutions); super(gl, sources, substitutions);
}
public async initialize(): Promise<void> {
await super.initialize();
this.prepareScreenQuad('vertexPosition'); this.prepareScreenQuad('vertexPosition');
} }

View file

@ -1,7 +1,6 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
export interface IProgram { export interface IProgram {
initialize(): Promise<void>;
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void; setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
bindAndSetUniforms(values: { [name: string]: any }): void; bindAndSetUniforms(values: { [name: string]: any }): void;
draw(): void; draw(): void;

View file

@ -7,7 +7,6 @@ import { IProgram } from './i-program';
export default abstract class Program implements IProgram { export default abstract class Program implements IProgram {
protected program?: WebGLProgram; protected program?: WebGLProgram;
private programPromise: Promise<WebGLProgram>;
private modelTransform = mat2d.identity(mat2d.create()); private modelTransform = mat2d.identity(mat2d.create());
private readonly ndcToUv = mat2d.fromValues(0.5, 0, 0, 0.5, 0.5, 0.5); private readonly ndcToUv = mat2d.fromValues(0.5, 0, 0, 0.5, 0.5, 0.5);
private uniforms: Array<{ private uniforms: Array<{
@ -23,16 +22,13 @@ export default abstract class Program implements IProgram {
) { ) {
substitutions = { ...settings.shaderMacros, ...substitutions }; substitutions = { ...settings.shaderMacros, ...substitutions };
this.programPromise = createProgram( this.program = createProgram(
this.gl, this.gl,
vertexShaderSource, vertexShaderSource,
fragmentShaderSource, fragmentShaderSource,
substitutions substitutions
); );
}
public async initialize(): Promise<void> {
this.program = await this.programPromise;
this.queryUniforms(); this.queryUniforms();
} }

View file

@ -20,18 +20,13 @@ export class UniformArrayAutoScalingProgram implements IProgram {
shaderSources: [string, string], shaderSources: [string, string],
private descriptors: Array<DrawableDescriptor> private descriptors: Array<DrawableDescriptor>
) { ) {
const names = descriptors.map((o) => o.countMacroName);
for (const combination of getCombinations( for (const combination of getCombinations(
descriptors.map((o) => o.shaderCombinationSteps) descriptors.map((o) => o.shaderCombinationSteps)
)) { )) {
this.createProgram(names, combination, shaderSources); this.createProgram(descriptors, combination, shaderSources);
} }
} }
public async initialize(): Promise<void> {
await Promise.all(this.programs.map((p) => p.program.initialize()));
}
public bindAndSetUniforms(uniforms: { [name: string]: any }): void { public bindAndSetUniforms(uniforms: { [name: string]: any }): void {
const values = this.descriptors.map((d) => const values = this.descriptors.map((d) =>
uniforms[d.uniformName] ? uniforms[d.uniformName].length : 0 uniforms[d.uniformName] ? uniforms[d.uniformName].length : 0
@ -45,7 +40,7 @@ export class UniformArrayAutoScalingProgram implements IProgram {
this.descriptors.map((d, i) => { this.descriptors.map((d, i) => {
const difference = closest.values[i] - values[i]; const difference = closest.values[i] - values[i];
for (let i = 0; i < difference; i++) { for (let i = 0; i < difference; i++) {
d.empty.serializeToUniforms(uniforms, 0, mat2d.create()); d.empty.serializeToUniforms(uniforms, mat2d.create(), 0);
} }
}); });
} }
@ -75,12 +70,15 @@ export class UniformArrayAutoScalingProgram implements IProgram {
} }
private createProgram( private createProgram(
names: Array<string>, descriptors: Array<DrawableDescriptor>,
combination: Array<number>, combination: Array<number>,
shaderSources: [string, string] shaderSources: [string, string]
): FragmentShaderOnlyProgram { ): FragmentShaderOnlyProgram {
const substitutions = {}; const substitutions = {
names.forEach((v, i) => (substitutions[v] = combination[i].toString())); macroDefinitions: this.getMacroDefinitions(combination, descriptors),
declarations: this.getDeclarations(combination, descriptors),
functionCalls: this.getFunctionCalls(combination, descriptors),
};
const program = new FragmentShaderOnlyProgram(this.gl, shaderSources, substitutions); const program = new FragmentShaderOnlyProgram(this.gl, shaderSources, substitutions);
@ -91,4 +89,43 @@ export class UniformArrayAutoScalingProgram implements IProgram {
return program; return program;
} }
private getMacroDefinitions(
combination: Array<number>,
descriptors: Array<DrawableDescriptor>
): string {
return combination
.map((v, i) => `#define ${descriptors[i].uniformCountMacroName} ${v}`)
.join('\n');
}
private getDeclarations(
combination: Array<number>,
descriptors: Array<DrawableDescriptor>
): string {
return combination
.map((v, i) => {
if (v == 0 || descriptors[i].sdf === undefined) {
return '';
}
return descriptors[i].sdf!.shader;
})
.join('\n');
}
private getFunctionCalls(
combination: Array<number>,
descriptors: Array<DrawableDescriptor>
): string {
return combination
.map((v, i) => {
if (v == 0 || descriptors[i].sdf === undefined) {
return '';
}
return `${descriptors[i].sdf!.distanceFunctionName}(minDistance, color);`;
})
.join('\n');
}
} }

View file

@ -1,16 +0,0 @@
import { vec2 } from 'gl-matrix';
import { Drawable } from '../drawables/drawable';
export interface IRenderer {
initialize(): Promise<void>;
startFrame(deltaTime: DOMHighResTimeStamp): void;
finishFrame(): void;
drawShape(drawable: Drawable): void;
drawLight(light: Drawable): void;
readonly canvasSize: vec2;
setViewArea(topLeft: vec2, size: vec2): void;
setCursorPosition(position: vec2): void;
}

View file

@ -0,0 +1,14 @@
import { vec2 } from 'gl-matrix';
import { Drawable } from '../../drawables/drawable';
export interface Renderer {
setViewArea(topLeft: vec2, size: vec2): void;
addDrawable(drawable: Drawable): void;
renderDrawables(): void;
autoscaleQuality(deltaTime: DOMHighResTimeStamp): void;
readonly canvasSize: vec2;
setCursorPosition(position: vec2): void;
}

View file

@ -0,0 +1,4 @@
export enum RenderingPassName {
distance = 'distance',
pixel = 'pixel',
}

View file

@ -22,10 +22,6 @@ export class RenderingPass {
); );
} }
public async initialize(): Promise<void> {
await this.program.initialize();
}
public addDrawable(drawable: Drawable) { public addDrawable(drawable: Drawable) {
this.drawables.push(drawable); this.drawables.push(drawable);
} }
@ -71,8 +67,8 @@ export class RenderingPass {
primitivesNearTile.forEach((p) => primitivesNearTile.forEach((p) =>
p.serializeToUniforms( p.serializeToUniforms(
uniforms, uniforms,
uniforms.scaleWorldLengthToNDC, uniforms.transformWorldToNDC,
uniforms.transformWorldToNDC uniforms.scaleWorldLengthToNDC
) )
); );

View file

@ -1,57 +1,49 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { Drawable } from '../../drawables/drawable'; import { Drawable } from '../../drawables/drawable';
import { CircleLight } from '../../drawables/lights/circle-light'; import { DrawableDescriptor } from '../../drawables/drawable-descriptor';
import { Flashlight } from '../../drawables/lights/flashlight';
import { Circle } from '../../drawables/shapes/circle';
import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer'; import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer';
import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer'; import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer';
import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context'; import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context';
import { WebGlStopwatch } from '../graphics-library/helper/stopwatch'; import { WebGlStopwatch } from '../graphics-library/helper/stopwatch';
import { IRenderer } from '../i-renderer';
import distanceFragmentShader from '../shaders/distance-fs.glsl'; import distanceFragmentShader from '../shaders/distance-fs.glsl';
import distanceVertexShader from '../shaders/distance-vs.glsl'; import distanceVertexShader from '../shaders/distance-vs.glsl';
import lightsFragmentShader from '../shaders/shading-fs.glsl'; import lightsFragmentShader from '../shaders/shading-fs.glsl';
import lightsVertexShader from '../shaders/shading-vs.glsl'; import lightsVertexShader from '../shaders/shading-vs.glsl';
import { FpsAutoscaler } from './fps-autoscaler'; import { FpsAutoscaler } from './fps-autoscaler';
import { Renderer } from './renderer';
import { RenderingPass } from './rendering-pass'; import { RenderingPass } from './rendering-pass';
import { RenderingPassName } from './rendering-pass-name';
import { UniformsProvider } from './uniforms-provider'; import { UniformsProvider } from './uniforms-provider';
export class WebGl2Renderer implements IRenderer { export class WebGl2Renderer implements Renderer {
private gl: WebGL2RenderingContext; private gl: WebGL2RenderingContext;
private stopwatch?: WebGlStopwatch; private stopwatch?: WebGlStopwatch;
private uniformsProvider: UniformsProvider; private uniformsProvider: UniformsProvider;
private distanceFieldFrameBuffer: IntermediateFrameBuffer; private distanceFieldFrameBuffer: IntermediateFrameBuffer;
private lightingFrameBuffer: DefaultFrameBuffer; private lightingFrameBuffer: DefaultFrameBuffer;
private distancePass: RenderingPass; private passes: { [key in keyof typeof RenderingPassName]: RenderingPass };
private lightingPass: RenderingPass;
private autoscaler: FpsAutoscaler; private autoscaler: FpsAutoscaler;
private initializePromise: Promise<[void, void]>; constructor(private canvas: HTMLCanvasElement, descriptors: Array<DrawableDescriptor>) {
constructor(private canvas: HTMLCanvasElement) {
this.gl = getWebGl2Context(canvas); this.gl = getWebGl2Context(canvas);
this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(this.gl); this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(this.gl);
this.lightingFrameBuffer = new DefaultFrameBuffer(this.gl); this.lightingFrameBuffer = new DefaultFrameBuffer(this.gl);
this.distancePass = new RenderingPass( this.passes = {
this.gl, [RenderingPassName.distance]: new RenderingPass(
[distanceVertexShader, distanceFragmentShader], this.gl,
[Circle.descriptor], [distanceVertexShader, distanceFragmentShader],
this.distanceFieldFrameBuffer descriptors.filter(WebGl2Renderer.hasSdf),
); this.distanceFieldFrameBuffer
),
this.lightingPass = new RenderingPass( [RenderingPassName.pixel]: new RenderingPass(
this.gl, this.gl,
[lightsVertexShader, lightsFragmentShader], [lightsVertexShader, lightsFragmentShader],
[CircleLight.descriptor, Flashlight.descriptor], descriptors.filter((d) => !WebGl2Renderer.hasSdf(d)),
this.lightingFrameBuffer this.lightingFrameBuffer
); ),
};
this.initializePromise = Promise.all([
this.distancePass.initialize(),
this.lightingPass.initialize(),
]);
this.uniformsProvider = new UniformsProvider(this.gl); this.uniformsProvider = new UniformsProvider(this.gl);
@ -70,35 +62,37 @@ export class WebGl2Renderer implements IRenderer {
} }
} }
public async initialize(): Promise<void> { private static hasSdf(descriptor: DrawableDescriptor) {
await this.initializePromise; return Object.prototype.hasOwnProperty.call(descriptor, 'sdf');
} }
public drawShape(shape: Drawable) { public addDrawable(drawable: Drawable): void {
this.distancePass.addDrawable(shape); if (WebGl2Renderer.hasSdf((drawable.constructor as typeof Drawable).descriptor)) {
this.passes[RenderingPassName.distance].addDrawable(drawable);
} else {
this.passes[RenderingPassName.pixel].addDrawable(drawable);
}
} }
public drawLight(light: Drawable) { public autoscaleQuality(deltaTime: DOMHighResTimeStamp) {
this.lightingPass.addDrawable(light);
}
public startFrame(deltaTime: DOMHighResTimeStamp) {
this.autoscaler.autoscale(deltaTime); this.autoscaler.autoscale(deltaTime);
}
public renderDrawables() {
this.stopwatch?.start(); this.stopwatch?.start();
this.distanceFieldFrameBuffer.setSize(); this.distanceFieldFrameBuffer.setSize();
this.lightingFrameBuffer.setSize(); this.lightingFrameBuffer.setSize();
}
public finishFrame() {
const common = { const common = {
distanceNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()), distanceNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()),
shadingNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()), shadingNdcPixelSize: 2 / Math.max(...this.distanceFieldFrameBuffer.getSize()),
}; };
this.distancePass.render(this.uniformsProvider.getUniforms(common)); this.passes[RenderingPassName.distance].render(
this.lightingPass.render( this.uniformsProvider.getUniforms(common)
);
this.passes[RenderingPassName.pixel].render(
this.uniformsProvider.getUniforms(common), this.uniformsProvider.getUniforms(common),
this.distanceFieldFrameBuffer.colorTexture this.distanceFieldFrameBuffer.colorTexture
); );

View file

@ -2,25 +2,16 @@
precision lowp float; precision lowp float;
// #define LINE_COUNT {lineCount}
// #define BLOB_COUNT {blobCount}
#define CIRCLE_COUNT {circleCount}
#define SURFACE_OFFSET 0.001 #define SURFACE_OFFSET 0.001
uniform float maxMinDistance; uniform float maxMinDistance;
uniform float distanceNdcPixelSize; uniform float distanceNdcPixelSize;
in vec2 position; in vec2 position;
float smoothMin(float a, float b) {macroDefinitions}
{
const float k = 2.0; {declarations}
a = pow(a, k);
b = pow(b, k);
return pow((a * b) / (a + b), 1.0 / k);
}
/* /*
#if LINE_COUNT > 0 #if LINE_COUNT > 0
uniform struct { uniform struct {
@ -54,22 +45,6 @@ float smoothMin(float a, float b)
minDistance = -myMinDistance; minDistance = -myMinDistance;
} }
#endif #endif
*/
#if CIRCLE_COUNT > 0
uniform struct {
vec2 center;
float radius;
}[CIRCLE_COUNT] circles;
void circleMinDistance(inout float minDistance, inout float color) {
for (int i = 0; i < CIRCLE_COUNT; i++) {
float dist = distance(circles[i].center, position) - circles[i].radius;
minDistance = min(minDistance, dist);
}
}
#endif
/*
#if BLOB_COUNT > 0 #if BLOB_COUNT > 0
uniform struct { uniform struct {
vec2 headCenter; vec2 headCenter;
@ -80,6 +55,15 @@ float smoothMin(float a, float b)
float k; float k;
}[BLOB_COUNT] blobs; }[BLOB_COUNT] blobs;
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);
}
float circleMinDistance(vec2 circleCenter, float radius) { float circleMinDistance(vec2 circleCenter, float radius) {
return distance(position, circleCenter) - radius; return distance(position, circleCenter) - radius;
} }
@ -112,17 +96,7 @@ void main() {
float minDistance = 10.0; //-maxMinDistance; float minDistance = 10.0; //-maxMinDistance;
float color = 1.0; float color = 1.0;
/*#if LINE_COUNT > 0 {functionCalls}
lineMinDistance(minDistance, color);
#endif
#if BLOB_COUNT > 0
blobMinDistance(minDistance, color);
#endif*/
#if CIRCLE_COUNT > 0
circleMinDistance(minDistance, color);
#endif
// minDistance / 2.0: NDC to UV scale // minDistance / 2.0: NDC to UV scale
fragmentColor = vec2(minDistance / 2.0, color); fragmentColor = vec2(minDistance / 2.0, color);

View file

@ -7,8 +7,7 @@ precision lowp float;
#define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25) #define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25)
#define SHADOW_HARDNESS 150.0 #define SHADOW_HARDNESS 150.0
#define CIRCLE_LIGHT_COUNT {circleLightCount} {macroDefinitions}
#define FLASHLIGHT_COUNT {flashlightCount}
uniform bool softShadowsEnabled; uniform bool softShadowsEnabled;
uniform vec2 squareToAspectRatioTimes2; uniform vec2 squareToAspectRatioTimes2;

View file

@ -2,8 +2,7 @@
precision lowp float; precision lowp float;
#define CIRCLE_LIGHT_COUNT {circleLightCount} {macroDefinitions}
#define FLASHLIGHT_COUNT {flashlightCount}
uniform mat3 modelTransform; uniform mat3 modelTransform;
in vec4 vertexPosition; in vec4 vertexPosition;

View file

@ -1,14 +1,20 @@
import { glMatrix } from 'gl-matrix'; import { glMatrix } from 'gl-matrix';
import { IRenderer } from './graphics/i-renderer'; import { DrawableDescriptor } from './drawables/drawable-descriptor';
import { Renderer } from './graphics/rendering/renderer';
import { WebGl2Renderer } from './graphics/rendering/webgl2-renderer'; import { WebGl2Renderer } from './graphics/rendering/webgl2-renderer';
import { applyArrayPlugins } from './helper/array'; import { applyArrayPlugins } from './helper/array';
export { Drawable } from './drawables/drawable'; export { Drawable } from './drawables/drawable';
export { CircleLight } from './drawables/lights/circle-light'; export { CircleLight } from './drawables/lights/circle-light';
export { Flashlight } from './drawables/lights/flashlight';
export { Circle } from './drawables/shapes/circle'; export { Circle } from './drawables/shapes/circle';
export { RenderingPassName } from './graphics/rendering/rendering-pass-name';
export const compile = (canvas: HTMLCanvasElement): IRenderer => { export const compile = (
canvas: HTMLCanvasElement,
descriptors: Array<DrawableDescriptor>
): Renderer => {
glMatrix.setMatrixArrayType(Array); glMatrix.setMatrixArrayType(Array);
applyArrayPlugins(); applyArrayPlugins();
return new WebGl2Renderer(canvas); return new WebGl2Renderer(canvas, descriptors);
}; };

View file

@ -12,6 +12,8 @@
"moduleResolution": "Node", "moduleResolution": "Node",
"module": "commonjs", "module": "commonjs",
"declaration": true, "declaration": true,
"composite": true,
"declarationMap": true,
"lib": ["es6", "dom", "es2017"] "lib": ["es6", "dom", "es2017"]
} }
} }

View file

@ -65,7 +65,7 @@ module.exports = {
{ {
test: /\.ts$/, test: /\.ts$/,
use: { use: {
loader: 'awesome-typescript-loader', loader: 'ts-loader',
}, },
exclude: /node_modules/, exclude: /node_modules/,
}, },