Files
bworld/client/renderer/shapes.ts
T
2026-10-12 15:09:22 -03:00

98 lines
2.3 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { flush_batch, get_current_texture, push_quad, push_vertex, set_current_texture, white_tex } from "./core.ts";
export function draw_rect(
x: number,
y: number,
w: number,
h: number,
color: [number, number, number, number] = [1, 1, 1, 1],
) {
if (get_current_texture() !== white_tex) {
flush_batch();
set_current_texture(white_tex!);
}
push_quad(x, y, w, h, 0, 0, 1, 1, color[0], color[1], color[2], color[3]);
}
export function draw_rect_stroke(
x: number,
y: number,
w: number,
h: number,
color: [number, number, number, number] = [1, 1, 1, 1],
thickness: number = 1,
) {
// top
draw_rect(x, y, w, thickness, color);
// bottom
draw_rect(x, y + h - thickness, w, thickness, color);
// left
draw_rect(x, y, thickness, h, color);
// right
draw_rect(x + w - thickness, y, thickness, h, color);
}
// a plane in the world to lay 2d drawing on: origin is its top left, x goes along right and y along -up, like the
// screen. for text and rects facing a direction, like nameplates facing the camera
export type Plane3d = {
origin: [number, number, number];
right: [number, number, number];
up: [number, number, number];
};
// a quad at x, y on the plane, in its units. wound counter clockwise seen from where right and up point the usual way,
// so it's culled from behind
export function push_plane_quad(
plane: Plane3d,
x: number,
y: number,
w: number,
h: number,
u0: number,
v0: number,
u1: number,
v1: number,
color: readonly number[],
) {
const { origin: o, right: rt, up } = plane;
const corner = (cx: number, cy: number, u: number, v: number) =>
push_vertex(
o[0] + rt[0] * cx - up[0] * cy,
o[1] + rt[1] * cx - up[1] * cy,
o[2] + rt[2] * cx - up[2] * cy,
u,
v,
color[0],
color[1],
color[2],
color[3],
);
const x2 = x + w;
const y2 = y + h;
corner(x, y, u0, v0);
corner(x, y2, u0, v1);
corner(x2, y2, u1, v1);
corner(x, y, u0, v0);
corner(x2, y2, u1, v1);
corner(x2, y, u1, v0);
}
export function draw_rect_3d(
plane: Plane3d,
x: number,
y: number,
w: number,
h: number,
color: readonly number[] = [1, 1, 1, 1],
) {
if (get_current_texture() !== white_tex) {
flush_batch();
set_current_texture(white_tex!);
}
push_plane_quad(plane, x, y, w, h, 0, 0, 1, 1, color);
}