@celljs/ta-voxel 0.0.0-stage → 4.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ // The controls of the first person (VoxelControls), on the element of the game: with keys WASD or the arrows walk,
2
+ // Shift runs (down while flying), Space jumps (up while flying), a click locks the mouse to look (Esc frees it), the left
3
+ // button and the right are the game's (break and place), the wheel and 1–9 its bar. On a touch screen the left half is
4
+ // a stick where the thumb comes down, the right half looks as it is dragged (a tap there does nothing); the buttons
5
+ // of the game are its own elements over it, which call `press`.
6
+ const LOOK = 0.0024;
7
+ const TOUCH_LOOK = 0.0055;
8
+ /** How far the stick goes, in CSS pixels. */
9
+ const STICK = 52;
10
+ export class VoxelControls {
11
+ constructor(element, hooks = {}) {
12
+ this.element = element;
13
+ this.hooks = hooks;
14
+ this.yaw = 0;
15
+ this.pitch = 0;
16
+ this.held = new Set();
17
+ this.run = false;
18
+ this.keys = new Set();
19
+ this.touches = new Map();
20
+ /** The page would not lock the mouse (a desktop app without it): a click acts, a drag looks. */
21
+ this.lockRefused = false;
22
+ this.off = [];
23
+ const listen = (target, type, run, options) => {
24
+ target.addEventListener(type, run, options);
25
+ this.off.push(() => target.removeEventListener(type, run, options));
26
+ };
27
+ listen(element, 'keydown', event => this.keyDown(event));
28
+ listen(element, 'keyup', event => this.keyUp(event));
29
+ listen(element, 'blur', () => this.release());
30
+ listen(element, 'mousedown', event => this.mouseDown(event));
31
+ listen(window, 'mouseup', event => this.mouseUp(event));
32
+ listen(element, 'mousemove', event => this.mouseMove(event));
33
+ listen(element, 'contextmenu', event => event.preventDefault());
34
+ const refused = () => {
35
+ this.lockRefused = true;
36
+ };
37
+ document.addEventListener('pointerlockerror', refused);
38
+ this.off.push(() => document.removeEventListener('pointerlockerror', refused));
39
+ listen(element, 'wheel', event => {
40
+ var _a, _b;
41
+ event.preventDefault();
42
+ (_b = (_a = this.hooks).pick) === null || _b === void 0 ? void 0 : _b.call(_a, { step: Math.sign(event.deltaY) });
43
+ }, { passive: false });
44
+ listen(element, 'touchstart', event => this.touchStart(event), { passive: false });
45
+ listen(element, 'touchmove', event => this.touchMove(event), { passive: false });
46
+ listen(element, 'touchend', event => this.touchEnd(event), { passive: false });
47
+ listen(element, 'touchcancel', event => this.touchEnd(event), { passive: false });
48
+ }
49
+ get locked() {
50
+ return typeof document !== 'undefined' && document.pointerLockElement === this.element;
51
+ }
52
+ /** Where to walk: forward and to the right, -1 to 1. */
53
+ movement() {
54
+ const k = this.keys;
55
+ let forward = (k.has('KeyW') || k.has('ArrowUp') ? 1 : 0) - (k.has('KeyS') || k.has('ArrowDown') ? 1 : 0);
56
+ let strafe = (k.has('KeyD') || k.has('ArrowRight') ? 1 : 0) - (k.has('KeyA') || k.has('ArrowLeft') ? 1 : 0);
57
+ if (this.stick) {
58
+ forward = -this.stick.y;
59
+ strafe = this.stick.x;
60
+ }
61
+ return { forward, strafe };
62
+ }
63
+ /** Whether running: Shift held (walking; flying it goes down), or the stick pushed all the way. */
64
+ running() {
65
+ return this.run || this.keys.has('ShiftLeft') || this.keys.has('ShiftRight') || (!!this.stick && Math.hypot(this.stick.x, this.stick.y) > 0.95);
66
+ }
67
+ /** A button of the page pressed or let go. */
68
+ press(action, down) {
69
+ var _a, _b;
70
+ if (down) {
71
+ this.held.add(action);
72
+ }
73
+ else {
74
+ this.held.delete(action);
75
+ }
76
+ (_b = (_a = this.hooks).action) === null || _b === void 0 ? void 0 : _b.call(_a, action, down);
77
+ }
78
+ /** Lets go of everything: the page was left, a panel opened. */
79
+ release() {
80
+ for (const action of [...this.held]) {
81
+ this.press(action, false);
82
+ }
83
+ this.keys.clear();
84
+ this.touches.clear();
85
+ this.stick = undefined;
86
+ }
87
+ turn(dx, dy, scale = LOOK) {
88
+ this.yaw -= dx * scale;
89
+ this.pitch = Math.max(-1.5, Math.min(1.5, this.pitch - dy * scale));
90
+ }
91
+ /** The way it looks, as a vector (x east, y up, z south). */
92
+ direction() {
93
+ const cos = Math.cos(this.pitch);
94
+ return { x: -Math.sin(this.yaw) * cos, y: Math.sin(this.pitch), z: -Math.cos(this.yaw) * cos };
95
+ }
96
+ dispose() {
97
+ for (const off of this.off) {
98
+ off();
99
+ }
100
+ if (this.locked) {
101
+ document.exitPointerLock();
102
+ }
103
+ }
104
+ keyDown(event) {
105
+ var _a, _b, _c, _d;
106
+ if (event.metaKey || event.ctrlKey || event.altKey) {
107
+ return;
108
+ }
109
+ const code = event.code;
110
+ if (/^Digit[1-9]$/.test(code)) {
111
+ (_b = (_a = this.hooks).pick) === null || _b === void 0 ? void 0 : _b.call(_a, { slot: Number(code.slice(5)) - 1 });
112
+ return;
113
+ }
114
+ const action = code === 'Space' ? 'jump' : code === 'ShiftLeft' || code === 'ShiftRight' ? 'down' : code === 'KeyE' || code === 'KeyF' ? 'interact' : undefined;
115
+ if (['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space', 'ShiftLeft', 'ShiftRight', 'KeyE', 'KeyF'].includes(code)) {
116
+ event.preventDefault();
117
+ if (!event.repeat) {
118
+ this.keys.add(code);
119
+ if (action) {
120
+ this.press(action, true);
121
+ }
122
+ }
123
+ return;
124
+ }
125
+ (_d = (_c = this.hooks).key) === null || _d === void 0 ? void 0 : _d.call(_c, event.key, event);
126
+ }
127
+ keyUp(event) {
128
+ this.keys.delete(event.code);
129
+ const action = event.code === 'Space' ? 'jump' : event.code.startsWith('Shift') ? 'down' : event.code === 'KeyE' || event.code === 'KeyF' ? 'interact' : undefined;
130
+ if (action) {
131
+ this.press(action, false);
132
+ }
133
+ }
134
+ mouseDown(event) {
135
+ var _a;
136
+ this.element.focus();
137
+ // The first click locks the mouse; without the lock (refused, or none) a click acts at once.
138
+ if (!this.locked && !this.lockRefused && typeof this.element.requestPointerLock === 'function') {
139
+ try {
140
+ const lock = this.element.requestPointerLock();
141
+ (_a = lock === null || lock === void 0 ? void 0 : lock.catch) === null || _a === void 0 ? void 0 : _a.call(lock, () => {
142
+ this.lockRefused = true;
143
+ });
144
+ }
145
+ catch (_b) {
146
+ this.lockRefused = true;
147
+ }
148
+ return;
149
+ }
150
+ this.press(event.button === 2 ? 'secondary' : 'primary', true);
151
+ }
152
+ mouseUp(event) {
153
+ const action = event.button === 2 ? 'secondary' : 'primary';
154
+ if (this.held.has(action)) {
155
+ this.press(action, false);
156
+ }
157
+ }
158
+ mouseMove(event) {
159
+ if (this.locked) {
160
+ this.turn(event.movementX, event.movementY);
161
+ }
162
+ else if (event.buttons & 1) {
163
+ this.turn(event.movementX, event.movementY);
164
+ }
165
+ }
166
+ touchStart(event) {
167
+ event.preventDefault();
168
+ const box = this.element.getBoundingClientRect();
169
+ for (const touch of Array.from(event.changedTouches)) {
170
+ const left = touch.clientX - box.left < box.width / 2;
171
+ this.touches.set(touch.identifier, { kind: left && !this.stick ? 'stick' : 'look', x: touch.clientX, y: touch.clientY });
172
+ if (left && !this.stick) {
173
+ this.stick = {
174
+ x: 0,
175
+ y: 0,
176
+ ox: touch.clientX - box.left,
177
+ oy: touch.clientY - box.top,
178
+ px: touch.clientX - box.left,
179
+ py: touch.clientY - box.top,
180
+ };
181
+ }
182
+ }
183
+ }
184
+ touchMove(event) {
185
+ event.preventDefault();
186
+ const box = this.element.getBoundingClientRect();
187
+ for (const touch of Array.from(event.changedTouches)) {
188
+ const known = this.touches.get(touch.identifier);
189
+ if (!known) {
190
+ continue;
191
+ }
192
+ if (known.kind === 'look') {
193
+ this.turn(touch.clientX - known.x, touch.clientY - known.y, TOUCH_LOOK);
194
+ known.x = touch.clientX;
195
+ known.y = touch.clientY;
196
+ }
197
+ else if (this.stick) {
198
+ const px = touch.clientX - box.left;
199
+ const py = touch.clientY - box.top;
200
+ let dx = px - this.stick.ox;
201
+ let dy = py - this.stick.oy;
202
+ const length = Math.hypot(dx, dy);
203
+ // The base follows a thumb that goes past it, so that turning back needs no reach.
204
+ if (length > STICK) {
205
+ this.stick.ox += (dx / length) * (length - STICK);
206
+ this.stick.oy += (dy / length) * (length - STICK);
207
+ dx = px - this.stick.ox;
208
+ dy = py - this.stick.oy;
209
+ }
210
+ this.stick.x = dx / STICK;
211
+ this.stick.y = dy / STICK;
212
+ this.stick.px = px;
213
+ this.stick.py = py;
214
+ }
215
+ }
216
+ }
217
+ touchEnd(event) {
218
+ var _a;
219
+ for (const touch of Array.from(event.changedTouches)) {
220
+ if (((_a = this.touches.get(touch.identifier)) === null || _a === void 0 ? void 0 : _a.kind) === 'stick') {
221
+ this.stick = undefined;
222
+ }
223
+ this.touches.delete(touch.identifier);
224
+ }
225
+ }
226
+ }
227
+ //# sourceMappingURL=voxel-controls.js.map
@@ -0,0 +1,23 @@
1
+ import { type VoxelBlocks } from './voxel-blocks.js';
2
+ import { type VoxelChunk, type VoxelStore } from './voxel-chunks.js';
3
+ export interface MeshPart {
4
+ positions: Float32Array;
5
+ /** Which way each corner's face looks, for a world lit by lights (VoxelMeshes `lit`). */
6
+ normals: Float32Array;
7
+ colors: Float32Array;
8
+ uvs: Float32Array;
9
+ indices: Uint32Array;
10
+ }
11
+ export interface ChunkMesh {
12
+ solid: MeshPart;
13
+ glow: MeshPart;
14
+ clear: MeshPart;
15
+ /** Water: seen through less than glass. */
16
+ liquid: MeshPart;
17
+ /** The faces drawn, for the budget of a frame. */
18
+ faces: number;
19
+ }
20
+ export declare namespace VoxelMesher {
21
+ /** `shade`: darken each side by which way it faces, for a world without lights (by default). */
22
+ function mesh(store: VoxelStore, chunk: VoxelChunk, blocks: VoxelBlocks, shade?: boolean): ChunkMesh;
23
+ }
@@ -0,0 +1,146 @@
1
+ import { TILE, TILE_CELL, TILE_COLUMNS, TILE_PAD } from './voxel-blocks.js';
2
+ import { CHUNK } from './voxel-chunks.js';
3
+ /** How light each side is: up, down, east and west, south and north. */
4
+ const SHADE = [1, 0.55, 0.82, 0.82, 0.7, 0.7];
5
+ /** How light a corner is by how many of its three blocks are there (ambient occlusion). */
6
+ const AO = [0.52, 0.68, 0.84, 1];
7
+ /** The six faces: the normal, then the two axes along the face (u, v), in order for the corners to go round. */
8
+ const FACES = [
9
+ { n: [0, 1, 0], u: [0, 0, 1], v: [1, 0, 0] },
10
+ { n: [0, -1, 0], u: [1, 0, 0], v: [0, 0, 1] },
11
+ { n: [1, 0, 0], u: [0, 1, 0], v: [0, 0, 1] },
12
+ { n: [-1, 0, 0], u: [0, 0, 1], v: [0, 1, 0] },
13
+ { n: [0, 0, 1], u: [1, 0, 0], v: [0, 1, 0] },
14
+ { n: [0, 0, -1], u: [0, 1, 0], v: [1, 0, 0] },
15
+ ];
16
+ class Builder {
17
+ constructor() {
18
+ this.positions = [];
19
+ this.normals = [];
20
+ this.colors = [];
21
+ this.uvs = [];
22
+ this.indices = [];
23
+ }
24
+ part() {
25
+ return {
26
+ positions: new Float32Array(this.positions),
27
+ normals: new Float32Array(this.normals),
28
+ colors: new Float32Array(this.colors),
29
+ uvs: new Float32Array(this.uvs),
30
+ indices: new Uint32Array(this.indices),
31
+ };
32
+ }
33
+ }
34
+ /** A number in [0, 1) the same for the same block, for the little differences of colour between blocks. */
35
+ function hash(x, y, z) {
36
+ let h = (x * 374761393 + y * 668265263 + z * 2147483647) | 0;
37
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
38
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
39
+ }
40
+ export var VoxelMesher;
41
+ (function (VoxelMesher) {
42
+ /** `shade`: darken each side by which way it faces, for a world without lights (by default). */
43
+ function mesh(store, chunk, blocks, shade = true) {
44
+ const solid = new Builder();
45
+ const glow = new Builder();
46
+ const clear = new Builder();
47
+ const liquid = new Builder();
48
+ const { looks, opaque, faceTile } = blocks;
49
+ const rows = Math.ceil(blocks.tiles.length / TILE_COLUMNS);
50
+ const width = TILE_COLUMNS * TILE_CELL;
51
+ const height = rows * TILE_CELL;
52
+ const ox = chunk.cx * CHUNK;
53
+ const oz = chunk.cz * CHUNK;
54
+ const { data, height: tall } = chunk;
55
+ /** The block beside, in this chunk or the next; what is not loaded counts as solid (no face). */
56
+ const at = (x, y, z) => {
57
+ var _a;
58
+ if (y < 0) {
59
+ return 1;
60
+ }
61
+ if (x >= 0 && x < CHUNK && z >= 0 && z < CHUNK) {
62
+ return y < tall ? data[(y * CHUNK + z) * CHUNK + x] : 0;
63
+ }
64
+ return (_a = store.get(ox + x, y, oz + z)) !== null && _a !== void 0 ? _a : -1;
65
+ };
66
+ const hides = (id) => id === -1 || opaque[id] === 1;
67
+ let faces = 0;
68
+ for (let y = 0; y < tall; y++) {
69
+ for (let z = 0; z < CHUNK; z++) {
70
+ for (let x = 0; x < CHUNK; x++) {
71
+ const id = data[(y * CHUNK + z) * CHUNK + x];
72
+ if (id === 0) {
73
+ continue;
74
+ }
75
+ const look = looks[id];
76
+ const out = look.liquid ? liquid : look.glow ? glow : look.clear ? clear : solid;
77
+ const jitter = look.flat ? 1 : 0.95 + hash(ox + x, y, oz + z) * 0.1;
78
+ const r = (((look.color >> 16) & 0xff) / 255) * jitter;
79
+ const g = (((look.color >> 8) & 0xff) / 255) * jitter;
80
+ const b = ((look.color & 0xff) / 255) * jitter;
81
+ for (let f = 0; f < 6; f++) {
82
+ const { n, u, v } = FACES[f];
83
+ const next = at(x + n[0], y + n[1], z + n[2]);
84
+ // Water shows only to the air; a block, to what does not hide it; glass not to glass.
85
+ if (look.liquid ? next !== 0 : hides(next) || (look.clear && next === id)) {
86
+ continue;
87
+ }
88
+ faces++;
89
+ const side = f > 1 && look.sideColor !== undefined;
90
+ const fr = side ? ((look.sideColor >> 16) & 0xff) / 255 : r;
91
+ const fg = side ? ((look.sideColor >> 8) & 0xff) / 255 : g;
92
+ const fb = side ? (look.sideColor & 0xff) / 255 : b;
93
+ const tile = faceTile[id * 6 + f];
94
+ const left = (tile % TILE_COLUMNS) * TILE_CELL + TILE_PAD;
95
+ const top = Math.floor(tile / TILE_COLUMNS) * TILE_CELL + TILE_PAD;
96
+ const base = out.positions.length / 3;
97
+ // The corner of the face at (0, 0) of u and v: on the side of the normal.
98
+ const cx = x + (n[0] > 0 ? 1 : 0);
99
+ const cy = y + (n[1] > 0 ? 1 : 0) - (look.liquid && f === 0 && next === 0 ? 0.12 : 0);
100
+ const cz = z + (n[2] > 0 ? 1 : 0);
101
+ const corners = [];
102
+ for (let k = 0; k < 4; k++) {
103
+ const su = k === 1 || k === 2 ? 1 : 0;
104
+ const sv = k >= 2 ? 1 : 0;
105
+ out.positions.push(cx + u[0] * su + v[0] * sv, cy + u[1] * su + v[1] * sv, cz + u[2] * su + v[2] * sv);
106
+ out.normals.push(n[0], n[1], n[2]);
107
+ let light = shade ? SHADE[f] : 1;
108
+ if (!look.glow && !look.clear) {
109
+ // The three blocks beside this corner, outside the face.
110
+ const du = su ? 1 : -1;
111
+ const dv = sv ? 1 : -1;
112
+ const px = x + n[0];
113
+ const py = y + n[1];
114
+ const pz = z + n[2];
115
+ const side1 = hides(at(px + u[0] * du, py + u[1] * du, pz + u[2] * du)) ? 1 : 0;
116
+ const side2 = hides(at(px + v[0] * dv, py + v[1] * dv, pz + v[2] * dv)) ? 1 : 0;
117
+ const corner = hides(at(px + u[0] * du + v[0] * dv, py + u[1] * du + v[1] * dv, pz + u[2] * du + v[2] * dv)) ? 1 : 0;
118
+ const ao = side1 && side2 ? 0 : 3 - side1 - side2 - corner;
119
+ corners.push(ao);
120
+ light *= AO[ao];
121
+ }
122
+ out.colors.push(fr * light, fg * light, fb * light);
123
+ // Across the tile: on the top and bottom along x and z; on a side along it, and up.
124
+ const dx = u[0] * su + v[0] * sv;
125
+ const dy = u[1] * su + v[1] * sv;
126
+ const dz = u[2] * su + v[2] * sv;
127
+ const across = f < 2 ? dx : n[0] !== 0 ? dz : dx;
128
+ const down = f < 2 ? dz : 1 - dy;
129
+ out.uvs.push((left + across * TILE) / width, (top + down * TILE) / height);
130
+ }
131
+ // Split the quad along the diagonal of the lighter corners, so that the shadow does not slant.
132
+ if (corners.length === 4 && corners[0] + corners[2] < corners[1] + corners[3]) {
133
+ out.indices.push(base + 1, base + 2, base + 3, base + 1, base + 3, base);
134
+ }
135
+ else {
136
+ out.indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
137
+ }
138
+ }
139
+ }
140
+ }
141
+ }
142
+ return { solid: solid.part(), glow: glow.part(), clear: clear.part(), liquid: liquid.part(), faces };
143
+ }
144
+ VoxelMesher.mesh = mesh;
145
+ })(VoxelMesher || (VoxelMesher = {}));
146
+ //# sourceMappingURL=voxel-mesher.js.map
@@ -0,0 +1,21 @@
1
+ export interface RayHit {
2
+ x: number;
3
+ y: number;
4
+ z: number;
5
+ /** The face it entered by: where a block placed on it goes is (x + nx, y + ny, z + nz). */
6
+ nx: number;
7
+ ny: number;
8
+ nz: number;
9
+ distance: number;
10
+ }
11
+ export declare namespace VoxelRay {
12
+ function cast(from: {
13
+ x: number;
14
+ y: number;
15
+ z: number;
16
+ }, direction: {
17
+ x: number;
18
+ y: number;
19
+ z: number;
20
+ }, reach: number, pick: (x: number, y: number, z: number) => boolean): RayHit | undefined;
21
+ }
@@ -0,0 +1,30 @@
1
+ // The block aimed at (VoxelRay): a ray from the eye through the blocks, block by block (Amanatides and Woo), to the
2
+ // first one `pick` takes, and the face it went in by, where a block put would go.
3
+ export var VoxelRay;
4
+ (function (VoxelRay) {
5
+ function cast(from, direction, reach, pick) {
6
+ const length = Math.hypot(direction.x, direction.y, direction.z) || 1;
7
+ const d = [direction.x / length, direction.y / length, direction.z / length];
8
+ const p = [from.x, from.y, from.z];
9
+ const cell = p.map(Math.floor);
10
+ const step = d.map(v => (v > 0 ? 1 : v < 0 ? -1 : 0));
11
+ const delta = d.map(v => (v === 0 ? Number.POSITIVE_INFINITY : Math.abs(1 / v)));
12
+ const next = d.map((v, i) => (v > 0 ? (cell[i] + 1 - p[i]) / v : v < 0 ? (p[i] - cell[i]) / -v : Number.POSITIVE_INFINITY));
13
+ let normal = [0, 0, 0];
14
+ let travelled = 0;
15
+ for (let i = 0; i < 512 && travelled <= reach; i++) {
16
+ if (pick(cell[0], cell[1], cell[2])) {
17
+ return { x: cell[0], y: cell[1], z: cell[2], nx: normal[0], ny: normal[1], nz: normal[2], distance: travelled };
18
+ }
19
+ const axis = next[0] < next[1] ? (next[0] < next[2] ? 0 : 2) : next[1] < next[2] ? 1 : 2;
20
+ travelled = next[axis];
21
+ next[axis] += delta[axis];
22
+ cell[axis] += step[axis];
23
+ normal = [0, 0, 0];
24
+ normal[axis] = -step[axis];
25
+ }
26
+ return undefined;
27
+ }
28
+ VoxelRay.cast = cast;
29
+ })(VoxelRay || (VoxelRay = {}));
30
+ //# sourceMappingURL=voxel-ray.js.map
@@ -0,0 +1,38 @@
1
+ import type * as T from 'three';
2
+ import { type VoxelBlocks } from './voxel-blocks.js';
3
+ import type { ChunkMesh } from './voxel-mesher.js';
4
+ type Three = typeof T;
5
+ /** The tiles of the blocks in one texture, each with its edges repeated round it (VoxelMesher maps the faces). */
6
+ export declare function voxelAtlas(THREE: Three, blocks: VoxelBlocks): T.DataTexture;
7
+ export declare class VoxelMeshes {
8
+ protected readonly THREE: Three;
9
+ readonly group: T.Group;
10
+ protected readonly solid: T.MeshBasicMaterial | T.MeshLambertMaterial;
11
+ protected readonly glow: T.MeshBasicMaterial;
12
+ protected readonly clear: T.MeshBasicMaterial | T.MeshLambertMaterial;
13
+ protected readonly liquid: T.MeshBasicMaterial | T.MeshLambertMaterial;
14
+ protected readonly lit: boolean;
15
+ protected readonly shadows: boolean;
16
+ protected readonly grain: T.DataTexture;
17
+ protected readonly meshes: Map<number, T.Mesh<T.BufferGeometry<T.NormalBufferAttributes, T.BufferGeometryEventMap>, T.Material<T.MaterialEventMap>[] | T.Material<T.MaterialEventMap>, T.Object3DEventMap>[]>;
18
+ /**
19
+ * `lit`: drawn by the lights of the scene (a sun and the sky) instead of by the colours of the corners alone, the
20
+ * meshes made without the shade of each side (VoxelMesher `shade` false); `shadows`, casting and receiving them.
21
+ */
22
+ constructor(THREE: Three, blocks: VoxelBlocks, options?: {
23
+ lit?: boolean;
24
+ shadows?: boolean;
25
+ });
26
+ /** The meshes of a chunk, at its corner in the scene (`x`, `z`), instead of what it had. */
27
+ set(key: number, x: number, z: number, mesh: ChunkMesh): void;
28
+ remove(key: number): void;
29
+ has(key: number): boolean;
30
+ keys(): IterableIterator<number>;
31
+ /**
32
+ * The light of the world: `sun` the tint of what the sun lights (white at noon, blue and dark at night),
33
+ * `glow` that of what glows (warmer and brighter at night: more than 1 is brighter than its colour).
34
+ */
35
+ light(sun: T.Color, glow: T.Color): void;
36
+ dispose(): void;
37
+ }
38
+ export {};
@@ -0,0 +1,119 @@
1
+ import { TILE, TILE_CELL, TILE_COLUMNS, TILE_PAD } from './voxel-blocks.js';
2
+ /** The tiles of the blocks in one texture, each with its edges repeated round it (VoxelMesher maps the faces). */
3
+ export function voxelAtlas(THREE, blocks) {
4
+ const rows = Math.ceil(blocks.tiles.length / TILE_COLUMNS);
5
+ const width = TILE_COLUMNS * TILE_CELL;
6
+ const height = rows * TILE_CELL;
7
+ const data = new Uint8Array(width * height * 4);
8
+ blocks.tiles.forEach((pixels, index) => {
9
+ const ox = (index % TILE_COLUMNS) * TILE_CELL;
10
+ const oy = Math.floor(index / TILE_COLUMNS) * TILE_CELL;
11
+ for (let y = 0; y < TILE_CELL; y++) {
12
+ for (let x = 0; x < TILE_CELL; x++) {
13
+ const sx = Math.max(0, Math.min(TILE - 1, x - TILE_PAD));
14
+ const sy = Math.max(0, Math.min(TILE - 1, y - TILE_PAD));
15
+ data.set(pixels.subarray((sy * TILE + sx) * 4, (sy * TILE + sx) * 4 + 4), ((oy + y) * width + ox + x) * 4);
16
+ }
17
+ }
18
+ });
19
+ const texture = new THREE.DataTexture(data, width, height);
20
+ texture.magFilter = THREE.NearestFilter;
21
+ // Far away the tiles blend, so that walls do not shimmer in stripes.
22
+ texture.minFilter = THREE.LinearMipmapLinearFilter;
23
+ texture.anisotropy = 4;
24
+ texture.generateMipmaps = true;
25
+ texture.colorSpace = THREE.SRGBColorSpace;
26
+ texture.needsUpdate = true;
27
+ return texture;
28
+ }
29
+ export class VoxelMeshes {
30
+ /**
31
+ * `lit`: drawn by the lights of the scene (a sun and the sky) instead of by the colours of the corners alone, the
32
+ * meshes made without the shade of each side (VoxelMesher `shade` false); `shadows`, casting and receiving them.
33
+ */
34
+ constructor(THREE, blocks, options = {}) {
35
+ this.THREE = THREE;
36
+ this.meshes = new Map();
37
+ this.group = new THREE.Group();
38
+ this.grain = voxelAtlas(THREE, blocks);
39
+ this.lit = !!options.lit;
40
+ this.shadows = !!options.shadows;
41
+ const Material = this.lit ? THREE.MeshLambertMaterial : THREE.MeshBasicMaterial;
42
+ this.solid = new Material({ vertexColors: true, map: this.grain });
43
+ this.glow = new THREE.MeshBasicMaterial({ vertexColors: true, toneMapped: false });
44
+ this.clear = new Material({ vertexColors: true, map: this.grain, transparent: true, opacity: 0.55, depthWrite: false });
45
+ this.liquid = new Material({ vertexColors: true, transparent: true, opacity: 0.82, depthWrite: false });
46
+ }
47
+ /** The meshes of a chunk, at its corner in the scene (`x`, `z`), instead of what it had. */
48
+ set(key, x, z, mesh) {
49
+ this.remove(key);
50
+ const made = [];
51
+ const add = (part, material, order) => {
52
+ if (part.indices.length === 0) {
53
+ return;
54
+ }
55
+ const { THREE } = this;
56
+ const geometry = new THREE.BufferGeometry();
57
+ geometry.setAttribute('position', new THREE.BufferAttribute(part.positions, 3));
58
+ geometry.setAttribute('color', new THREE.BufferAttribute(part.colors, 3));
59
+ if (this.lit) {
60
+ geometry.setAttribute('normal', new THREE.BufferAttribute(part.normals, 3));
61
+ }
62
+ geometry.setAttribute('uv', new THREE.BufferAttribute(part.uvs, 2));
63
+ geometry.setIndex(new THREE.BufferAttribute(part.indices, 1));
64
+ geometry.computeBoundingSphere();
65
+ const object = new THREE.Mesh(geometry, material);
66
+ object.position.set(x, 0, z);
67
+ object.renderOrder = order;
68
+ object.castShadow = this.shadows && material === this.solid;
69
+ object.receiveShadow = this.shadows && material !== this.glow;
70
+ object.matrixAutoUpdate = false;
71
+ object.updateMatrix();
72
+ this.group.add(object);
73
+ made.push(object);
74
+ };
75
+ add(mesh.solid, this.solid, 0);
76
+ add(mesh.glow, this.glow, 0);
77
+ add(mesh.clear, this.clear, 1);
78
+ add(mesh.liquid, this.liquid, 1);
79
+ this.meshes.set(key, made);
80
+ }
81
+ remove(key) {
82
+ var _a;
83
+ for (const object of (_a = this.meshes.get(key)) !== null && _a !== void 0 ? _a : []) {
84
+ this.group.remove(object);
85
+ object.geometry.dispose();
86
+ }
87
+ this.meshes.delete(key);
88
+ }
89
+ has(key) {
90
+ return this.meshes.has(key);
91
+ }
92
+ keys() {
93
+ return this.meshes.keys();
94
+ }
95
+ /**
96
+ * The light of the world: `sun` the tint of what the sun lights (white at noon, blue and dark at night),
97
+ * `glow` that of what glows (warmer and brighter at night: more than 1 is brighter than its colour).
98
+ */
99
+ light(sun, glow) {
100
+ // Lit by the lights of the scene, it is not tinted besides.
101
+ if (!this.lit) {
102
+ this.solid.color.copy(sun);
103
+ this.clear.color.copy(sun);
104
+ this.liquid.color.copy(sun);
105
+ }
106
+ this.glow.color.copy(glow);
107
+ }
108
+ dispose() {
109
+ for (const key of [...this.meshes.keys()]) {
110
+ this.remove(key);
111
+ }
112
+ this.solid.dispose();
113
+ this.glow.dispose();
114
+ this.clear.dispose();
115
+ this.liquid.dispose();
116
+ this.grain.dispose();
117
+ }
118
+ }
119
+ //# sourceMappingURL=voxel-three.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from './voxel-blocks';
2
+ export * from './voxel-body';
3
+ export * from './voxel-chunks';
4
+ export * from './voxel-controls';
5
+ export * from './voxel-mesher';
6
+ export * from './voxel-ray';
7
+ export * from './voxel-three';
8
+ //# sourceMappingURL=index.d.ts.map
package/lib/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./voxel-blocks"), exports);
18
+ __exportStar(require("./voxel-body"), exports);
19
+ __exportStar(require("./voxel-chunks"), exports);
20
+ __exportStar(require("./voxel-controls"), exports);
21
+ __exportStar(require("./voxel-mesher"), exports);
22
+ __exportStar(require("./voxel-ray"), exports);
23
+ __exportStar(require("./voxel-three"), exports);
24
+ //# sourceMappingURL=index.js.map