new rendering code, still cant do shit, but its on webgl now so lessgooo gpu and vertices + shaders im coming for you

This commit is contained in:
2026-04-01 18:11:17 +02:00
parent 5c413f4e8b
commit 92418e7e4e
8 changed files with 927 additions and 270 deletions
+114
View File
@@ -0,0 +1,114 @@
import type Vector2 from '$lib/vector';
class Renderer {
private gl: WebGL2RenderingContext;
private posBuffer!: WebGLBuffer;
private program!: WebGLProgram;
constructor(canvas: HTMLCanvasElement) {
let context = canvas.getContext('webgl2');
if (!context) throw new Error(`Failed to get webgl2 context from ${canvas}`);
this.gl = context;
}
public async init() {
try {
const vert: WebGLShader = await this.loadShader(
this.gl,
'src/lib/shimeji/renderer/shaders/vertex_shader.vert',
this.gl.VERTEX_SHADER
);
const frag: WebGLShader = await this.loadShader(
this.gl,
'src/lib/shimeji/renderer/shaders/fragment_shader.frag',
this.gl.FRAGMENT_SHADER
);
const program = this.gl.createProgram();
this.program = program;
this.gl.attachShader(program, vert);
this.gl.attachShader(program, frag);
this.gl.linkProgram(program);
if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
console.error(this.gl.getProgramInfoLog(program));
this.gl.deleteProgram(program);
throw new Error(`Failed to link program to webgl2 context ${program}`);
}
const pos = this.gl.createBuffer();
this.posBuffer = pos;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
let resUniLoc = this.gl.getUniformLocation(program, 'u_resolution');
this.gl.uniform2f(resUniLoc, this.gl.canvas.width, this.gl.canvas.height);
this.gl.clearColor(0, 0, 0, 0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.gl.useProgram(program);
this.gl.enableVertexAttribArray(0);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
this.gl.vertexAttribPointer(0, 2, this.gl.FLOAT, false, 0, 0);
} catch (error) {
console.log(error);
this.gl.VERTEX_SHADER;
}
}
private async loadShader(
gl: WebGL2RenderingContext,
path: string,
type: typeof gl.VERTEX_SHADER | typeof gl.FRAGMENT_SHADER
) {
const response = await fetch(path);
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
const data = await response.text();
const shader = gl.createShader(type);
if (!shader) throw new Error(`Failed to create the shader ${shader}`);
gl.shaderSource(shader, data);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
throw new Error(`Failed to compile the shader ${shader}`);
}
return shader;
}
public UpdateBounds(width: number, height: number): void {
this.gl.viewport(0, 0, width, height);
}
public Draw(pos: Vector2, size: number): void {
let x1 = pos.x - size;
let x2 = pos.x + size;
let y1 = pos.y + size;
let y2 = pos.y - size;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.posBuffer);
this.gl.bufferData(
this.gl.ARRAY_BUFFER,
new Float32Array([x1, y1, x2, y1, x2, y2, x1, y1, x1, y2, x2, y2]),
this.gl.STATIC_DRAW
);
var primitiveType = this.gl.TRIANGLES;
var offset = 0;
var count = 6;
this.gl.drawArrays(primitiveType, offset, count);
}
}
export default Renderer;
@@ -0,0 +1,10 @@
#version 300 es
precision mediump float;
out vec4 color;
in vec4 v_color;
void main() {
color = v_color;
}
@@ -0,0 +1,15 @@
#version 300 es
layout ( location = 0 ) in vec2 a_position;
uniform vec2 u_resolution;
out vec4 v_color;
void main() {
vec2 zeroToOne = a_position / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
//gl_Position = vec4(a_position, 0, 1);
v_color = vec4(a_position.xyx * 0.5 + 0.5, 1.0);
}
+183 -181
View File
@@ -1,210 +1,212 @@
import Vector2 from "../vector";
import Renderer from '$lib/shimeji/renderer/renderer';
import Vector2 from '../vector';
export class Shimeji {
private element: HTMLElement;
private canvas: HTMLCanvasElement;
private rect: DOMRect;
private pos: Vector2 = Vector2.zero;
private vel: Vector2 = Vector2.zero;
private element: HTMLElement;
private canvas: HTMLCanvasElement;
private renderer: Renderer;
private rect: DOMRect;
private mousePos: Vector2 = Vector2.zero;
private pos: Vector2 = Vector2.zero;
private vel: Vector2 = Vector2.zero;
private pivot: Vector2 = Vector2.zero;
private mousePos: Vector2 = Vector2.zero;
private isBeingDragged: boolean = false;
private rafId: number | null = null;
private prevDeltaTime: number = 0;
private readonly TIMESCALE: number = 1;
private readonly RESTITUTION: number = 0.4;
private readonly CURSOR_STRENGTH: number = 500;
private readonly DAMPING: number = 1;
private readonly MASS: number = 1;
private readonly FRICTION: number = 0.9;
private readonly GRAVITY: number = 50;
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
constructor(element: HTMLElement, canvas: HTMLCanvasElement) {
this.element = element;
this.canvas= canvas;
this.rect = element.getBoundingClientRect();
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
this.pos.set(window.innerWidth / 2, window.innerHeight/ 2);
this.updateBounds();
window.addEventListener('resize', () => this.updateBounds());
private pivot: Vector2 = Vector2.zero;
console.log(this.element.getBoundingClientRect());
this.setupDragEvents();
}
private updateBounds(): void {
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
start(): void {
if (this.rafId !== null) return;
private isBeingDragged: boolean = false;
const firstFrame = (delta: number) => {
this.prevDeltaTime = delta;
this.rafId = requestAnimationFrame(animate);
}
private rafId: number | null = null;
private prevDeltaTime: number = 0;
const animate = (delta: number) => {
let dt = (delta - this.prevDeltaTime) / 1000; // seconds
dt = Math.min(dt, 0.05 * this.TIMESCALE); // cap to 50 ms
this.prevDeltaTime = delta;
private readonly TIMESCALE: number = 1;
private readonly RESTITUTION: number = 0.4;
private readonly CURSOR_STRENGTH: number = 500;
private readonly DAMPING: number = 1;
private readonly MASS: number = 1;
private readonly FRICTION: number = 0.9;
private readonly GRAVITY: number = 50;
this.updatePhysics(dt);
this.applyBoundaries();
this.render();
this.rafId = requestAnimationFrame(animate);
};
this.rafId = requestAnimationFrame(firstFrame);
}
stop(): void {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
}
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
private setupDragEvents(): void {
this.element.addEventListener('mousedown', (e) => {
e.preventDefault();
this.isBeingDragged = true;
this.element.style.cursor = 'grabbing';
constructor(element: HTMLElement, canvas: HTMLCanvasElement, renderer: Renderer) {
this.element = element;
this.canvas = canvas;
this.renderer = renderer;
this.rect = element.getBoundingClientRect();
const parent = this.element.parentElement;
if(parent) parent.style.cursor = 'grabbing';
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
this.pivot.x = e.offsetX - this.rect.width / 2;
this.pivot.y = e.offsetY - this.rect.height / 2;
});
this.pos.set(window.innerWidth / 2, window.innerHeight / 2);
document.addEventListener('mousemove', (e) => {
this.mousePos.x = e.pageX;
this.mousePos.y = e.pageY;
});
this.updateBounds();
window.addEventListener('resize', () => this.updateBounds());
document.addEventListener('mouseup', (e) => {
if(this.isBeingDragged) {
this.isBeingDragged = false;
this.element.style.cursor = 'grab';
console.log(this.element.getBoundingClientRect());
const parent = this.element.parentElement;
if(parent) parent.style.cursor = 'auto';
this.setupDragEvents();
}
this.pivot = Vector2.zero;
}
private updateBounds(): void {
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
});
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.renderer.UpdateBounds(window.innerWidth, window.innerHeight);
}
this.element.addEventListener('dragstart', (e) => {
e.preventDefault();
});
}
private updatePhysics(dt: number): void {
if (this.isBeingDragged) {
const direction: Vector2 = this.mousePos.sub(this.pivot).sub(this.pos);
const force: Vector2 = direction.mul(this.CURSOR_STRENGTH);
start(): void {
if (this.rafId !== null) return;
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
acceleration.mulEq(dt);
const firstFrame = (delta: number) => {
this.prevDeltaTime = delta;
this.rafId = requestAnimationFrame(animate);
};
this.vel.addEq(acceleration);
this.vel.mulEq(0.8);
}
this.vel.y += this.GRAVITY;
this.vel.mulEq(this.DAMPING);
if (this.pos.y + this.rect.width >= this.bounds.maxY) {
this.vel.x *= this.FRICTION;
}
const animate = (delta: number) => {
let dt = (delta - this.prevDeltaTime) / 1000;
dt = Math.min(dt, 0.05 * this.TIMESCALE);
this.prevDeltaTime = delta;
const outVel = this.vel.mul(dt);
this.pos.addEq(outVel);
}
private applyBoundaries(): void {
const leftBound = this.rect.width / 2;
const rightBound = this.bounds.maxX - this.rect.width / 2;
if (this.pos.x < leftBound) {
this.pos.x = leftBound;
this.vel.x = -(this.RESTITUTION) * this.vel.x;
} else if (this.pos.x > rightBound) {
this.pos.x = rightBound;
this.vel.x = -(this.RESTITUTION) * this.vel.x;
}
const topBound = this.rect.height / 2;
const bottomBound = this.bounds.maxY - this.rect.height / 2;
if (this.pos.y < topBound) {
this.pos.y = topBound;
this.vel.y = -(this.RESTITUTION) * this.vel.y;
} else if (this.pos.y > bottomBound) {
this.pos.y = bottomBound;
this.vel.y = -(this.RESTITUTION) * this.vel.y;
}
}
this.updatePhysics(dt);
this.applyBoundaries();
this.render();
this.rafId = requestAnimationFrame(animate);
};
private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) {
const ctx = this.canvas.getContext("2d")!;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.strokeStyle = "white";
ctx.lineWidth = 0.1
ctx.beginPath();
ctx.moveTo(pos1.x, pos1.y);
ctx.lineTo(pos2.x, pos2.y);
ctx.stroke();
}
private render(): void {
this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px)`;
this.rafId = requestAnimationFrame(firstFrame);
}
/* if(this.isBeingDragged) {
stop(): void {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
}
private setupDragEvents(): void {
this.element.addEventListener('mousedown', (e) => {
e.preventDefault();
this.isBeingDragged = true;
this.element.style.cursor = 'grabbing';
const parent = this.element.parentElement;
if (parent) parent.style.cursor = 'grabbing';
this.pivot.x = e.offsetX - this.rect.width / 2;
this.pivot.y = e.offsetY - this.rect.height / 2;
});
document.addEventListener('mousemove', (e) => {
this.mousePos.x = e.pageX;
this.mousePos.y = e.pageY;
});
document.addEventListener('mouseup', (e) => {
if (this.isBeingDragged) {
this.isBeingDragged = false;
this.element.style.cursor = 'grab';
const parent = this.element.parentElement;
if (parent) parent.style.cursor = 'auto';
this.pivot = Vector2.zero;
}
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
});
this.element.addEventListener('dragstart', (e) => {
e.preventDefault();
});
}
private updatePhysics(dt: number): void {
if (this.isBeingDragged) {
const direction: Vector2 = this.mousePos.sub(this.pivot).sub(this.pos);
const force: Vector2 = direction.mul(this.CURSOR_STRENGTH);
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
acceleration.mulEq(dt);
this.vel.addEq(acceleration);
this.vel.mulEq(0.8);
}
this.vel.y += this.GRAVITY;
this.vel.mulEq(this.DAMPING);
if (this.pos.y + this.rect.width >= this.bounds.maxY) {
this.vel.x *= this.FRICTION;
}
const outVel = this.vel.mul(dt);
this.pos.addEq(outVel);
}
private applyBoundaries(): void {
const leftBound = this.rect.width / 2;
const rightBound = this.bounds.maxX - this.rect.width / 2;
if (this.pos.x < leftBound) {
this.pos.x = leftBound;
this.vel.x = -this.RESTITUTION * this.vel.x;
} else if (this.pos.x > rightBound) {
this.pos.x = rightBound;
this.vel.x = -this.RESTITUTION * this.vel.x;
}
const topBound = this.rect.height / 2;
const bottomBound = this.bounds.maxY - this.rect.height / 2;
if (this.pos.y < topBound) {
this.pos.y = topBound;
this.vel.y = -this.RESTITUTION * this.vel.y;
} else if (this.pos.y > bottomBound) {
this.pos.y = bottomBound;
this.vel.y = -this.RESTITUTION * this.vel.y;
}
}
private drawRay(pos1: { x: number; y: number }, pos2: { x: number; y: number }) {
const ctx = this.canvas.getContext('2d')!;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.strokeStyle = 'white';
ctx.lineWidth = 0.1;
ctx.beginPath();
ctx.moveTo(pos1.x, pos1.y);
ctx.lineTo(pos2.x, pos2.y);
ctx.stroke();
}
private render(): void {
this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px)`;
this.renderer.Draw(this.pos, this.rect.width / 2);
/* if(this.isBeingDragged) {
this.drawRay(
{x: this.mouseX, y: this.mouseY},
{x: this.x + this.pivotX, y: this.y + this.pivotY}
)
} */
}
addImpulse(x: number, y: number): void {
this.vel.x += x;
this.vel.y += y;
}
}
moveTo(pos: number) {
}
}
addImpulse(x: number, y: number): void {
this.vel.x += x;
this.vel.y += y;
}
moveTo(pos: number) {}
}
+54 -43
View File
@@ -1,58 +1,69 @@
<script lang="ts">
import { Shimeji } from "$lib/stores/shimeji";
import { onMount } from "svelte";
import Renderer from '$lib/shimeji/renderer/renderer';
import { Shimeji } from '$lib/stores/shimeji';
import Vector2 from '$lib/vector';
import { onMount } from 'svelte';
const drag: number = 3;
const speed: number = 2;
const drag: number = 3;
const speed: number = 2;
let shimeji: Shimeji;
let sprite: HTMLElement;
let canvas: HTMLCanvasElement;
let shown: boolean = $state(false);
let shimeji: Shimeji;
let renderer: Renderer;
let sprite: HTMLElement;
let canvas: HTMLCanvasElement;
let shown: boolean = $state(false);
function genRandomPos(min: number, max: number): number{
const out = Math.random() * (max - min) + min;
return out;
}
function genRandomPos(min: number, max: number): number {
const out = Math.random() * (max - min) + min;
return out;
}
onMount(() => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
async function fetchShader(path: string): Promise<string> {
const response = await fetch(path);
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
return await response.text();
}
shimeji = new Shimeji(sprite, canvas);
shimeji.start();
onMount(async () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
shown = true;
const vert = await fetchShader('src/lib/shimeji/renderer/shaders/vertex_shader.vert');
const frag = await fetchShader('src/lib/shimeji/renderer/shaders/fragment_shader.frag');
document.addEventListener('keydown', (e) => {
if(e.key === 'a') {
shimeji.addImpulse(-500, -100);
}
if(e.key === 'd') {
shimeji.addImpulse(500, -100);
}
if(e.key === 'space') {
shimeji.moveTo(genRandomPos(200, window.innerWidth - 200));
}
});
console.log(vert, '\n', frag);
return () => {
shimeji.stop();
};
renderer = new Renderer(canvas);
await renderer.init();
renderer.Draw(new Vector2(500, 500), 50);
})
/* shimeji = new Shimeji(sprite, canvas, renderer);
shimeji.start();
shown = true;
document.addEventListener('keydown', (e) => {
if (e.key === 'a') {
shimeji.addImpulse(-500, -100);
}
if (e.key === 'd') {
shimeji.addImpulse(500, -100);
}
if (e.key === 'space') {
shimeji.moveTo(genRandomPos(200, window.innerWidth - 200));
}
}); */
});
</script>
<div class=" absolute z-20 size-full overflow-clip ">
<canvas bind:this={canvas} style=" stroke-width: 5px;" class=" stroke-red-500 absolute z-2 size-full"></canvas>
<div bind:this={sprite} class=" z-30 cursor-grab origin-center transform-flat -translate-1/2 will-change-transform absolute bg-amber-400 size-20"></div>
<div class=" absolute z-20 size-full overflow-clip">
<canvas
bind:this={canvas}
style=" stroke-width: 5px;"
class=" absolute z-2 size-full stroke-red-500"
></canvas>
<!-- <div
bind:this={sprite}
class=" absolute z-30 size-20 origin-center -translate-1/2 cursor-grab bg-amber-400 opacity-15 will-change-transform transform-flat"
></div> -->
</div>
<style>
</style>
-9
View File
@@ -1,9 +0,0 @@
<script lang="ts">
import Shimeji from "../../modules/Shimeji.svelte";
</script>
<Shimeji />