Commit 61d20977 authored by Laureline Nevin's avatar Laureline Nevin ⌨️
Browse files

Split export window renderer into two shaders

parent 21a4c3f8
Loading
Loading
Loading
Loading
+1 −1
Changes for index.html: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -131,7 +131,7 @@
<dialog id="message" class="drop-shadow" ref="messageDialog" @click="app.onDialogClick">
    <h1></h1>
    <p></p>
    <button class="btn-dark" type="reset" autofocus @click="$refs.messageDialog.close()" v-t="ok"></button>
    <button class="btn-dark" type="reset" autofocus @click="$refs.messageDialog.close()" v-t="ok">Ok</button>
</dialog>
<dialog id="create-inmemory" ref="memCreateDia" class="drop-shadow" @click="app.onDialogClick"
        @close="fn.cancelCreateMemoryDataset($el.returnValue)">
+142 −31
Changes for src/gl-program.ts: 142 added lines, 31 removed lines.
Original line number Diff line number Diff line
@@ -3,7 +3,9 @@ import rlghtFrgSource from './shaders/relight.frag';
import lghtbllVtxSource from './shaders/lightball.vert';
import lghtbllFrgSource from './shaders/lightball.frag';
import exportRectVtxSource from './shaders/exportRect.vert';
import exportCornerVtxSource from './shaders/exportCorner.vert';
import exportRectFrgSource from './shaders/exportRect.frag';
import exportCornerFrgSource from './shaders/exportCorner.frag';
import { mat4, vec2, vec3 } from 'gl-matrix';
import { Controls, CONTROLS_SET_UNIFORMS, State } from './control.ts';
import { DEBUG, Exported, GL } from './utils.ts';
@@ -146,17 +148,38 @@ abstract class GLProgramBase<Attribs extends string[], Uniforms extends string[]
        if (!this.gl.getShaderParameter(shader, GL.COMPILE_STATUS)) {
            let err = this.gl.getShaderInfoLog(shader);
            this.gl.deleteShader(shader);
            const line = err?.match(/ERROR: \d+:(\d+):/);
            if (line) {
                const l = parseInt(line[1]) - 1;
                const lines = source.split('\n')
                    .map((s, i) => Math.abs(i - l) <= 3 ? (i === l ? '>>' : '| ') + s : null)
                    .filter((s) => s)
                    .join('\n');
                err += '\n' + lines;
            const errReg = /ERROR: \d+:(\d+): (.*)/g;
            const errors = err && Array.from(err.matchAll(errReg)).map(([_, l, e]) => [parseInt(l) - 1, e] as const),
                LINES_CONTEXT = 3;
            if (errors && errors.length > 0) {
                errors.sort((a, b) => a[0] - b[0]);
                let l = 0,
                    nextErrLine = errors[0][0],
                    lastErrLine = -(1 << 20);
                const lines = source.split('\n'),
                    outLines = new Array<string>(),
                    padSize = Math.ceil(Math.log10(lines.length));
                for (const line of lines) {
                    if (l - lastErrLine <= LINES_CONTEXT || nextErrLine - l <= LINES_CONTEXT) {
                        if (nextErrLine - l === LINES_CONTEXT && outLines.length > 0)
                            outLines.push('-'.repeat(padSize) + ' --- --- ---');
                        outLines.push(`${l.toString().padStart(padSize, ' ')}: ` + line);
                        while (l === nextErrLine) {
                            const e = errors.splice(0, 1)[0];
                            outLines.push(`${' '.repeat(padSize + 1)}>  ${e[1]}`);
                            lastErrLine = nextErrLine;
                            nextErrLine = errors.length > 0 ? errors[0][0] : Number.MAX_SAFE_INTEGER;
                        }
                    }
                    l++;
                }

                err = err?.substring(0, err.search(errReg)) + '\n' + outLines.join('\n');
            }
            throw new Error(
                `An error occurred compiling the ${type === GL.VERTEX_SHADER ? 'vertex' : 'fragment'} shader: ${err}`,
                `An error occurred compiling the ${
                    type === GL.VERTEX_SHADER ? 'vertex' : 'fragment'
                } shader of class ${this.constructor.name}: ${err}`,
            );
        }

@@ -376,21 +399,36 @@ export class ExportRectProgram extends GLProgramBase<
    public static readonly PARAMS = {
        cornerRadius: 25,
        lineSize: 4,
        color: [1., 1., 0., .5],
    } as const;
        color: [1, 1, 0, 0.5] as const,
    };
    static attributes = {
        vertexPosition: GLProgramBase.newAttribute('aVertexPosition', 2, WebGLRenderingContext.FLOAT),
    };
    static uniformNames = {
        projectionMatrix: 'uProjectionMatrix',
    static commonUniformNames = {
        color: 'uColor',
        exportRect: 'uExportRect',
        lineWidth: 'uLineWidth',
        projectionMatrix: 'uProjectionMatrix',
    };
    static uniformNames = {
        ...ExportRectProgram.commonUniformNames,
        renderRect: 'uRenderRect',
        parameters: 'uParameters',
        color: 'uColor',
    };
    static cornerUniformNames = {
        ...ExportRectProgram.commonUniformNames,
        cornerCenter: 'uCornerCenter',
        cornerRadius: 'uCornerRadius',
    };

    constructor(gl: WebGLRenderingContext) {
        super(gl, exportRectVtxSource, exportRectFrgSource, ExportRectProgram.attributes, ExportRectProgram.uniformNames);
        super(
            gl,
            exportRectVtxSource,
            exportRectFrgSource,
            ExportRectProgram.attributes,
            ExportRectProgram.uniformNames,
        );

        this.buffers = {
            vertexPosition: super.initF32Buffer(this.gl, [0, 0, 1, 0, 0, 1, 1, 1]),
        };
@@ -399,37 +437,110 @@ export class ExportRectProgram extends GLProgramBase<
        gl.clearColor(0.0, 0.0, 0.0, 0.0); // Clear to transparent
    }

    private static setCommonParams(
        gl: WebGLRenderingContext,
        data: RenderData,
        uniforms: { [key: string]: WebGLUniformLocation },
    ): typeof ExportRectProgram.PARAMS {
        let { cornerRadius, color, lineSize } = ExportRectProgram.PARAMS;
        cornerRadius /= Math.min(1, data.viewport.zoom);
        lineSize /= Math.min(1, data.viewport.zoom);

        gl.uniformMatrix4fv(uniforms.projectionMatrix, false, data.viewport.projectionMat);

        for (const [name, value] of [
            ['exportRect', [...data.exportParams!.offset, ...data.exportParams!.size]],
            ['renderRect', [0, 0, ...data.renderArea]],
            ['lineWidth', [lineSize]],
            ['cornerRadius', [cornerRadius]],
            ['color', color],
        ] as [string, number[]][]) {
            const location = uniforms[name];
            if (location) {
                const func = [gl.uniform1fv, gl.uniform2fv, gl.uniform3fv, gl.uniform4fv][value.length - 1];
                func.call(gl, location, value);
            }
        }
        return { cornerRadius, color, lineSize };
    }

    public render(data: RenderData): string {
        if (!data.exportParams)
            throw new Error("ExportRectProgram called with no export params");
        if (!data.exportParams) throw new Error('ExportRectProgram called with no export params');
        const gl = this.gl;
        let output = '== ExportRectProgram ==\n';

        gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.useProgram(this.program);

        let { cornerRadius, color, lineSize } = ExportRectProgram.PARAMS;
        cornerRadius /= data.viewport.zoom;
        lineSize /= data.viewport.zoom;
        let { color, lineSize } = ExportRectProgram.setCommonParams(gl, data, this.uniformLocations);

        gl.uniformMatrix4fv(this.uniformLocations.projectionMatrix, false, data.viewport.projectionMat);
        const area = new Rect(0, 0, ...data.renderArea).grow(lineSize);
        this.setAttribute('vertexPosition');
        this.gl.bufferData(GL.ARRAY_BUFFER, area.vertexPositions(), GL.DYNAMIC_DRAW);
        gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4);

        output +=
            `Area: ${area}\n  color: ${color}\n  lineSize: ${lineSize}\n` +
            `  exportRect: ${new Rect(...data.exportParams.offset, ...data.exportParams.size)}\n` +
            `  renderRect: ${new Rect(0, 0, ...data.renderArea)}\n`;

        gl.uniform4fv(this.uniformLocations.color, color);
        gl.uniform2f(this.uniformLocations.parameters, cornerRadius, lineSize);
        gl.uniform4f(this.uniformLocations.exportRect,
            ...data.exportParams.offset, ...data.exportParams.size);
        gl.uniform4f(this.uniformLocations.renderRect,
            0, 0, ...data.renderArea);
        output += this.cornerProgram.render(data);

        const area = new Rect(0, 0, ...data.renderArea)
            .grow(cornerRadius + lineSize * 2 + 1);
        this.setAttribute("vertexPosition");
        return output;
    }

    private cornerProgram = new (class extends GLProgramBase<
        [keyof typeof ExportRectProgram.attributes],
        [keyof typeof ExportRectProgram.cornerUniformNames]
    > {
        static attributes = ExportRectProgram.attributes;
        constructor(rect: ExportRectProgram) {
            super(
                rect.gl,
                exportCornerVtxSource,
                exportCornerFrgSource,
                ExportRectProgram.attributes,
                ExportRectProgram.cornerUniformNames,
            );
            this.buffers = {
                vertexPosition: super.initF32Buffer(this.gl, [0, 0, 1, 0, 0, 1, 1, 1]),
            };
        }

        public render(data: RenderData): string {
            if (!data.exportParams) throw new Error('ExportCornerProgram called with no export params');
            const gl = this.gl;
            let output = '== ExportCornerProgram ==\n';

            gl.useProgram(this.program);
            let { cornerRadius, lineSize } = ExportRectProgram.setCommonParams(gl, data, this.uniformLocations);

            const minX = data.exportParams.offset[0] - lineSize / 2,
                minY = data.exportParams.offset[1] - lineSize / 2,
                width = data.exportParams.size[0] + lineSize,
                height = data.exportParams.size[1] + lineSize,
                cornerArea = (cornerRadius + lineSize) * 2 + 1;
            this.setAttribute('vertexPosition');

            for (const corner of [
                [0, 0],
                [1, 0],
                [0, 1],
                [1, 1],
            ]) {
                const cornerX = minX + width * corner[0],
                    cornerY = minY + height * corner[1];
                const area = new Rect(cornerX - cornerArea / 2, cornerY - cornerArea / 2, cornerArea, cornerArea);
                gl.uniform2f(this.uniformLocations.cornerCenter, cornerX, cornerY);
                this.gl.bufferData(GL.ARRAY_BUFFER, area.vertexPositions(), GL.DYNAMIC_DRAW);
                gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4);
            }

            output += `Corner radius: ${cornerRadius}\n`;

            return output;
        }
    })(this);
}
export function resizeCanvasToDisplaySize(gl: WebGLRenderingContext, canvasSize?: [number, number]) {
    if (gl.canvas instanceof OffscreenCanvas) return false;
+28 −0
Changes for src/shaders/exportCorner.frag: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
precision mediump float;

uniform mediump vec4 uColor;
uniform mediump vec2 uCornerCenter;
uniform mediump float uCornerRadius;
uniform mediump vec4 uExportRect;
uniform mediump float uLineWidth;

varying mediump vec2 vVertexCoord;

bool inRect(vec2 pos, vec4 rect) {
    return pos.x > rect.x && pos.y > rect.y && pos.x < rect.x + rect.z && pos.y < rect.y + rect.w;
}

void main(void) {
    float cornerDistance = distance(vVertexCoord, uCornerCenter);
    bool inCorner = bool(cornerDistance <= uCornerRadius);// Redundant constructor because of an IDE issue
    bool onBorder = inCorner && (uCornerRadius - cornerDistance <= uLineWidth);
    if (inCorner && !inRect(vVertexCoord, uExportRect)) {
        vec4 col = uColor;
        if (!onBorder) {
            col.a *= .5;
        }
        gl_FragColor = col;
    } else {
        discard;
    }
}
 No newline at end of file
+10 −0
Changes for src/shaders/exportCorner.vert: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
uniform mat4 uProjectionMatrix;

attribute vec4 aVertexPosition;

varying mediump vec2 vVertexCoord;

void main(void) {
    gl_Position = uProjectionMatrix * aVertexPosition;
    vVertexCoord = aVertexPosition.xy;
}
 No newline at end of file
+11 −29
Changes for src/shaders/exportRect.frag: 11 added lines, 29 removed lines.
Original line number Diff line number Diff line
precision mediump float;

uniform mediump vec4 uColor;
uniform mediump vec2 uParameters;
uniform mediump vec4 uRenderRect;
uniform mediump vec4 uExportRect;
uniform mediump float uLineWidth;

varying mediump vec2 vPosition;
varying mediump vec2 vVertexCoord;

bool inRect(vec2 pos, vec4 rect) {
    return pos.x > rect.x && pos.y > rect.y && pos.x < rect.x + rect.z && pos.y < rect.y + rect.w;
float rectDist(vec2 pos, vec4 rect) {
    return max(
        max(rect.x - pos.x, rect.y - pos.y),
        max(pos.x - rect.x - rect.z, pos.y - rect.y - rect.w));
}

void main(void) {
    float cornerRadius = uParameters.x, lineWidth = uParameters.y;
    vec2 pos = vPosition; // Shorthand for readability
    vec2 recP = uExportRect.xy;
    vec2 recS = uExportRect.zw;
    float left = recP.x - pos.x, right = pos.x - recP.x - recS.x,
    top = recP.y - pos.y, bottom = pos.y - recP.y - recS.y;
    bool onBorder = bool(// Redundant constructor because of an IDE issue
    left >= 0. && left < lineWidth ||
    right >= 0. && right < lineWidth ||
    top >= 0. && top < lineWidth ||
    bottom >= 0. && bottom < lineWidth);
    float cornerDistance = min(
        min(distance(pos + vec2(.5, .5) * lineWidth, uExportRect.xy),
            distance(pos + vec2(-.5, .5) * lineWidth, uExportRect.xy + vec2(uExportRect.z, 0.))),
        min(distance(pos + vec2(.5, -.5) * lineWidth, uExportRect.xy + vec2(0., uExportRect.w)),
            distance(pos + vec2(-.5, -.5) * lineWidth, uExportRect.xy + uExportRect.zw)));
    bool onCorner = bool(cornerDistance <= cornerRadius && cornerRadius - cornerDistance <= lineWidth);
    if (inRect(pos, uExportRect)) {
    float dist = rectDist(vVertexCoord, uExportRect);
    if (dist < 0.) {
        discard; // Inside export rectangle
    } else if (inRect(pos, uExportRect + cornerRadius * vec4(-1, -1, 2, 2)) && onBorder || cornerDistance <= cornerRadius) {
    } else if (dist <= uLineWidth) {
        vec4 col = uColor;
        if (!onBorder && cornerRadius - cornerDistance > lineWidth) {
            col.a *= .5;
        }
        gl_FragColor = col;
    } else if (inRect(pos, uRenderRect)) {
        // In render area, outside of exporrt rectangle
        gl_FragColor = vec4(0., 0., 0., mod((pos.x + pos.y) / lineWidth / 2., 2.) > 1. ? .2 : .1);
    } else if (rectDist(vVertexCoord, uRenderRect) <= 0.) {
        // In render area, outside of export window
        gl_FragColor = vec4(0., 0., 0., mod((vVertexCoord.x + vVertexCoord.y) / uLineWidth / 2., 2.) > 1. ? .2 : .1);
    } else {
        // Outside of render area
        discard;
Loading