webgl2 1.0.3 → 1.0.4
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 +14 -0
- package/README.md +167 -84
- package/index.js +15 -0
- package/package.json +19 -2
- package/docs/1-webgl-emulator.md +0 -51
package/LICENSE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
Copyright (c) 2025 WebGL2 Platform Team
|
|
2
|
+
All Rights Reserved.
|
|
3
|
+
|
|
4
|
+
THIS IS A RESTRICTIVE PLACEHOLDER LICENSE (PROPRIETARY).
|
|
5
|
+
|
|
6
|
+
Permission to use, copy, modify, distribute, or publish this software, in whole
|
|
7
|
+
or in part, is NOT granted. All rights are reserved by the copyright holder.
|
|
8
|
+
|
|
9
|
+
This file is intentionally restrictive and intended only as a temporary
|
|
10
|
+
placeholder to allow packaging/testing in private. Replace this file with an
|
|
11
|
+
appropriate open-source license (for example, MIT or Apache-2.0)
|
|
12
|
+
if you intend to grant any rights to others.
|
|
13
|
+
|
|
14
|
+
-- END OF PLACEHOLDER LICENSE --
|
package/README.md
CHANGED
|
@@ -1,120 +1,203 @@
|
|
|
1
|
-
|
|
1
|
+
# WebGL2 Development Platform: VISION
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A **Rust + WASM** based toolkit for debugging GLSL shaders and generating ergonomic WebGL2 bindings.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## 🎯 Quick Start
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```bash
|
|
8
|
+
# Build the project
|
|
9
|
+
cargo build --release
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
# Compile a GLSL shader to WASM with debug info
|
|
12
|
+
cargo run --bin webgl2 -- compile tests/fixtures/simple.vert --debug
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
# Validate a shader
|
|
15
|
+
cargo run --bin webgl2 -- validate tests/fixtures/simple.frag
|
|
12
16
|
|
|
13
|
-
|
|
17
|
+
# Generate TypeScript harness
|
|
18
|
+
cargo run --bin webgl2 -- codegen tests/fixtures/simple.vert -o output.ts
|
|
19
|
+
```
|
|
14
20
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
21
|
+
### Build via npm
|
|
22
|
+
|
|
23
|
+
This repository is both a Rust workspace and an npm package. Run the npm build helper to build the Rust workspace for the WASM target and copy produced .wasm files into `runners/wasm/`:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
# from repository root
|
|
27
|
+
npm run build
|
|
28
|
+
```
|
|
19
29
|
|
|
20
|
-
|
|
30
|
+
Notes:
|
|
31
|
+
- The script runs `cargo build --target wasm32-unknown-unknown --release` and copies any `.wasm` files from `target/wasm32-unknown-unknown/release/` into `runners/wasm/`.
|
|
32
|
+
- If you need `wasm-bindgen` output (JS glue), run `wasm-bindgen` manually on the produced `.wasm` files; adding automated wasm-bindgen support is a follow-up task.
|
|
21
33
|
|
|
22
|
-
|
|
34
|
+
## 🚀 Project Overview and Goals
|
|
35
|
+
|
|
36
|
+
The project aims to create a **Composite WebGL2 Development Platform** built with **Rust and WASM**. The primary objective is to significantly improve the developer experience by introducing standard software engineering practices—specifically, **robust debugging and streamlined resource management**—into the WebGL/GLSL workflow, which is currently hindered by platform-specific API complexity and opaque GPU execution.
|
|
37
|
+
|
|
38
|
+
| Key Goals | Target Block | Value Proposition |
|
|
23
39
|
| :--- | :--- | :--- |
|
|
24
|
-
|
|
|
25
|
-
|
|
|
26
|
-
|
|
|
27
|
-
|
|
|
28
|
-
| **`hashbrown`** | **Fast Resource Registry (`u32` handles).** | **C1** |
|
|
29
|
-
| **`serde` / `serde-wasm-bindgen`** | **Safe, clean transfer of configuration and metadata objects.** | **C2** |
|
|
30
|
-
| **`wgpu-types`** | **Validated Resource Structs (optional, highly recommended).** | **C1** |
|
|
40
|
+
| **GPU Debugging** | Block 1 (Emulator) | Enable **step-through debugging**, breakpoints, and variable inspection for GLSL code. |
|
|
41
|
+
| **Unit Testing** | Block 1 (Emulator) | Provide a stable, deterministic environment for **automated testing** of graphics logic. |
|
|
42
|
+
| **API Ergonomics** | Block 2 (Codegen) | **Automate boilerplate code** for resource binding, attribute setup, and uniform linking. |
|
|
43
|
+
| **Tech Stack** | Both | Utilize **Rust for safety and WASM for high-performance cross-platform execution** in the browser. |
|
|
31
44
|
|
|
32
45
|
-----
|
|
33
46
|
|
|
34
|
-
##
|
|
47
|
+
## 🛠️ Functional Block 1: WebGL2 Software Rendering Pipeline (The Debugger)
|
|
35
48
|
|
|
36
|
-
This
|
|
49
|
+
This block provides the **deterministic, inspectable execution environment** for GLSL logic.
|
|
37
50
|
|
|
38
|
-
###
|
|
51
|
+
### 1\. **Core Component: Rust-based WebGL2 Emulator (`wasm-gl-emu`)**
|
|
39
52
|
|
|
40
|
-
|
|
53
|
+
* **State Machine Emulation:** Implement a full software model of the WebGL2 state (e.g., Framebuffer Objects, Renderbuffers, Texture Units, Vertex Array Objects, current programs, depth/stencil settings). This component will track all API calls and maintain a CPU-accessible copy of all state.
|
|
54
|
+
* **Rasterization Logic:** Implement CPU-based vertex and fragment processing. This logic must precisely follow the WebGL2/OpenGL ES 3.0 specification, including clipping, primitive assembly, and the fragment pipeline (culling, depth test, blending).
|
|
55
|
+
* **Input/Output:** Expose the emulator's state and rendering results via a standard Rust interface that can be compiled to WASM and wrapped for JavaScript access.
|
|
41
56
|
|
|
42
|
-
|
|
43
|
-
// In src/gl_emulation.rs
|
|
44
|
-
#[wasm_bindgen(js_name = createGLContext)]
|
|
45
|
-
pub fn create_gl_context(width: u32, height: u32) -> GLContextHandle {
|
|
46
|
-
// Initializes internal state (framebuffer, viewport, etc.)
|
|
47
|
-
// Returns a handle to the initialized context instance.
|
|
48
|
-
// ...
|
|
49
|
-
}
|
|
57
|
+
### 2\. **GLSL Translation and Debugging Integration (`glsl-to-wasm`)**
|
|
50
58
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
59
|
+
* **GLSL Frontend:** Use a Rust-based GLSL parser (e.g., based on `naga` or a custom parser) to convert shader source code into an Intermediate Representation (IR).
|
|
60
|
+
* **WASM Backend:** Compile the IR into **WASM module functions**. Each shader stage (Vertex, Fragment) will be converted into a function that executes the shader logic on a single vertex or fragment input.
|
|
61
|
+
* **Source Map Generation:** The crucial step is to generate **high-quality source maps** that link the generated WASM instructions back to the original GLSL source code line and variable names. This enables DevTools/IDE to pause WASM execution and display the corresponding GLSL line and variable values.
|
|
62
|
+
* **JIT Compilation:** For performance during debugging, the WASM modules can be compiled using a fast JIT compiler (potentially leveraging existing browser capabilities or a custom runtime) to execute the many vertex/fragment calls.
|
|
54
63
|
|
|
55
|
-
###
|
|
64
|
+
### 3\. **Debugging and Testing Harness**
|
|
56
65
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
| **API Surface** | Implement the **`glow::Context`** trait on the internal `WasmGLContext` struct. Methods not required for unit testing (e.g., `end_query`, `fence_sync`) are stubbed out to return success/no-op. | Minimizes implementation effort while guaranteeing API correctness. |
|
|
60
|
-
| **Resource Management** | **`WasmGLContext`** contains a **`hashbrown::HashMap<u32, ResourceData>`** registry. All API calls (`createBuffer`, `bindTexture`) reference and mutate resources based on these internal `u32` handles. | Avoids complex host pointers and ensures a deterministic, debuggable state machine. |
|
|
61
|
-
| **Buffer Data Transfer** | The body of `buffer_data()` performs a **transactional copy** of the incoming JavaScript `TypedArray` data directly into the target `Vec<u8>` within the WASM linear memory heap. | Ensures data is persistent and safely managed within the WASM sandbox. |
|
|
66
|
+
* **Test Runner:** Develop a testing harness in Rust/WASM that can execute a defined set of inputs (e.g., vertex attributes, uniform values) against the emulated pipeline and assert on the final pixel output or intermediate variable state.
|
|
67
|
+
* **Step-Through Integration:** The WASM modules, when run by the browser's JavaScript engine, will expose the generated source maps, allowing the developer to naturally set **breakpoints** within the GLSL source file viewed in the browser's DevTools (or a connected IDE).
|
|
62
68
|
|
|
63
|
-
|
|
69
|
+
-----
|
|
64
70
|
|
|
65
|
-
|
|
71
|
+
## ⚙️ Functional Block 2: Introspection and Codegen Tool (The Ergonomics Layer)
|
|
66
72
|
|
|
67
|
-
|
|
68
|
-
2. **Execution Stages:** The `draw_arrays()` body runs the full pipeline: Input Assembly $\rightarrow$ **Vertex Kernel Execution** (calling the Rust function for each vertex) $\rightarrow$ Rasterization (`glam` math) $\rightarrow$ **Fragment Kernel Execution** (calling the Rust function for each pixel).
|
|
69
|
-
3. **Output:** Writes the final color values to the **`WasmGLContext.framebuffer`** array.
|
|
73
|
+
This block automates the error-prone, repetitive JavaScript/TypeScript code required for WebGL2 resource setup.
|
|
70
74
|
|
|
71
|
-
###
|
|
75
|
+
### 1\. **GLSL Introspection Engine (`glsl-parser-rs`)**
|
|
72
76
|
|
|
73
|
-
|
|
77
|
+
* **Parsing:** Use a dedicated Rust parser to analyze the GLSL source files (both Vertex and Fragment shaders).
|
|
78
|
+
* **Annotation Extraction:** The parser must identify and extract **discardable annotations** embedded in the GLSL source.
|
|
79
|
+
* *Example Annotation:*
|
|
80
|
+
```glsl
|
|
81
|
+
//! @buffer_layout MeshData
|
|
82
|
+
layout(location = 0) in vec3 a_position;
|
|
83
|
+
// JSDoc-like for resource description
|
|
84
|
+
/** @uniform_group Camera @semantic ProjectionMatrix */
|
|
85
|
+
uniform mat4 u_projection;
|
|
86
|
+
```
|
|
87
|
+
* **Resource Mapping:** Generate a structured data model (e.g., JSON or Rust structs) that lists all attributes, uniforms, uniform blocks, and their associated types, locations, and extracted metadata (like semantic hints from the annotations).
|
|
74
88
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
89
|
+
### 2\. **Code Generation Module (`js-harness-codegen`)**
|
|
90
|
+
|
|
91
|
+
* **Harness Template:** Define a set of customizable templates (e.g., Handlebars, Tera) for generating the target **JavaScript/TypeScript harness code**.
|
|
92
|
+
* **Code Generation:** Using the resource map data from the parser, the module will generate files that:
|
|
93
|
+
* Define **JavaScript/TypeScript classes** for each shader program.
|
|
94
|
+
* Provide methods for **binding resource objects** (e.g., `program.setUniforms(cameraData)`).
|
|
95
|
+
* Implement all the necessary `gl.bindBuffer()`, `gl.getUniformLocation()`, `gl.vertexAttribPointer()`, and `gl.uniformX()` calls.
|
|
96
|
+
* *Goal:* Reduce the developer's WebGL setup code to simple, type-safe resource assignments.
|
|
97
|
+
|
|
98
|
+
### 3\. **Tool Integration**
|
|
99
|
+
|
|
100
|
+
* Package the Rust component as a **Command-Line Interface (CLI)** tool (or an accompanying library) that runs during the build step, consuming GLSL files and outputting the JavaScript/TypeScript harness code. This integrates smoothly into modern build pipelines (e.g., Webpack, Vite).
|
|
83
101
|
|
|
84
102
|
-----
|
|
85
103
|
|
|
86
|
-
##
|
|
104
|
+
## ⏳ Project Phases and Deliverables
|
|
87
105
|
|
|
88
|
-
|
|
106
|
+
| Phase | Duration | Focus | Key Deliverables |
|
|
107
|
+
| :--- | :--- | :--- | :--- |
|
|
108
|
+
| **Phase 1** | 3 Months | Core Compiler & Codegen | Functional GLSL parser (Block 2). CLI tool for JS harness generation (Block 2). Prototype `glsl-to-wasm` compiler (Block 1). |
|
|
109
|
+
| **Phase 2** | 4 Months | Core Emulator Implementation | Basic WebGL2 State Machine and Triangle Rasterizer (Block 1). Source Map integration (GLSL \<-\> WASM \<-\> DevTools) (Block 1). |
|
|
110
|
+
| **Phase 3** | 3 Months | Feature Completion & Polishing | Full WebGL2 feature set support in emulator (textures, complex blending, stencil). Robustness testing and documentation. |
|
|
111
|
+
| **Phase 4** | 2 Months | Integration & Release | Unit testing framework integration. Final documentation and developer tutorials. Full platform release. |
|
|
89
112
|
|
|
90
|
-
|
|
113
|
+
-----
|
|
91
114
|
|
|
92
|
-
|
|
115
|
+
## � Project Structure
|
|
93
116
|
|
|
94
|
-
```rust
|
|
95
|
-
// In src/codegen.rs
|
|
96
|
-
#[wasm_bindgen(js_name = generateKernelJS)]
|
|
97
|
-
pub fn generate_kernel_js(
|
|
98
|
-
glsl_source: &str,
|
|
99
|
-
options_js: JsValue // Incoming JS object for configuration
|
|
100
|
-
) -> Result<GeneratedOutput, JsValue> {
|
|
101
|
-
// ... logic ...
|
|
102
|
-
}
|
|
103
117
|
```
|
|
118
|
+
webgl2/
|
|
119
|
+
├── crates/
|
|
120
|
+
│ ├── naga-wasm-backend/ # Naga IR → WASM compiler with DWARF
|
|
121
|
+
│ ├── wasm-gl-emu/ # Software rasterizer & WASM runtime
|
|
122
|
+
│ ├── glsl-introspection/ # GLSL parser + annotation extraction
|
|
123
|
+
│ ├── js-codegen/ # TypeScript harness generator
|
|
124
|
+
│ └── webgl2-cli/ # Command-line interface
|
|
125
|
+
├── tests/fixtures/ # Test shaders
|
|
126
|
+
├── docs/ # Detailed documentation
|
|
127
|
+
│ ├── 1-plan.md # Original project plan
|
|
128
|
+
│ └── 1.1-ir-wasm.md # Naga IR → WASM architecture
|
|
129
|
+
└── external/ # Reference implementations (naga, wgpu, servo)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## 🏗️ Architecture
|
|
133
|
+
|
|
134
|
+
This project uses **Naga** (from the wgpu/WebGPU ecosystem) as the shader IR, rather than building a custom IR from scratch. This significantly reduces complexity while providing a proven, well-maintained foundation.
|
|
135
|
+
|
|
136
|
+
### Key Components
|
|
137
|
+
|
|
138
|
+
1. **naga-wasm-backend**: Translates Naga IR to WebAssembly with DWARF debug information
|
|
139
|
+
2. **wasm-gl-emu**: Executes WASM shaders in a software rasterizer for debugging
|
|
140
|
+
3. **glsl-introspection**: Parses GLSL and extracts resource metadata
|
|
141
|
+
4. **js-codegen**: Generates ergonomic TypeScript bindings
|
|
142
|
+
5. **webgl2-cli**: Unified command-line tool
|
|
143
|
+
|
|
144
|
+
See [`docs/1.1-ir-wasm.md`](docs/1.1-ir-wasm.md) for detailed architecture documentation.
|
|
145
|
+
|
|
146
|
+
## 🔧 Development Status
|
|
147
|
+
|
|
148
|
+
**Current Phase: Phase 0 - Foundation Setup** ✅
|
|
149
|
+
|
|
150
|
+
- [x] Workspace structure created
|
|
151
|
+
- [x] Core crate skeletons implemented
|
|
152
|
+
- [x] Basic WASM backend (emits empty functions)
|
|
153
|
+
- [x] Runtime structure (wasmtime integration)
|
|
154
|
+
- [x] CLI tool with compile/validate/codegen/run commands
|
|
155
|
+
- [ ] DWARF debug information generation (in progress)
|
|
156
|
+
- [ ] Browser DevTools integration validation
|
|
157
|
+
|
|
158
|
+
## 📚 Documentation
|
|
159
|
+
|
|
160
|
+
- [`docs/1-plan.md`](docs/1-plan.md) - Original project proposal and plan
|
|
161
|
+
- [`docs/1.1-ir-wasm.md`](docs/1.1-ir-wasm.md) - Naga IR → WASM architecture (recommended reading)
|
|
162
|
+
- [`external/use.md`](external/use.md) - Guide to leveraging external repositories
|
|
163
|
+
|
|
164
|
+
## ⏳ Project Phases
|
|
165
|
+
|
|
166
|
+
| Phase | Duration | Focus | Status |
|
|
167
|
+
| :--- | :--- | :--- | :--- |
|
|
168
|
+
| **Phase 0** | 2 Weeks | Foundation & DWARF Validation | **In Progress** |
|
|
169
|
+
| **Phase 1** | 8 Weeks | Core Backend (scalars, vectors, control flow) | Not Started |
|
|
170
|
+
| **Phase 2** | 6 Weeks | Advanced Features (uniforms, textures, matrices) | Not Started |
|
|
171
|
+
| **Phase 3** | 4 Weeks | Software Rasterizer Integration | Not Started |
|
|
172
|
+
| **Phase 4** | 8 Weeks | Codegen Tool & Polish | Not Started |
|
|
173
|
+
|
|
174
|
+
## 🧪 Testing
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
# Run all tests
|
|
178
|
+
cargo test
|
|
179
|
+
|
|
180
|
+
# Test with a simple shader
|
|
181
|
+
cargo run --bin webgl2 -- compile tests/fixtures/simple.vert --debug -o output.wasm
|
|
182
|
+
cargo run --bin webgl2 -- run output.wasm
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## 🤝 Contributing
|
|
186
|
+
|
|
187
|
+
This project is in early development. Contributions are welcome once Phase 0 is complete and the architecture is validated.
|
|
188
|
+
|
|
189
|
+
## 📄 License
|
|
190
|
+
|
|
191
|
+
MIT OR Apache-2.0
|
|
192
|
+
|
|
193
|
+
-----
|
|
194
|
+
|
|
195
|
+
## �💰 Resource Requirements
|
|
196
|
+
|
|
197
|
+
The project will require specialized expertise in:
|
|
104
198
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
2. **Naga Reflection:** The core logic uses **`naga`** to parse the GLSL and analyze the Intermediate Representation (IR). This analysis extracts:
|
|
109
|
-
* All **Uniform** names, types, and locations.
|
|
110
|
-
* All **Attribute** names and types.
|
|
111
|
-
* All **Texture/Sampler** definitions.
|
|
112
|
-
3. **JavaScript Generation:** Use the reflection data to programmatically generate the user-facing JavaScript class string, including:
|
|
113
|
-
* Class definition (`class MyKernel { ... }`).
|
|
114
|
-
* **Typed Setter Methods** (e.g., `setUniformFloat(name, value)`).
|
|
115
|
-
* WASM calls to Component 1's low-level `buffer_data`, `uniform_1f`, etc., methods.
|
|
116
|
-
4. **Structured Output (Codec):** Build the final **`GeneratedOutput`** struct, which uses **`#[wasm_bindgen]`** to ensure clean object transfer:
|
|
117
|
-
* `kernel_code`: The generated JavaScript class string.
|
|
118
|
-
* `metadata`: Array of objects detailing the introspected resources.
|
|
119
|
-
* `diagnostics`: Array of objects containing warnings and errors from `naga` and custom checks.
|
|
199
|
+
* **Rust and WASM Development**
|
|
200
|
+
* **Computer Graphics / GPU Pipeline Implementation** (for the emulator)
|
|
201
|
+
* **Compiler Design / Language Tooling** (for GLSL parsing and source map generation)
|
|
120
202
|
|
|
203
|
+
Would you like to discuss the **specific toolchain recommendations** for the GLSL-to-WASM compilation process?
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// index.js (compat shim)
|
|
2
|
+
// Re-export the new implementation in `index2.js` so existing consumers who
|
|
3
|
+
// import `index.js` keep working. The legacy implementation was removed and
|
|
4
|
+
// moved to `index2.js` which contains the canonical, tested API.
|
|
5
|
+
|
|
6
|
+
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
|
|
7
|
+
|
|
8
|
+
if (isNode) {
|
|
9
|
+
// In Node.js environments re-export everything from index2.js
|
|
10
|
+
module.exports = require('./index2.js');
|
|
11
|
+
} else {
|
|
12
|
+
// In browsers assume `index2.js` is loaded alongside this file and has
|
|
13
|
+
// populated `window.webGL2`. Nothing else to do here.
|
|
14
|
+
// (Keeping a no-op shim avoids duplicating the implementation.)
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webgl2",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "WebGL2 tools to derisk large GPU projects on the web beyond toys and demos.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"
|
|
7
|
+
"start": "node ./index.js",
|
|
8
|
+
"build:wasm": "node ./scripts/build-wasm.js",
|
|
9
|
+
"build": "node -e \"(async()=>{const p=require('path');const dir=process.env.INIT_CWD||process.cwd();require(p.join(dir,'scripts','build-wasm.js'));})()\"",
|
|
10
|
+
"prepublishOnly": "npm run build",
|
|
11
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
12
|
+
"test:smoke": "npm run build:wasm && node ./test/smoke.js"
|
|
13
|
+
},
|
|
14
|
+
"wasmBuild": {
|
|
15
|
+
"outDir": "wasm",
|
|
16
|
+
"target": "wasm32-unknown-unknown",
|
|
17
|
+
"profile": "release"
|
|
8
18
|
},
|
|
9
19
|
"repository": {
|
|
10
20
|
"type": "git",
|
|
@@ -17,4 +27,11 @@
|
|
|
17
27
|
"url": "https://github.com/mavity/mavity/issues"
|
|
18
28
|
},
|
|
19
29
|
"homepage": "https://github.com/mavity/mavity#readme"
|
|
30
|
+
,
|
|
31
|
+
"files": [
|
|
32
|
+
"index.js",
|
|
33
|
+
"wasm",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
]
|
|
20
37
|
}
|
package/docs/1-webgl-emulator.md
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
# WebGL Emulator (Component 1) Deep Dive
|
|
2
|
-
|
|
3
|
-
The **WebGL Emulator** is the **pure-Rust software graphics driver** that compiles to a single, single-threaded WASM module. Its primary goal is **correctness, fidelity, and debuggability** by mimicking the entire WebGL2 state machine and rendering pipeline on the CPU.
|
|
4
|
-
|
|
5
|
-
## 1. ⚙️ Core Architecture and State Management
|
|
6
|
-
|
|
7
|
-
The emulator's design centers on satisfying the **`glow::Context` trait** while managing all resources within the WASM linear memory.
|
|
8
|
-
|
|
9
|
-
* **Factory Function:** The entire system is instantiated via the clean factory function: `createGLContext(width, height)`. This function initializes the full internal state and returns a handle.
|
|
10
|
-
* **State Container:** The central struct, e.g., `WasmGLContext`, is the single source of truth for the entire GL state. It manages:
|
|
11
|
-
* **Resource Registry (`hashbrown::HashMap<u32, ResourceData>`):** Maps the user-facing $\mathbf{u32}$ integer handles (returned by `gl.createBuffer()`, etc.) to the actual Rust structs holding the data and parameters.
|
|
12
|
-
* **Framebuffer:** A large `Vec<u32>` or `Vec<u8>` in the WASM heap that stores the final pixel output.
|
|
13
|
-
* **Bound State:** Fields tracking the currently bound program, active VAO, active texture unit, viewport dimensions, etc.
|
|
14
|
-
|
|
15
|
-
## 2. 🔌 Implementing the $\mathbf{300+}$ API Surface with `glow`
|
|
16
|
-
|
|
17
|
-
This step minimizes bug surface by reusing the `glow` API definition.
|
|
18
|
-
|
|
19
|
-
* **Trait Implementation:** The `WasmGLContext` struct implements every method defined in the `glow::Context` trait.
|
|
20
|
-
* **Stubbing:** Approximately $\mathbf{80\%}$ of the methods implement simple state updates or stubs:
|
|
21
|
-
* **State Setting:** Methods like `enable(DEPTH_TEST)` simply flip a boolean in the `WasmGLContext` struct.
|
|
22
|
-
* **Resource Binding:** Methods like `bind_buffer(ARRAY_BUFFER, handle)` update the state machine's field to hold the input $\mathbf{u32}$ handle.
|
|
23
|
-
* **Unsupported Features:** Methods for complex GPU features like `begin_query` or `fence_sync` are implemented as **no-ops** (stubs), returning success without affecting internal state, as they are non-goals for a unit-testing platform.
|
|
24
|
-
* **Data Transfer (`buffer_data`):** The body of this function handles the vital **transactional copy** of `TypedArray` data from JavaScript into the WASM heap buffer referenced by the `u32` handle, ensuring data integrity within the emulation.
|
|
25
|
-
|
|
26
|
-
## 3. 🧠 The Complex Core: Shader Translation and Execution
|
|
27
|
-
|
|
28
|
-
The most bespoke and critical logic is transforming the GLSL source into executable Rust code.
|
|
29
|
-
|
|
30
|
-
### A. Shader Compilation Flow (`compile_shader` / `link_program`)
|
|
31
|
-
|
|
32
|
-
1. **Parse & Reflect:** The `shader_source()` and `compile_shader()` methods feed the GLSL code into **`naga`**.
|
|
33
|
-
* **Naga Output:** `naga` performs parsing, validation, and produces its **Intermediate Representation (IR)**.
|
|
34
|
-
2. **Code Generation (IR $\rightarrow$ Rust):** A custom routine is required to traverse the Naga IR and output a **Rust source code string** that accurately replicates the shader's logic.
|
|
35
|
-
* **Vertex Kernel:** Generates a Rust function signature like `fn vs_kernel(uniforms: &Uniforms, vertex_in: &VertexIn) -> VertexOut`, where `VertexIn` and `VertexOut` are structs derived from the shader's attributes and varyings.
|
|
36
|
-
* **Fragment Kernel:** Generates a Rust function signature like `fn fs_kernel(uniforms: &Uniforms, fragment_in: &FragmentIn) -> Color`, implementing all shading logic.
|
|
37
|
-
3. **Kernel Storage:** The Rust source code is compiled (or dynamically built/cached), and a **function pointer or closure** to this executable kernel is stored in the internal `ProgramData` resource.
|
|
38
|
-
|
|
39
|
-
### B. Software Rasterizer Execution (`draw_arrays` and similar)
|
|
40
|
-
|
|
41
|
-
The `draw_arrays()` call initiates the CPU-bound process:
|
|
42
|
-
|
|
43
|
-
1. **Vertex Execution:** The emulation loop iterates through the vertex data. For each vertex, it calls the **Vertex Kernel (Rust function)**, which performs the vertex transformation using **`glam`** math and outputs the clip-space coordinates.
|
|
44
|
-
2. **Rasterization:** The **`glam`**-powered core logic handles triangle setup, clipping, barycentric interpolation of varyings, and determining which pixels are covered.
|
|
45
|
-
3. **Fragment Execution:** For every covered pixel, the loop calls the **Fragment Kernel (Rust function)**, passing the interpolated varyings and uniform data. This executes the final shading calculation.
|
|
46
|
-
4. **Output Merger:** Applies depth, stencil, and blending logic based on the current state before writing the final color result to the **WASM Framebuffer**.
|
|
47
|
-
|
|
48
|
-
## 4. 🔬 Debugging and Output
|
|
49
|
-
|
|
50
|
-
* **Debugging Hooks:** The structure of the generated **Rust CPU Kernels** is explicitly designed to be inspected by WASM debugging tools (like browser DevTools). Because the GLSL is translated into traceable Rust code, the developer can pause execution inside the shader logic.
|
|
51
|
-
* **Final Output:** The separate `presentFrame()` function acts as the single bridge to the host, copying the contents of the **WASM Framebuffer** to a JavaScript `Uint8Array` for display via `ctx.putImageData()`.
|