gputex 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Runtime GPU texture compression via WebGPU compute shaders, with a WebGL2 fragment-shader fallback. Feed it a PNG/JPG/WebP/AVIF and get back a GPU-compressed texture (BC7, BC5, ASTC 4x4, or BC1) ready for Three.js or React Three Fiber.
4
4
 
5
- ⚠️: This is 100% vibe-coded. The code is completely unreviewed, under-tested, it will probably crash on many devices, and this library is very likely to go unmaintained. Do not use for anything important.
5
+ ⚠️: This is 100% vibe-coded. The code is completely unreviewed and under-tested. Do not use for anything important.
6
6
 
7
7
  ## Install
8
8
 
@@ -14,7 +14,14 @@ pnpm add gputex
14
14
  bun add gputex
15
15
  ```
16
16
 
17
- `three` is a peer dependency (`>=0.180`).
17
+ ### Entry points
18
+
19
+ `gputex` ships two entry points:
20
+
21
+ - **`gputex`** — the engine-agnostic core: the `*Encoder` classes, capability / format detection, and mip helpers. Nothing here imports `three`, so it works with Babylon.js, raw WebGPU/WebGL, workers, etc. Encoders return raw compressed block bytes via `encodeToBytes()`.
22
+ - **`gputex/three`** — the Three.js layer. Re-exports the entire core **plus** `compressTexture()`, `GputexLoader`, and `buildCompressedTexture()` / `encodeToTexture()`. This is the only entry that imports `three`.
23
+
24
+ `three` is an **optional** peer dependency (`>=0.170`): install it only if you import `gputex/three`. Pure-core consumers (e.g. Babylon.js) can skip it entirely.
18
25
 
19
26
  ## Formats
20
27
 
@@ -44,7 +51,7 @@ Notes on the WebGL path:
44
51
  ### `compressTexture` — direct API
45
52
 
46
53
  ```ts
47
- import { compressTexture } from 'gputex'
54
+ import { compressTexture } from 'gputex/three'
48
55
 
