Skip to content

WIP cube GL demo #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 163 additions & 0 deletions cube/gldemo.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=0.5" />
<link rel="stylesheet" type="text/css" href="index.css" />
<title>Cube</title>
</head>

<body>

<div style="position: absolute; right: 0">

<div
title="Key[C] Whether to draw using a derived 'curved tile' layer whose cells are computed at the 4-corners of the base land-vs-water layer">
<input id="show_curves" type="checkbox" />
<label for="show_curves">Use Curved Tiles</label>
</div>

<div
title="Key[X] Whether tile curves should extend past edge of world, or clip as if surrounded by land on all sides">
<input id="extend_curves" type="checkbox" />
<label for="extend_curves">Extend Tile Curves</label>
</div>

<div title="Key[- +] Size of each world tile in pixels">
<label for="cell_size">Cell Size</label>
<input id="cell_size" value="100" type="number" min="2" max="256" step="2" />
</div>

<div title="Key[A D] World width in cells">
<label for="world_width">World Width</label>
<input id="world_width" value="8" type="number" min="1" max="2048" step="1" />
</div>

<div title="Key[W S] World height in cells">
<label for="world_height">World Height</label>
<input id="world_height" value="8" type="number" min="1" max="2048" step="1" />
</div>

</div>

<div style="width: 100%; height: 100%">
<canvas id="world"></canvas>
</div>

<script type="module">
import demo from './gldemo.js';

const $world = document.querySelector('canvas#world');
if (!$world) throw new Error('unable to find world canvas');

const $showCurves = document.querySelector('#show_curves');
if (!$showCurves) throw new Error('unable to find #show_curves');

const $extendCurves = document.querySelector('#extend_curves');
if (!$extendCurves) throw new Error('unable to find #extend_curves');

const $cellSize = document.querySelector('#cell_size');
if (!$cellSize) throw new Error('unable to find #cell_size');

const $worldWidth = document.querySelector('#world_width');
if (!$worldWidth) throw new Error('unable to find #world_width');

const $worldHeight = document.querySelector('#world_height');
if (!$worldHeight) throw new Error('unable to find #world_height');

let stop = () => { }

$cellSize.addEventListener('change', () => {stop()});

window.addEventListener('keypress', e => {
switch (e.key) {

case 'c':
case 'C':
$showCurves.checked = !$showCurves.checked;
break;

case 'x':
case 'X':
$extendCurves.checked = !$extendCurves.checked;
break;

case '.':
stop();
break;

case '+':
$cellSize.stepUp();
stop();
break;

case '-':
$cellSize.stepDown();
stop();
break;

case 'a':
case 'A':
$worldWidth.stepDown();
stop();
break;

case 'd':
case 'D':
$worldWidth.stepUp();
stop();
break;

case 's':
case 'S':
$worldHeight.stepDown();
stop();
break;

case 'w':
case 'W':
$worldHeight.stepUp();
stop();
break;

}
});

for (
let count = 0, backoff = 0, now = Date.now(), then = now; ;
then = now,
backoff = Math.min(200, Math.pow(1.5, ++count))
) {
let running = true;
stop = () => {running = false};

const since = now - then;
const wait = backoff - since;
if (wait > 0) {
await new Promise(resolve => setTimeout(resolve, wait));
console.log('wait', wait);
} else {
count = 0;
}
if (!running) continue;

await demo({
$world,
cellSize: $cellSize.valueAsNumber,
tileSize: 256,

worldWidth: $worldWidth.valueAsNumber,
worldHeight: $worldHeight.valueAsNumber,

shouldRun() {return running},
showCurvyTiles() {return $showCurves.checked},
clipCurvyTiles() {return !$extendCurves.checked},

});
}

</script>
</body>

</html>
204 changes: 204 additions & 0 deletions cube/gldemo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// @ts-check

import {
compileTileProgram,
makeTileRenderer,
makeTileSheet,
makeLayer,
} from './gltiles.js';
/** @template T @typedef {import("./gltiles.js").tileable<T>} tileable */
/** @template T @typedef {import("./gltiles.js").TileSheet<T>} TileSheet */
/** @typedef {import("./gltiles.js").Layer} Layer */

/** @callback layback
* @param {TileSheet<number>} tileSheet
* @param {Layer} layer
* @returns {void}
*/

/** @template [T = any]
* @callback tileMaker
* @param {tileable<T>} tiles
* @return TileSheet<T>
*/

import {
generateSimpleTiles,

generateCurvedTiles,
makeCurvedLayer,
updateCurvedLayer,
clippedBaseCellQuery,
extendedBaseCellQuery,
} from './tilegen.js';

