bagl-js 0.1.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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright 2026 Jake Coxon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,434 @@
1
+ # Bagl
2
+
3
+ A modern WebGL2 wrapper with deferred context binding, inspired by the original regl library.
4
+
5
+ ## Features
6
+
7
+ - **Deferred Context Binding**: Create resources and commands before a WebGL context is available
8
+ - **WebGL2 Native**: Built specifically for WebGL2 with modern features like VAOs and instanced rendering
9
+ - **State Management**: Efficient state caching and diffing for optimal performance
10
+ - **TypeScript Support**: Full TypeScript support with comprehensive type definitions
11
+ - **Context Loss Handling**: Graceful handling of WebGL context loss and restoration
12
+ - **Resource Management**: Automatic cleanup and resource lifecycle management
13
+ - **Context Object**: Built-in time, ticks, width, height tracking for animations
14
+ - **Uniform Functions**: Support for dynamic uniforms with context and props parameters
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install bagl
20
+ ```
21
+
22
+ ## Basic Usage
23
+
24
+ ### Immediate Context Binding
25
+
26
+ ```typescript
27
+ import { createBagl } from 'bagl';
28
+
29
+ const canvas = document.querySelector('canvas')!;
30
+ const bagl = createBagl(canvas);
31
+
32
+ const drawTriangle = bagl({
33
+ vert: `
34
+ #version 300 es
35
+ precision mediump float;
36
+ in vec2 position;
37
+ void main() {
38
+ gl_Position = vec4(position, 0.0, 1.0);
39
+ }
40
+ `,
41
+ frag: `
42
+ #version 300 es
43
+ precision mediump float;
44
+ out vec4 color;
45
+ void main() {
46
+ color = vec4(0.3, 0.7, 0.9, 1.0);
47
+ }
48
+ `,
49
+ attributes: {
50
+ position: bagl.buffer({
51
+ data: new Float32Array([-1, -1, 1, -1, 0, 1]),
52
+ size: 2 // 2 components per vertex (x, y)
53
+ })
54
+ },
55
+ count: 3
56
+ });
57
+
58
+ bagl.frame(() => {
59
+ bagl.clear({ color: [0, 0, 0, 1] });
60
+ drawTriangle();
61
+ });
62
+ ```
63
+
64
+ ### Deferred Context Binding
65
+
66
+ ```typescript
67
+ import { createBagl } from 'bagl';
68
+
69
+ // Create bagl without a canvas
70
+ const bagl = createBagl();
71
+
72
+ // Prepare resources and commands before DOM is ready
73
+ const vertices = bagl.buffer({
74
+ data: new Float32Array([-1, -1, 1, -1, 0, 1]),
75
+ size: 2
76
+ });
77
+
78
+ const drawTriangle = bagl({
79
+ vert: `#version 300 es
80
+ precision mediump float;
81
+ in vec2 position;
82
+ void main() { gl_Position = vec4(position, 0.0, 1.0); }`,
83
+ frag: `#version 300 es
84
+ precision mediump float;
85
+ out vec4 color;
86
+ void main() { color = vec4(0.3, 0.7, 0.9, 1.0); }`,
87
+ attributes: { position: vertices },
88
+ count: 3
89
+ });
90
+
91
+ // Set up render loop
92
+ bagl.frame(() => {
93
+ bagl.clear({ color: [0, 0, 0, 1] });
94
+ drawTriangle();
95
+ });
96
+
97
+ // Later, attach to canvas
98
+ const canvas = document.querySelector('canvas')!;
99
+ bagl.attach(canvas);
100
+ ```
101
+
102
+ ### Animated Example with Context
103
+
104
+ ```typescript
105
+ import { createBagl } from 'bagl';
106
+
107
+ const bagl = createBagl();
108
+
109
+ const vertices = bagl.buffer({
110
+ data: new Float32Array([-0.5, -0.5, 0.5, -0.5, 0.0, 0.5]),
111
+ size: 2
112
+ });
113
+
114
+ const drawAnimatedTriangle = bagl({
115
+ vert: `
116
+ #version 300 es
117
+ precision mediump float;
118
+ in vec2 position;
119
+ uniform float time;
120
+ void main() {
121
+ vec2 pos = position;
122
+ pos.x += sin(time) * 0.1;
123
+ pos.y += cos(time * 0.5) * 0.05;
124
+ gl_Position = vec4(pos, 0.0, 1.0);
125
+ }
126
+ `,
127
+ frag: `
128
+ #version 300 es
129
+ precision mediump float;
130
+ uniform float time;
131
+ out vec4 color;
132
+ void main() {
133
+ color = vec4(
134
+ 0.5 + 0.5 * sin(time),
135
+ 0.3 + 0.3 * cos(time * 0.7),
136
+ 0.7 + 0.3 * sin(time * 1.3),
137
+ 1.0
138
+ );
139
+ }
140
+ `,
141
+ attributes: { position: vertices },
142
+ uniforms: {
143
+ time: (context, props) => context.time
144
+ },
145
+ count: 3
146
+ });
147
+
148
+ bagl.frame(() => {
149
+ bagl.clear({ color: [0, 0, 0, 1] });
150
+ drawAnimatedTriangle();
151
+ });
152
+ ```
153
+
154
+ ## API Reference
155
+
156
+ ### Core Functions
157
+
158
+ #### `createBagl(canvas?)`
159
+ Creates a new bagl instance. If a canvas is provided, immediately attaches to it.
160
+
161
+ #### `bagl.attach(target)`
162
+ Attaches to a canvas or WebGL2 context.
163
+
164
+ #### `bagl.detach()`
165
+ Detaches from the current context and destroys all GPU resources.
166
+
167
+ #### `bagl.destroy()`
168
+ Destroys the bagl instance, cancels all animation loops, and cleans up resources.
169
+
170
+ #### `bagl.attached`
171
+ Boolean indicating if currently attached to a context.
172
+
173
+ ### Context Object
174
+
175
+ The bagl instance provides a context object with timing and dimension information:
176
+
177
+ ```typescript
178
+ bagl.context.time // Current time in seconds
179
+ bagl.context.ticks // Frame count
180
+ bagl.context.width // Canvas width
181
+ bagl.context.height // Canvas height
182
+ bagl.context.deltaTime // Time since last frame
183
+ ```
184
+
185
+ ### Resource Creation
186
+
187
+ #### `bagl.buffer(data)`
188
+ Creates a buffer for vertex data.
189
+
190
+ ```typescript
191
+ const buffer = bagl.buffer({
192
+ data: new Float32Array([...]),
193
+ size: 3, // Number of components per vertex (1-4)
194
+ type: 'array', // or 'elements'
195
+ usage: 'static' // 'static', 'dynamic', or 'stream'
196
+ });
197
+ ```
198
+
199
+ #### `bagl.elements(data)`
200
+ Creates an element buffer for indexed drawing.
201
+
202
+ ```typescript
203
+ const elements = bagl.elements({
204
+ data: new Uint16Array([...]),
205
+ usage: 'static'
206
+ });
207
+ ```
208
+
209
+ #### `bagl.texture(options)`
210
+ Creates a 2D texture.
211
+
212
+ ```typescript
213
+ const texture = bagl.texture({
214
+ data: imageData,
215
+ width: 512,
216
+ height: 512,
217
+ format: 'rgba',
218
+ min: 'linear',
219
+ mag: 'linear'
220
+ });
221
+ ```
222
+
223
+ #### `bagl.cube(options)`
224
+ Creates a cubemap texture.
225
+
226
+ #### `bagl.framebuffer(options)`
227
+ Creates a framebuffer for render-to-texture.
228
+
229
+ ```typescript
230
+ const fbo = bagl.framebuffer({
231
+ color: 1,
232
+ depth: true,
233
+ width: 512,
234
+ height: 512
235
+ });
236
+ ```
237
+
238
+ ### Drawing Commands
239
+
240
+ #### `bagl(description)`
241
+ Creates a draw command.
242
+
243
+ ```typescript
244
+ const draw = bagl({
245
+ vert: 'vertex shader source',
246
+ frag: 'fragment shader source',
247
+ attributes: { position: buffer },
248
+ uniforms: {
249
+ time: (context, props) => context.time,
250
+ resolution: (context, props) => [context.width, context.height]
251
+ },
252
+ count: 3,
253
+ framebuffer: fbo
254
+ });
255
+ ```
256
+
257
+ ### Uniform Functions
258
+
259
+ Uniforms can be static values or functions that receive context and props:
260
+
261
+ ```typescript
262
+ uniforms: {
263
+ // Static value
264
+ color: [1, 0, 0, 1],
265
+
266
+ // Function with context
267
+ time: (context, props) => context.time,
268
+
269
+ // Function with context and props
270
+ scale: (context, props) => props.scale || 1.0,
271
+
272
+ // Dynamic matrix
273
+ model: (context, props) => {
274
+ const model = mat4.create();
275
+ mat4.rotateY(model, model, context.time);
276
+ return model;
277
+ }
278
+ }
279
+ ```
280
+
281
+ ### State Management
282
+
283
+ #### `bagl.clear(options)`
284
+ Clears the framebuffer.
285
+
286
+ ```typescript
287
+ bagl.clear({
288
+ color: [0, 0, 0, 1],
289
+ depth: 1,
290
+ stencil: 0
291
+ });
292
+ ```
293
+
294
+ #### `bagl.frame(callback)`
295
+ Sets up a render loop.
296
+
297
+ ```typescript
298
+ const cancel = bagl.frame(({ time, deltaTime, tick }) => {
299
+ // Render frame
300
+ });
301
+
302
+ // Later, cancel the loop
303
+ cancel();
304
+ ```
305
+
306
+ ### Context Information
307
+
308
+ #### `bagl.limits`
309
+ Access to WebGL2 limits.
310
+
311
+ #### `bagl.extensions`
312
+ Available WebGL2 extensions.
313
+
314
+ ## Advanced Features
315
+
316
+ ### 3D Rendering with Lighting
317
+
318
+ ```typescript
319
+ import { createBagl } from 'bagl';
320
+ import * as mat4 from 'gl-mat4';
321
+
322
+ const bagl = createBagl();
323
+
324
+ // Create cube with normals
325
+ const positions = bagl.buffer({
326
+ data: new Float32Array([/* cube vertices */]),
327
+ size: 3
328
+ });
329
+
330
+ const normals = bagl.buffer({
331
+ data: new Float32Array([/* cube normals */]),
332
+ size: 3
333
+ });
334
+
335
+ const drawCube = bagl({
336
+ vert: `
337
+ #version 300 es
338
+ precision mediump float;
339
+ in vec3 position;
340
+ in vec3 normal;
341
+ uniform mat4 model, view, projection;
342
+ out vec3 vNormal, vPosition;
343
+ void main() {
344
+ vPosition = position;
345
+ vNormal = normal;
346
+ gl_Position = projection * view * model * vec4(position, 1.0);
347
+ }
348
+ `,
349
+ frag: `
350
+ #version 300 es
351
+ precision mediump float;
352
+ uniform float time;
353
+ uniform mat4 model;
354
+ in vec3 vNormal, vPosition;
355
+ out vec4 color;
356
+ void main() {
357
+ mat3 normalMatrix = mat3(model);
358
+ vec3 worldNormal = normalize(normalMatrix * vNormal);
359
+ vec3 lightDir = normalize(vec3(sin(time), cos(time), 0.5));
360
+ float diffuse = max(dot(worldNormal, lightDir), 0.0);
361
+ vec3 baseColor = vec3(0.8, 0.6, 0.4);
362
+ color = vec4(baseColor * (0.2 + 0.8 * diffuse), 1.0);
363
+ }
364
+ `,
365
+ attributes: { position: positions, normal: normals },
366
+ uniforms: {
367
+ model: (context, props) => {
368
+ const model = mat4.create();
369
+ mat4.rotateY(model, model, context.time * 0.5);
370
+ return model;
371
+ },
372
+ view: (context, props) => {
373
+ const view = mat4.create();
374
+ mat4.translate(view, view, [0, 0, -3]);
375
+ return view;
376
+ },
377
+ projection: (context, props) => {
378
+ const projection = mat4.create();
379
+ const aspect = context.width / context.height;
380
+ mat4.perspective(projection, Math.PI / 4, aspect, 0.1, 100.0);
381
+ return projection;
382
+ },
383
+ time: (context, props) => context.time
384
+ },
385
+ depth: { enable: true, func: 'less' },
386
+ count: 36
387
+ });
388
+
389
+ bagl.frame(() => {
390
+ bagl.clear({ color: [0, 0, 0, 1], depth: 1 });
391
+ drawCube();
392
+ });
393
+ ```
394
+
395
+ ### Context Loss Handling
396
+
397
+ ```typescript
398
+ canvas.addEventListener('webglcontextlost', (e) => {
399
+ e.preventDefault();
400
+ bagl.detach();
401
+ });
402
+
403
+ canvas.addEventListener('webglcontextrestored', () => {
404
+ bagl.attach(canvas);
405
+ });
406
+ ```
407
+
408
+ ### Resource Lifecycle
409
+
410
+ Resources are automatically managed, but you can manually destroy them:
411
+
412
+ ```typescript
413
+ const buffer = bagl.buffer({ data: new Float32Array([...]) });
414
+ // ... use buffer
415
+ buffer.destroy(); // Manually destroy
416
+ ```
417
+
418
+ ## Performance Considerations
419
+
420
+ - **State Diffing**: Bagl automatically caches WebGL state and only updates what has changed
421
+ - **VAOs**: Uses WebGL2 Vertex Array Objects for efficient attribute binding
422
+ - **Resource Pooling**: Resources are reused when possible
423
+ - **Lazy Compilation**: Shaders are compiled only when needed
424
+ - **Loop Management**: Animation loops are automatically cancelled when the bagl instance is destroyed
425
+
426
+ ## Browser Support
427
+
428
+ - WebGL2 capable browsers
429
+ - Modern browsers with ES2015+ support
430
+ - TypeScript 4.0+
431
+
432
+ ## License
433
+
434
+ MIT
package/dist/api.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { Bagl, Context, BaglInit, WebGLExtensions, GLLimits } from './types';
2
+ import { type ContextLifecycle } from './context-life';
3
+ import { type StateManager } from './state';
4
+ export type InternalState = {
5
+ context: ContextLifecycle;
6
+ contextObj: Context;
7
+ glContextState: GLContextState | null;
8
+ };
9
+ export type GLContextState = {
10
+ gl: WebGL2RenderingContext;
11
+ context: ContextLifecycle;
12
+ state: StateManager;
13
+ limits: GLLimits;
14
+ extensions: Partial<Record<keyof WebGLExtensions, any>>;
15
+ };
16
+ export declare function createBaglInternalState(): InternalState;
17
+ export declare function createStateManagerFactory(internalState: InternalState, initObject: any): void;
18
+ export declare function createBagl(init?: BaglInit): Bagl;