49
56
  const { texture, format } = await compressTexture('/cobblestone.avif', {
50
57
  hint: 'color', // 'color' | 'colorWithAlpha' | 'normal'
@@ -75,7 +82,7 @@ material.map = texture
75
82
  ### `GputexLoader` — Three.js Loader
76
83
 
77
84
  ```ts
78
- import { GputexLoader } from 'gputex'
85
+ import { GputexLoader } from 'gputex/three'
79
86
 
80
87
  const loader = new GputexLoader()
81
88
  loader.hint = 'normal'
@@ -90,7 +97,7 @@ The `GputexLoader` works with R3F's `useLoader`:
90
97
 
91
98
  ```tsx
92
99
  import { useLoader } from '@react-three/fiber'
93
- import { GputexLoader } from 'gputex'
100
+ import { GputexLoader } from 'gputex/three'
94
101
 
95
102
  function Scene() {
96
103
  const texture = useLoader(GputexLoader, '/cobblestone.avif', loader => {
@@ -113,7 +120,7 @@ For a reusable hook with metadata access:
113
120
  ```tsx
114
121
  import { useLayoutEffect } from 'react'
115
122
  import { useLoader } from '@react-three/fiber'
116
- import { GputexLoader } from 'gputex'
123
+ import { GputexLoader } from 'gputex/three'
117
124
  import type { TextureHint } from 'gputex'
118
125
 
119
126
  function useGputex(url: string, options?: { hint?: TextureHint; colorSpace?: 'srgb' | 'linear'; mipmaps?: boolean }) {
@@ -157,18 +164,35 @@ function Scene() {
157
164
  }
158
165
  ```
159
166
 
160
- ### Low-level encoders
167
+ ### Low-level encoders (any engine)
161
168
 
162
- Individual encoder classes are exported for direct control:
169
+ The individual encoder classes live in the engine-agnostic core (`gputex`). `encodeToBytes()` returns raw compressed block bytes with no Three.js involvement — feed them into whatever compressed-texture upload your engine exposes (Babylon.js, raw WebGPU/WebGL, …):
163
170
 
164
171
  ```ts
165
172
  import { BC7Encoder, BC5Encoder, ASTC4x4Encoder, BC1Encoder } from 'gputex'
166
173
 
167
174
  const encoder = await BC7Encoder.create()
168
- const { data, width, height } = await encoder.encodeToBytes(imageBitmap)
175
+ const { data, width, height, paddedWidth, paddedHeight } = await encoder.encodeToBytes(imageBitmap)
176
+ // `data` is a Uint8Array of BC7 blocks covering paddedWidth × paddedHeight.
169
177
  encoder.destroy()
170
178
  ```
171
179
 
180
+ To turn an encoder's output into a Three.js `CompressedTexture` directly, use the helpers in `gputex/three`:
181
+
182
+ ```ts
183
+ import { BC7Encoder, TextureFormat } from 'gputex'
184
+ import { encodeToTexture, buildCompressedTexture } from 'gputex/three'
185
+
186
+ const encoder = await BC7Encoder.create()
187
+
188
+ // One-shot: image → CompressedTexture (plus the raw byte metadata)
189
+ const { texture } = await encodeToTexture(encoder, imageBitmap, { colorSpace: 'srgb' })
190
+
191
+ // …or assemble a texture from bytes you already have (e.g. a mip chain):
192
+ const bytes = await encoder.encodeToBytes(imageBitmap)
193
+ const tex = buildCompressedTexture([bytes], TextureFormat.BC7_SRGB)
194
+ ```
195
+
172
196
  ## Options
173
197
 
174
198
  ### `compressTexture` options
package/dist/index.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { CompressedPixelFormat, CompressedTexture, Texture, Loader } from 'three';
2
-
3
1
  declare const TextureFormat: {
4
2
  readonly BC1: "BC1";
5
3
  readonly BC1_SRGB: "BC1_SRGB";
@@ -48,8 +46,9 @@ interface EncoderOptions {
48
46
  /**
49
47
  * Encoder quality level. 'fast' (default) uses the cheaper search paths in the
50
48
  * shaders — measured ~2–4× faster for ≤0.36 dB PSNR. 'high' runs the exhaustive
51
- * search, producing output byte-identical to the CPU reference encoders.
52
- * No effect on BC1 (already single-pass; both levels are identical).
49
+ * search, producing output byte-identical to the CPU reference encoders (BC5/
50
+ * BC7/ASTC). BC1's 'high' adds a principal-axis endpoint seed and iterative
51
+ * refit on top of the 'fast' bbox+refit path.
53
52
  */
54
53
  type EncodeQuality = 'fast' | 'high';
55
54
  interface EncodeCallOptions {
@@ -58,19 +57,11 @@ interface EncodeCallOptions {
58
57
  /** Encode quality / speed trade-off. Default 'fast'. */
59
58
  quality?: EncodeQuality;
60
59
  }
61
- interface EncodeResult {
62
- width: number;
63
- height: number;
64
- paddedWidth: number;
65
- paddedHeight: number;
66
- data: Uint8Array;
67
- texture: CompressedTexture;
68
- encodeMs: number;
69
- }
70
60
  /**
71
- * Result of a raw bytes-only encode (no wrapping in a `CompressedTexture`).
72
- * Used by the mipped encode path to bundle multiple levels into a single
73
- * `CompressedTexture` at the end.
61
+ * Result of a raw bytes-only encode. This is the encoder's native output: the
62
+ * compressed block bytes plus dimensions, with no Three.js (or any engine)
63
+ * involvement. Feed `data` into whatever renderer's compressed-texture upload
64
+ * you like, or use `buildCompressedTexture()` from `gputex/three`.
74
65
  */
75
66
  interface EncodeBytesResult {
76
67
  width: number;
@@ -95,6 +86,8 @@ interface FormatVariant {
95
86
  type EncoderConstructor<T extends Encoder = Encoder> = {
96
87
  new (opts: EncoderOptions): T;
97
88
  requiredFeature: GPUFeatureName | null;
89
+ /** Logical formats this encoder can emit (linear first, then sRGB variant). */
90
+ readonly textureFormats: readonly TextureFormat[];
98
91
  create(): Promise<T>;
99
92
  };
100
93
  declare abstract class Encoder {
@@ -142,8 +135,8 @@ declare abstract class Encoder {
142
135
  get supportsSrgb(): boolean;
143
136
  /**
144
137
  * Whether the shader declares a `QUALITY_HIGH` pipeline-overridable constant
145
- * (i.e. has distinct fast/high search paths). BC1 is already single-pass and
146
- * leaves this false; BC5/BC7/ASTC override it to true.
138
+ * (i.e. has distinct fast/high search paths). Default false (e.g. a stub or a
139
+ * format with a single path); BC1/BC5/BC7/ASTC override it to true.
147
140
  */
148
141
  get supportsQuality(): boolean;
149
142
  /**
@@ -158,40 +151,23 @@ declare abstract class Encoder {
158
151
  abstract wgslSource(): string;
159
152
  /** e.g. 'bc1-rgba-unorm-srgb'. */
160
153
  abstract gpuTextureFormat(opts: FormatVariant): GPUTextureFormat;
161
- /** Three.js `CompressedPixelFormat` constant for `CompressedTexture`. */
162
- abstract threeTextureFormat(opts: FormatVariant): CompressedPixelFormat;
163
154
  /**
164
155
  * True if the device reports the feature the output texture needs.
165
156
  * The encoder itself only writes to a storage buffer, so this is about
166
157
  * whether the result can actually be sampled.
167
158
  */
168
159
  get supportsSampling(): boolean;
169
- encode(source: EncoderImageSource, { colorSpace, quality }?: EncodeCallOptions): Promise<EncodeResult>;
170
160
  /**
171
- * Encode one image source to raw compressed bytes, skipping the
172
- * `CompressedTexture` wrap. Used by the public `encode()` above and by
173
- * the mipped encode path in `compressTexture()` so N mip levels end up
174
- * in a single `CompressedTexture` instead of N throwaway wrappers.
175
- *
176
- * Public (not protected) because `compressTexture()` calls it across the
177
- * encoder boundary. Still safe to call from outside — it just does
178
- * less work than `encode()` and the caller assembles the texture.
161
+ * Encode one image source to raw compressed bytes. This is the encoder's
162
+ * native, engine-agnostic output. `compressTexture()` and
163
+ * `encodeToTexture()` (both in `gputex/three`) call it and then wrap the
164
+ * bytes into a `CompressedTexture`; callers targeting another engine feed
165
+ * `data` into that engine's compressed-texture upload directly.
179
166
  */
180
167
  encodeToBytes(source: EncoderImageSource, { flipY, quality }?: {
181
168
  flipY?: boolean;
182
169
  quality?: EncodeQuality;
183
170
  }): Promise<EncodeBytesResult>;
184
- /**
185
- * Assemble a `CompressedTexture` from pre-encoded mip levels. Called
186
- * by `compressTexture()` after it has run each level through
187
- * `encodeToBytes()`. Centralised here so the single-level and mipped
188
- * paths share the same format / colour-space / wrap settings.
189
- *
190
- * `levels[0]` is the base level; its padded dimensions become the
191
- * texture's overall size. Filter setup assumes at least 2 levels →
192
- * trilinear; 1 level → bilinear.
193
- */
194
- buildMippedTexture(levels: readonly EncodeBytesResult[], { colorSpace }?: EncodeCallOptions): CompressedTexture;
195
171
  }
196
172
 
197
173
  declare class BC1Encoder extends Encoder {
@@ -200,9 +176,9 @@ declare class BC1Encoder extends Encoder {
200
176
  get label(): string;
201
177
  get bytesPerBlock(): number;
202
178
  get supportsSrgb(): boolean;
179
+ get supportsQuality(): boolean;
203
180
  wgslSource(): string;
204
181
  gpuTextureFormat({ colorSpace }: FormatVariant): GPUTextureFormat;
205
- threeTextureFormat(): CompressedPixelFormat;
206
182
  }
207
183
 
208
184
  declare class BC5Encoder extends Encoder {
@@ -215,7 +191,6 @@ declare class BC5Encoder extends Encoder {
215
191
  wgslSource(): string;
216
192
  wgslSourceFastF16(): string;
217
193
  gpuTextureFormat(): GPUTextureFormat;
218
- threeTextureFormat(): CompressedPixelFormat;
219
194
  }
220
195
 
221
196
  declare class BC7Encoder extends Encoder {
@@ -228,7 +203,6 @@ declare class BC7Encoder extends Encoder {
228
203
  wgslSource(): string;
229
204
  wgslSourceFastF16(): string;
230
205
  gpuTextureFormat({ colorSpace }: FormatVariant): GPUTextureFormat;
231
- threeTextureFormat(): CompressedPixelFormat;
232
206
  }
233
207
 
234
208
  declare class ASTC4x4Encoder extends Encoder {
@@ -241,18 +215,6 @@ declare class ASTC4x4Encoder extends Encoder {
241
215
  wgslSource(): string;
242
216
  wgslSourceFastF16(): string;
243
217
  gpuTextureFormat({ colorSpace }: FormatVariant): GPUTextureFormat;
244
- threeTextureFormat(): CompressedPixelFormat;
245
- }
246
-
247
- /** One encoded mip level. The fields both encoder backends already produce. */
248
- interface EncodedLevel {
249
- /** Logical (pre-padding) dimensions, surfaced on the texture's userData. */
250
- width: number;
251
- height: number;
252
- /** Block-aligned dimensions the compressed `data` actually covers. */
253
- paddedWidth: number;
254
- paddedHeight: number;
255
- data: Uint8Array;
256
218
  }
257
219
 
258
220
  /** Raw RGBA8 pixel data (e.g. a CPU-generated mip level). */
@@ -305,8 +267,6 @@ declare abstract class WebGLBlockEncoder {
305
267
  abstract get supportsSrgb(): boolean;
306
268
  /** GLSL ES 3.00 fragment-shader source. */
307
269
  abstract fragSource(): string;
308
- /** Three.js `CompressedPixelFormat` constant; sRGB is carried by colorSpace. */
309
- abstract threeTextureFormat(): CompressedPixelFormat;
310
270
  protected _buildProgram(): void;
311
271
  /** Release the GL program + VAO. The shared context itself is left intact. */
312
272
  destroy(): void;
@@ -326,10 +286,6 @@ declare abstract class WebGLBlockEncoder {
326
286
  encodeToBytes(source: WebGLEncoderImageSource, { flipY }?: {
327
287
  flipY?: boolean;
328
288
  }): WebGLEncodeBytesResult;
329
- /** Wrap pre-encoded levels into a CompressedTexture. Shared with the WebGPU path. */
330
- buildMippedTexture(levels: readonly EncodedLevel[], { colorSpace }?: {
331
- colorSpace?: 'srgb' | 'linear';
332
- }): CompressedTexture;
333
289
  }
334
290
 
335
291
  declare class BC1WebGLEncoder extends WebGLBlockEncoder {
@@ -337,7 +293,6 @@ declare class BC1WebGLEncoder extends WebGLBlockEncoder {
337
293
  get bytesPerBlock(): number;
338
294
  get supportsSrgb(): boolean;
339
295
  fragSource(): string;
340
- threeTextureFormat(): CompressedPixelFormat;
341
296
  }
342
297
 
343
298
  declare class BC5WebGLEncoder extends WebGLBlockEncoder {
@@ -345,7 +300,6 @@ declare class BC5WebGLEncoder extends WebGLBlockEncoder {
345
300
  get bytesPerBlock(): number;
346
301
  get supportsSrgb(): boolean;
347
302
  fragSource(): string;
348
- threeTextureFormat(): CompressedPixelFormat;
349
303
  }
350
304
 
351
305
  declare class BC7WebGLEncoder extends WebGLBlockEncoder {
@@ -353,7 +307,6 @@ declare class BC7WebGLEncoder extends WebGLBlockEncoder {
353
307
  get bytesPerBlock(): number;
354
308
  get supportsSrgb(): boolean;
355
309
  fragSource(): string;
356
- threeTextureFormat(): CompressedPixelFormat;
357
310
  }
358
311
 
359
312
  declare class ASTC4x4WebGLEncoder extends WebGLBlockEncoder {
@@ -361,7 +314,6 @@ declare class ASTC4x4WebGLEncoder extends WebGLBlockEncoder {
361
314
  get bytesPerBlock(): number;
362
315
  get supportsSrgb(): boolean;
363
316
  fragSource(): string;
364
- threeTextureFormat(): CompressedPixelFormat;
365
317
  }
366
318
 
367
319
  /**
@@ -436,95 +388,6 @@ interface WebGLFormatSelection {
436
388
  }
437
389
  declare function selectWebGLFormat(caps: WebGLCapabilities, hint: TextureHint, options?: SelectFormatOptions): WebGLFormatSelection;
438
390
 
439
- /**
440
- * Everything `compressTexture()` can take as an image source. A superset
441
- * of `EncoderImageSource` (see Encoder.ts) that also accepts URL strings
442
- * and Blob / File objects — the common cases in a web app.
443
- */
444
- type CompressTextureSource = string | Blob | File | ImageBitmap | HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageData;
445
- interface CompressOptions {
446
- /** How the texture will be used. Drives format selection. Default 'color'. */
447
- hint?: TextureHint;
448
- /** Pick the sRGB or linear variant of the chosen format. Default 'srgb'. */
449
- colorSpace?: 'srgb' | 'linear';
450
- /** Flip the image vertically before encoding. Default true (matches Three.js convention). */
451
- flipY?: boolean;
452
- /** Generate a full mip chain down to 1×1 on the CPU, encode every level. */
453
- mipmaps?: boolean;
454
- /**
455
- * Encode quality / speed trade-off. 'fast' (default) is ~2–4× faster for a
456
- * ≤0.36 dB PSNR cost; 'high' runs the exhaustive search (output identical to
457
- * the CPU reference encoders). No effect on BC1 or on the WebGL fallback
458
- * (which always uses the fast encoders).
459
- */
460
- quality?: EncodeQuality;
461
- /** Reuse an existing device (e.g. Three.js's renderer device) instead
462
- * of creating a new one. WebGPU path only. When provided, the encoder
463
- * never destroys it. */
464
- device?: GPUDevice;
465
- adapter?: GPUAdapter;
466
- }
467
- interface CompressResult {
468
- /** CompressedTexture on a compressed path; Texture on RGBA8 fallback. */
469
- texture: Texture | CompressedTexture;
470
- /** The compressed format selected, or null when we fell back to RGBA8. */
471
- format: TextureFormat | null;
472
- /** True iff we returned an uncompressed Texture because no encoder fit. */
473
- fallbackUncompressed: boolean;
474
- /**
475
- * Which backend produced the result. 'webgpu' = compute path, 'webgl' =
476
- * fragment-shader fallback, 'none' = uncompressed RGBA8.
477
- */
478
- backend: 'webgpu' | 'webgl' | 'none';
479
- /**
480
- * True iff the chosen format is ASTC and the hint was 'normal'. The
481
- * caller must apply the (R, W) → (x, y) swizzle in the material — ASTC
482
- * has no 2-channel mode, so normal maps ride the RGBA path.
483
- */
484
- astcNormalRemap: boolean;
485
- width: number;
486
- height: number;
487
- mipLevels: number;
488
- /** Wall-clock time of GPU encoding, summed across mip levels. */
489
- encodeMs: number;
490
- /** Release the encoder's internal GPU resources. No-op if `device` was
491
- * passed in by the caller. */
492
- destroy(): void;
493
- }
494
- declare function compressTexture(source: CompressTextureSource, options?: CompressOptions): Promise<CompressResult>;
495
-
496
- declare class GputexLoader extends Loader<Texture> {
497
- /** Format-selection hint. Default 'color'. */
498
- hint: TextureHint;
499
- /** Pick the sRGB or linear variant of the chosen format. Default 'srgb'. */
500
- colorSpace: 'srgb' | 'linear';
501
- /** Flip the image vertically before encoding. Default true (matches Three.js convention). */
502
- flipY: boolean;
503
- /** Generate + encode a full mip chain. Default false. */
504
- mipmaps: boolean;
505
- /** Encode quality / speed trade-off. Default 'fast' (~2–4× faster, ≤0.36 dB). */
506
- quality: EncodeQuality;
507
- /**
508
- * Optional pre-existing WebGPU device. Reusing the renderer's device
509
- * avoids spinning up a second WebGPU context for encoding.
510
- */
511
- device?: GPUDevice;
512
- adapter?: GPUAdapter;
513
- /**
514
- * Most recent full encode result. Useful when the caller wants format
515
- * / mipLevels / astcNormalRemap metadata without threading a separate
516
- * callback through `load()`. Cleared when a new load starts.
517
- */
518
- lastResult: CompressResult | null;
519
- /**
520
- * THREE.Loader contract: returns void, drives callbacks. `loadAsync`
521
- * (inherited from the base class) wraps this with Promise semantics.
522
- * Errors routed through `manager.itemError` so the LoadingManager's
523
- * aggregate state stays accurate.
524
- */
525
- load(url: string, onLoad?: (texture: Texture) => void, _onProgress?: (event: ProgressEvent) => void, onError?: (err: unknown) => void): void;
526
- }
527
-
528
391
  /** One level of a mip chain. 4 bytes per pixel (RGBA8). */
529
392
  interface MipLevel {
530
393
  data: Uint8ClampedArray;
@@ -550,4 +413,4 @@ declare function generateMipChain(level0: MipLevel): MipLevel[];
550
413
  */
551
414
  declare function padToBlockMultiple(level: MipLevel): MipLevel;
552
415
 
553
- export { ASTC4x4Encoder, ASTC4x4WebGLEncoder, BC1Encoder, BC1WebGLEncoder, BC5Encoder, BC5WebGLEncoder, BC7Encoder, BC7WebGLEncoder, type Capabilities, type CompressOptions, type CompressResult, type CompressTextureSource, type EncodeBytesResult, type EncodeCallOptions, type EncodeQuality, type EncodeResult, Encoder, type EncoderConstructor, type EncoderImageSource, type EncoderOptions, type ExtensionProvider, type FeatureProvider, type FormatSelection, type FormatVariant, GputexLoader, type MipLevel, type RawPixelSource, type SelectFormatOptions, TextureFormat, type TextureHint, WebGLBlockEncoder, type WebGLCapabilities, type WebGLEncodeBytesResult, type WebGLEncoderConstructor, type WebGLEncoderImageSource, type WebGLEncoderOptions, type WebGLFormatSelection, WebGPUFeature, compressTexture, createWebGLContext, detectCapabilities, detectWebGLCapabilities, generateMipChain, getSharedWebGLContext, isWebGLAvailable, padToBlockMultiple, selectFormat, selectWebGLFormat };
416
+ export { ASTC4x4Encoder, ASTC4x4WebGLEncoder, BC1Encoder, BC1WebGLEncoder, BC5Encoder, BC5WebGLEncoder, BC7Encoder, BC7WebGLEncoder, type Capabilities, type EncodeBytesResult, type EncodeCallOptions, type EncodeQuality, Encoder, type EncoderConstructor, type EncoderImageSource, type EncoderOptions, type ExtensionProvider, type FeatureProvider, type FormatSelection, type FormatVariant, type MipLevel, type RawPixelSource, type SelectFormatOptions, TextureFormat, type TextureHint, WebGLBlockEncoder, type WebGLCapabilities, type WebGLEncodeBytesResult, type WebGLEncoderConstructor, type WebGLEncoderImageSource, type WebGLEncoderOptions, type WebGLFormatSelection, WebGPUFeature, createWebGLContext, detectCapabilities, detectWebGLCapabilities, generateMipChain, getSharedWebGLContext, isWebGLAvailable, padToBlockMultiple, selectFormat, selectWebGLFormat };