@thoughts-on-things/vantage-mc 0.3.0 → 0.5.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.
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { i as WorldManifest, W as WorldFetch, R as Rgb, B as BiomeEntry, a as DecodedTextureArray, D as DecodedTile, j as WorldSource } from './biome-CPP37ieY.js';
2
+ import { i as WorldManifest, W as WorldFetch, R as Rgb, M as ManifestTile, c as LowresLevel, B as BiomeEntry, a as DecodedTextureArray, D as DecodedTile, j as WorldSource } from './biome-NBWIY7dT.js';
3
3
 
4
4
  interface TileManagerOptions {
5
5
  manifest: WorldManifest;
@@ -12,7 +12,7 @@ interface TileManagerOptions {
12
12
  /** The shared water shader (from {@link createWaterMaterial}). */
13
13
  waterMaterial: THREE.ShaderMaterial;
14
14
  /** The shared atlas-lit shader (from {@link createLightmappedMaterial});
15
- * required to draw VTL8 tiles' lightmapped geometry (manifest format 4+). */
15
+ * required to draw VTL8+ tiles' lightmapped geometry (manifest format 4+). */
16
16
  lmMaterial?: THREE.ShaderMaterial;
17
17
  /** The shared lowres LOD shader (from {@link createLowresMaterial}); required
18
18
  * to stream a format-2 manifest's lowres pyramid. */
@@ -21,10 +21,22 @@ interface TileManagerOptions {
21
21
  palette: Rgb[];
22
22
  /** Stream-in radius around the focus, in blocks. Default `768`. */
23
23
  viewDistance?: number;
24
- /** Hard cap on resident tiles (nearest win). Default `96`. */
24
+ /** Hard cap on resident tiles (nearest win). Default `120` (fills the
25
+ * default view-distance disc; matches the settings panel's "med" preset). */
25
26
  maxTiles?: number;
26
27
  /** Concurrent tile fetches. Default `4`. */
27
28
  concurrency?: number;
29
+ /** Estimated CPU/GPU residency budget in bytes. Unlike `maxTiles`, this
30
+ * accounts for large and small tiles having very different geometry. One
31
+ * nearest oversized tile is allowed for forward progress. Default `512 MiB`. */
32
+ maxBytes?: number;
33
+ /** Live/on-demand renders grow the shared texture atlas in viewport order, so
34
+ * a fetched tile can reference layers the atlas doesn't have yet. When set,
35
+ * the manager widens the atlas (awaiting this) before building a tile that
36
+ * needs newer layers, so nothing is ever drawn against a missing-texture
37
+ * atlas. Returns the atlas layer count now loaded. Omitted for a
38
+ * static/complete render, whose atlas never grows. */
39
+ ensureAtlas?: (layers: number) => Promise<number>;
28
40
  }
29
41
  /** Live totals across resident tiles. */
30
42
  interface TileStats {
@@ -40,6 +52,8 @@ interface TileStats {
40
52
  triangleCount: number;
41
53
  /** Compressed bytes fetched and resident. */
42
54
  bytes: number;
55
+ /** Estimated CPU/GPU bytes held by resident and upload-pending resources. */
56
+ residentBytes: number;
43
57
  }
44
58
  interface TileEvents extends Record<string, unknown> {
45
59
  /** A tile finished loading or was unloaded; payload = live stats. */
@@ -49,6 +63,12 @@ declare class TileManager {
49
63
  private readonly opts;
50
64
  private readonly lowresMaterial;
51
65
  private readonly lmMaterial;
66
+ /** Widens the shared atlas to cover a tile's layers before it's drawn (live
67
+ * renders only); null when the atlas is complete. */
68
+ private readonly ensureAtlas;
69
+ /** Best-known covered atlas layer count. `Infinity` disables the gate — a
70
+ * static render never grows its atlas. */
71
+ private atlasLayers;
52
72
  private readonly index;
53
73
  private readonly records;
54
74
  private readonly emitter;
@@ -59,10 +79,15 @@ declare class TileManager {
59
79
  private readonly lowIndex;
60
80
  /** Set when residency changed and lowres visibility needs recomputing. */
61
81
  private coverageDirty;
82
+ /** Tiles mid stream-in fade; drained by update(), keeps the viewer drawing. */
83
+ private readonly fadingKeys;
62
84
  private queue;
63
85
  /** Built tiles awaiting scene insertion — flushed ONE per update() call so
64
86
  * multi-MB GPU uploads never pile into a single frame. */
65
87
  private pendingAdd;
88
+ /** Built records still holding upload-pending typed arrays. Pumping pauses at
89
+ * one concurrency-window so decode cannot outrun GPU submission. */
90
+ private pendingBuilt;
66
91
  private inFlight;
67
92
  private lastFocusX;
68
93
  private lastFocusZ;
@@ -71,6 +96,11 @@ declare class TileManager {
71
96
  * backoff escalates; cleared on success or unload (a fresh pan-in retries). */
72
97
  private failCounts;
73
98
  private nextRetrySweep;
99
+ /** Learned tile weights survive eviction and make future admission byte-aware. */
100
+ private readonly sizeHints;
101
+ private averageHiresBytes;
102
+ private focusX;
103
+ private focusZ;
74
104
  private biomesCache;
75
105
  private statsCache;
76
106
  /** Y range of everything loaded so far, for ray-march bounds. */
@@ -97,6 +127,16 @@ declare class TileManager {
97
127
  * loading hundreds of tiles) it drains faster so the map sharpens in a
98
128
  * couple of seconds instead of many. */
99
129
  private flushOne;
130
+ /** Stream-in fade length. Long enough to read as a dissolve, short enough
131
+ * that a fast pan still feels instant. */
132
+ static readonly FADE_MS = 280;
133
+ /** Whether any tile is mid stream-in fade — the viewer keeps drawing while
134
+ * true so the dissolve actually animates under render-on-demand. */
135
+ get fading(): boolean;
136
+ /** Chain a per-draw uFade write onto each mesh's onBeforeRender (after the
137
+ * dequantize-uniform hook terrain.ts installs). Every TileManager mesh gets
138
+ * one — the materials are shared, so each draw must set its own fade. */
139
+ private attachFade;
100
140
  /**
101
141
  * Hide every lowres tile whose footprint is fully SHOWN by finer data.
102
142
  * "Shown" is transitive, computed bottom-up: a hires tile shows its area by
@@ -112,17 +152,32 @@ declare class TileManager {
112
152
  * ring edge, loading).
113
153
  */
114
154
  private applyCoverage;
155
+ /** Ingest tiles a progressive render has newly published. Unknown tiles join
156
+ * the streaming index and force a re-plan so they stream in on the next
157
+ * update(); already-known tiles are ignored. Returns whether anything was
158
+ * added. */
159
+ addTiles(tiles: ManifestTile[]): boolean;
160
+ /** Install the lowres pyramid once a progressive render finishes (its earlier
161
+ * manifests carried no lowres). No-op without a lowres material, or if a
162
+ * pyramid is already present. Forces a re-plan so the coarse rings stream in. */
163
+ ingestLowres(lowres: {
164
+ grid: number;
165
+ levels: LowresLevel[];
166
+ }): void;
115
167
  /** Live-tune streaming (view distance, tile budget, fetch concurrency).
116
168
  * Takes effect on the next update(): the plan is recomputed from scratch. */
117
169
  configure(settings: {
118
170
  viewDistance?: number;
119
171
  maxTiles?: number;
120
172
  concurrency?: number;
173
+ maxBytes?: number;
121
174
  }): void;
122
175
  /** The current stream-in radius, in blocks. */
123
176
  get viewDistance(): number;
124
177
  /** The current resident-tile budget. */
125
178
  get maxTiles(): number;
179
+ /** The current estimated CPU+GPU residency budget. */
180
+ get maxBytes(): number;
126
181
  /** Fetch + decode one lowres LOD tile into a heightfield mesh. */
127
182
  private loadLowres;
128
183
  /** A transient failure (network blip, 5xx) retries with exponential backoff
@@ -135,6 +190,10 @@ declare class TileManager {
135
190
  private retrySweep;
136
191
  private loadTile;
137
192
  private unload;
193
+ /** Correct estimation misses after a tile is decoded. Farthest hires records
194
+ * leave first; one nearest tile is always kept so an oversized outlier does
195
+ * not create an unload/refetch loop. Learned weights make the next plan fit. */
196
+ private trimToMemoryBudget;
138
197
  private invalidate;
139
198
  /** Live totals across resident tiles. */
140
199
  get stats(): TileStats;
@@ -402,6 +461,8 @@ interface StreamingSettings {
402
461
  maxTiles?: number;
403
462
  /** Concurrent tile fetches. Default `4`. */
404
463
  concurrency?: number;
464
+ /** Estimated CPU/GPU tile residency budget, in bytes. Default `512 MiB`. */
465
+ maxBytes?: number;
405
466
  }
406
467
  interface VantageViewerOptions {
407
468
  /** Initial camera framing. Default `'orbit'`. */
@@ -422,6 +483,13 @@ interface VantageViewerOptions {
422
483
  * or pasted into the address bar — is applied to the camera. Default `false`
423
484
  * (the React `<VantageViewer>` turns it on). */
424
485
  urlState?: boolean;
486
+ /** Render only when something changed (camera, streaming tiles, settings) —
487
+ * plus a steady ~10 fps tick while animated textures (water, lava) are
488
+ * loaded, matching their baked 2-tick frametime. An idle view costs ~0
489
+ * GPU/CPU instead of a full render loop; input still renders the same
490
+ * frame it arrives. Default `true`; set `false` to render every frame
491
+ * (e.g. when driving external per-frame effects off the viewer's scene). */
492
+ renderOnDemand?: boolean;
425
493
  }
426
494
  /** A tile source: a URL to fetch, a raw buffer, or already-decoded data. */
427
495
  type TileSource = string | ArrayBuffer | DecodedTile;
@@ -464,6 +532,17 @@ interface ViewerEvents extends Record<string, unknown> {
464
532
  mode: {
465
533
  fly: boolean;
466
534
  };
535
+ /** The depth slice (cave view) moved or toggled. `null` = off. */
536
+ slice: {
537
+ y: number | null;
538
+ };
539
+ /** Progressive render progress, while a live bake streams in. `done` reaches
540
+ * `total` and `rendering` flips false on the final manifest. */
541
+ progress: {
542
+ done: number;
543
+ total: number;
544
+ rendering: boolean;
545
+ };
467
546
  }
468
547
  declare class VantageViewer {
469
548
  readonly renderer: THREE.WebGLRenderer;
@@ -492,10 +571,22 @@ declare class VantageViewer {
492
571
  private worldSpan;
493
572
  private tilesUnsub;
494
573
  private lastBiomesEmit;
574
+ private progressiveManager;
575
+ private lastTextureLayers;
576
+ /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
577
+ * poll coalesce onto one request instead of racing separate fetches. */
578
+ private atlasRefresh;
495
579
  private biomeEnabled;
496
580
  private highlight;
497
581
  private mixTarget;
498
582
  private mixCurrent;
583
+ private sliceTarget;
584
+ private sliceCurrent;
585
+ private sliceActive;
586
+ /** The last depth used, so re-opening the cave view returns there. */
587
+ private lastSliceY;
588
+ /** The dark "unexplored rock" floor under a sliced world. */
589
+ private slicePlane;
499
590
  private light;
500
591
  private display;
501
592
  private readonly raycaster;
@@ -505,6 +596,9 @@ declare class VantageViewer {
505
596
  private dragging;
506
597
  private lastHover;
507
598
  private lastFrameMs;
599
+ private needsRender;
600
+ private hasAnims;
601
+ private lastRenderMs;
508
602
  private framedState;
509
603
  private hashTimer;
510
604
  private lastWrittenHash;
@@ -522,6 +616,27 @@ declare class VantageViewer {
522
616
  * the camera as it moves and unload behind it; the whole world is reachable
523
617
  * without ever holding more than the streaming budget in memory. */
524
618
  private loadWorld;
619
+ /** Emit a `progress` event from a manifest (falling back to the tile count
620
+ * when the generator didn't include a `progress` block). */
621
+ private emitProgress;
622
+ /** Follow a live (`rendering: true`) render: re-fetch the manifest on an
623
+ * interval, stream newly-baked tiles in, widen the texture array when the
624
+ * atlas grows, and install the lowres pyramid once the bake completes. Runs
625
+ * until the render finishes or the world is replaced. */
626
+ private pollProgressive;
627
+ /** Ensure the terrain atlas covers at least `layers` texture-array layers,
628
+ * re-fetching `terrain.vtexarr` if it's behind. Coalesces concurrent callers
629
+ * — the on-demand tile-insert gate and the progressive poll — onto one
630
+ * request. Resolves once the atlas is current (or the fetch failed and the
631
+ * old atlas stands, to be retried by a later gate/poll). */
632
+ private ensureAtlasLayers;
633
+ /** Re-fetch `terrain.vtexarr` and widen every shared material's atlas (they
634
+ * share the sampler uniform objects, so one update reaches all). */
635
+ private refetchAtlas;
636
+ /** Set the world bounds + span from a manifest's tile extents, without moving
637
+ * the camera. Used to frame a world on load and to widen the extent when a
638
+ * progressive render finishes and the full size is finally known. */
639
+ private updateWorldBounds;
525
640
  /** Frame a streamed world: pivot on the spawn point when the manifest has
526
641
  * one (that's where the builds are), else the centre of the tile extents.
527
642
  * Distances are tied to the streaming view distance, not the world size —
@@ -571,31 +686,71 @@ declare class VantageViewer {
571
686
  * immediately, no re-bake). */
572
687
  setLight(settings: LightSettings): void;
573
688
  private applyLight;
689
+ /** Whether the loaded world was baked with full cave geometry
690
+ * (`vantage render --caves full`) — i.e. the depth slice has real caves to
691
+ * reveal. The slice API works regardless; this is the "show the UI?" bit. */
692
+ get hasCaves(): boolean;
693
+ /** The world-Y bounds for the depth slice, from the manifest's baked extent
694
+ * (falling back to the loaded bounds / vanilla build limits). */
695
+ get sliceRange(): {
696
+ min: number;
697
+ max: number;
698
+ };
699
+ /** The current depth-slice Y, or `null` when the cave view is off. */
700
+ get slice(): number | null;
701
+ /** Slice the world at world-Y `y` (everything above is cut away, exposing
702
+ * the caves below — the cave / X-ray view); `null` turns it off. The plane
703
+ * eases to its target, so toggling peels the world open. Emits `'slice'`. */
704
+ setSlice(y: number | null): void;
705
+ /** Toggle the cave view: off → the last used depth (or a sensible cave
706
+ * depth on first open), on → off. */
707
+ toggleSlice(): void;
708
+ /** Push slice state to the shader + scene: clip uniform, ambient floor, and
709
+ * the void floor's presence. Also called on (re)load to seed a fresh shader. */
710
+ private applySlice;
711
+ /** The "unexplored rock" floor under a sliced world: a huge dark plane at
712
+ * the world's bottom, so solid ground reads as solid where no cave is
713
+ * exposed (instead of sky bleeding through the planet). Carries a faint
714
+ * 16-block chunk grid for scale and shares the terrain's fog uniforms so
715
+ * its distance haze matches. Follows the camera focus each frame. */
716
+ private buildSlicePlane;
717
+ /** Install the terrain-follow height source, wrapped so the controls' pivot
718
+ * never rides the (now invisible) surface above an open depth slice —
719
+ * zooming in descends to the exposed cave level instead of stopping at the
720
+ * clipped-away hilltops. */
721
+ private setHeightSampler;
574
722
  /** The current live display fidelity (sharpness, colour grade, fog, scale). */
575
723
  get displaySettings(): Required<DisplaySettings>;
576
724
  /** Update the live display fidelity (merges with current; immediate, no
577
725
  * re-bake). `renderScale` resizes the framebuffer; the rest are shader uniforms. */
578
726
  setDisplay(settings: DisplaySettings): void;
579
727
  /** devicePixelRatio × renderScale, capped by maxPixelRatio (and a hard 4 so a
580
- * fat-fingered scale can't allocate a giant framebuffer). */
728
+ * fat-fingered scale can't allocate a giant framebuffer). Floored at 0.25:
729
+ * a hidden/headless window can report devicePixelRatio 0, which would
730
+ * otherwise zero the framebuffer and break screenshot() and the first
731
+ * visible frame. */
581
732
  private targetPixelRatio;
582
733
  private applyDisplay;
583
- /** The current streaming settings (view distance, tile budget, concurrency). */
734
+ /** The current streaming settings (view distance, tile/byte budgets, concurrency). */
584
735
  get streamingSettings(): Required<StreamingSettings>;
585
- /** Live-tune streaming: view distance, resident-tile budget, concurrency.
736
+ /** Live-tune streaming: view distance, resident tile/byte budgets, concurrency.
586
737
  * Applies immediately to a streamed world (tiles re-plan, fog and camera
587
738
  * range follow) and persists for future loads. The fidelity dial: raise
588
- * viewDistance/maxTiles to see farther, lower them on weak hardware. */
739
+ * viewDistance/maxTiles/maxBytes to see farther, lower them on weak hardware. */
589
740
  setStreaming(settings: StreamingSettings): void;
590
- /** The current view serialized as a `#@x,y,z,dist,rot,tilt` hash fragment —
591
- * paste-able into any URL serving the same world. */
741
+ /** The current view serialized as a `#@x,y,z,dist,rot,tilt[,sliceY]` hash
742
+ * fragment — paste-able into any URL serving the same world. The trailing
743
+ * component appears only while the cave view is open, so those deep links
744
+ * reopen sliced at the same depth. */
592
745
  getViewHash(): string;
593
- /** Apply a `#@x,y,z,dist,rot,tilt` hash to the camera (leading `#` optional).
594
- * Returns whether the hash parsed. */
746
+ /** Apply a `#@x,y,z,dist,rot,tilt[,sliceY]` hash to the camera (leading `#`
747
+ * optional). Returns whether the hash parsed. */
595
748
  applyViewHash(hash: string): boolean;
596
749
  /** Debounced camera→hash sync plus hashchange→camera (pasted links apply
597
750
  * live). `history.replaceState` avoids history spam and hashchange echo. */
598
751
  private bindUrlState;
752
+ /** Debounce a hash write — camera motion and slice changes funnel here. */
753
+ private queueHashWrite;
599
754
  private writeHash;
600
755
  /** Smoothly zoom by `steps` wheel-notches (positive = in). Drives the same
601
756
  * inertial zoom as the wheel, so on-screen buttons feel identical. */
@@ -625,7 +780,19 @@ declare class VantageViewer {
625
780
  private bindInput;
626
781
  private emitHover;
627
782
  private pickHover;
783
+ /** Request a redraw on the next animation frame. The viewer invalidates
784
+ * itself for everything it owns (camera motion, tile streaming, settings,
785
+ * the biome layer); call this only if you mutate the scene from outside. */
786
+ invalidate(): void;
787
+ /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
788
+ * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
789
+ private static readonly ANIM_TICK_MS;
628
790
  private frame;
791
+ private draw;
792
+ /** Draw a fresh frame and return the canvas as a PNG data URL, for a
793
+ * screenshot button / download link. Draws synchronously first because the
794
+ * default framebuffer is not preserved between the on-demand renders. */
795
+ screenshot(): string;
629
796
  private resize;
630
797
  private disposeCurrent;
631
798
  /** Tear down the renderer, controls, observers, and remove the canvas. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thoughts-on-things/vantage-mc",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Render a Minecraft (Java) world as a fast, beautiful 3D web map. The web frontend for the Vantage generator.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -49,6 +49,7 @@
49
49
  "dev": "vite",
50
50
  "build": "tsup",
51
51
  "build:demo": "vite build",
52
+ "build:viewer": "vite build -c vite.viewer.config.ts",
52
53
  "preview": "vite preview",
53
54
  "typecheck": "tsc --noEmit",
54
55
  "test": "vitest run",
@@ -61,6 +62,9 @@
61
62
  "esbuild": "^0.28.1"
62
63
  }
63
64
  },
65
+ "allowScripts": {
66
+ "esbuild": true
67
+ },
64
68
  "peerDependencies": {
65
69
  "react": ">=18",
66
70
  "react-dom": ">=18",
@@ -79,13 +83,13 @@
79
83
  "@types/react": "^19.0.0",
80
84
  "@types/react-dom": "^19.0.0",
81
85
  "@types/three": "^0.160.0",
82
- "@vitejs/plugin-react": "^4.3.4",
86
+ "@vitejs/plugin-react": "^6.0.2",
83
87
  "react": "^19.0.0",
84
88
  "react-dom": "^19.0.0",
85
- "three": "^0.160.0",
89
+ "three": "^0.185.1",
86
90
  "tsup": "^8.3.5",
87
- "typescript": "^5.7.2",
88
- "vite": "^6.0.0",
89
- "vitest": "^3.2.6"
91
+ "typescript": "^6.0.3",
92
+ "vite": "^8.0.16",
93
+ "vitest": "^4.1.8"
90
94
  }
91
95
  }