/**
* @param {object} opts
* @param {HTMLCanvasElement} opts.$world
* @param {number} [opts.tileSize]
* @param {number} [opts.cellSize]
* @param {number} [opts.worldWidth]
* @param {number} [opts.worldHeight]
* @param {(() => boolean)} [opts.shouldRun]
* @param {boolean|(() => boolean)} [opts.showCurvyTiles]
* @param {boolean|(() => boolean)} [opts.clipCurvyTiles]
*/
export default async function demo(opts) {
const {
$world,
tileSize = 256,
cellSize = 64,

worldWidth = 5,
worldHeight = 5,

shouldRun = () => true,
showCurvyTiles = true,
clipCurvyTiles = false,
} = opts;
const shouldShowCurvyTiles = typeof showCurvyTiles == 'boolean' ? () => showCurvyTiles : showCurvyTiles;
const shouldClipCurvyTiles = typeof clipCurvyTiles == 'boolean' ? () => clipCurvyTiles : clipCurvyTiles;

const gl = $world.getContext('webgl2');
if (!gl) throw new Error('No GL For You!');

sizeToParent($world);

const tileRend = makeTileRenderer(gl, await compileTileProgram(gl));

const landCurveTiles = makeTileSheet(gl, generateCurvedTiles({
aFill: '#5c9e31', // land
bFill: '#61b2e4', // water
// gridLineStyle: 'red',
}), { tileSize });

const foreTiles = makeTileSheet(gl, generateSimpleTiles(
{ glyph: '🧚' },
{ glyph: '🍵' },
{ glyph: '🫖' },
{ glyph: '⛵' }
), { tileSize });

const bg = makeLayer(gl, {
texture: landCurveTiles.texture,
cellSize,
width: worldWidth,
height: worldHeight,
});

const fg = makeLayer(gl, {
texture: foreTiles.texture,
cellSize,
width: worldWidth,
height: worldHeight,
});

{
const { randn, random } = makeRandom();

// generate terrain
const land = landCurveTiles.getLayerID(0b0000);
const water = landCurveTiles.getLayerID(0b1111);
const isWater = new Uint8Array(bg.width * bg.height);
for (let i = 0; i < isWater.length; i++)
isWater[i] = random() > 0.5 ? 1 : 0;
for (let y = 0; y < bg.height; y++)
for (let x = 0; x < bg.width; x++)
bg.set(x, y, {
layerID: isWater[y * bg.width + x] ? water : land
});

// place fore objects
for (let y = 0; y < fg.height; y++) {
for (let x = 0; x < fg.width; x++) {
const tileID = Number(randn(2n * BigInt(foreTiles.size)));
const layerID = foreTiles.getLayerID(tileID);
const spin = random();
fg.set(x, y, { layerID, spin });
}
}
}

// send layer data to gpu; NOTE this needs to be called going forward after any update
bg.send();
fg.send();

let lastCurveClip = shouldClipCurvyTiles();
const bgCurved = makeCurvedLayer(gl, bg);
updateCurvedLayer(bgCurved, landCurveTiles,
lastCurveClip
? clippedBaseCellQuery(bg, landCurveTiles)
: extendedBaseCellQuery(bg, landCurveTiles));
bgCurved.send();

// forever draw loop
for await (const _ of frameTimes()) {
if (!shouldRun()) return;

// TODO animate things via const dt = lastT - t;

const nowCurveClip = shouldClipCurvyTiles();
if (lastCurveClip != nowCurveClip) {
lastCurveClip = nowCurveClip;
updateCurvedLayer(bgCurved, landCurveTiles,
shouldClipCurvyTiles()
? clippedBaseCellQuery(bg, landCurveTiles)
: extendedBaseCellQuery(bg, landCurveTiles));
bgCurved.send();
}

gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT);

tileRend.draw(function*() {
if (shouldShowCurvyTiles()) {
gl.enable(gl.SCISSOR_TEST);
gl.scissor(
// NOTE: lower left corner, with 0 counting up from bottom edge of viewport
bg.left * cellSize,
gl.canvas.height - (bg.top + bg.height) * cellSize,
bg.width * cellSize,
bg.height * cellSize
);
yield bgCurved;
gl.disable(gl.SCISSOR_TEST);
} else {
yield bg;
}
yield fg;
}());
}

}

function makeRandom(seed = 0xdead_beefn) {
let randState = seed;
const rand = () => (randState = randState * 6364136223846793005n + 1442695040888963407n) >> 17n & 0xffff_ffffn;
/** @param {bigint} n */
const randn = n => rand() % n;
const random = () => Number(rand()) / 0x1_0000_0000;
return { rand, randn, random };
}

async function* frameTimes() {
for (; ;)
yield new Promise(resolve => requestAnimationFrame(resolve));
}

/** @param {HTMLCanvasElement} $canvas */
function sizeToParent($canvas, update = () => { }) {
const $cont = $canvas.parentElement;
if ($cont) {
const resize = () => {
const { clientWidth, clientHeight, } = $cont;
$canvas.width = clientWidth;
$canvas.height = clientHeight;
update();
};
$cont.ownerDocument.defaultView?.addEventListener('resize', () => resize());
resize();
}
}
Loading