fast-layer 0.1.1

WIP: A fast WebAssembly-based layer for high-performance MapLibre/Mapbox
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use glam::f32::{Mat4, Vec3};
use js_sys::Uint8Array;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::spawn_local;
use web_sys::{
    Element, HtmlCanvasElement, WebGl2RenderingContext, WebGlBuffer, WebGlProgram, WebGlShader,
    WebGlUniformLocation, WebGlVertexArrayObject, console, window,
};
mod init;
mod shaders;

const PI: f32 = 3.14159265358979323846;
/// Simple mesh data to be consumed by the vertex shader.
///
/// - `vertices` is a flat list of `f32` vertex attributes (e.g. position, uv, etc.).
/// - `indices` describes element indices (u16) for indexed drawing.
#[derive(Clone, Debug)]
pub struct Mesh {
    pub vertices: Vec<f32>,
    pub indices: Vec<u16>,
}

impl Mesh {
    /// Create a new mesh from raw vertex and index arrays.
    pub fn new(vertices: Vec<f32>, indices: Vec<u16>) -> Self {
        Mesh { vertices, indices }
    }

    /// Number of vertices (interpreted as count of attribute groups should be computed by caller).
    pub fn vertex_count(&self) -> usize {
        // This returns the number of f32 values; callers can divide by the vertex stride.
        self.vertices.len()
    }

    /// Number of indices for indexed drawing.
    pub fn index_count(&self) -> usize {
        self.indices.len()
    }
}

/// Returns a unit cube mesh centered at the origin with side length 2 (from -1 to +1).
///
/// Vertex layout (per-vertex, flat `Vec<f32>`):
/// `[x, y, z, nx, ny, nz, u, v]` (8 floats per vertex).
///
/// The cube uses 24 unique vertices (4 per face) so each face has correct normals
/// and texture coordinates. Indices are `u16` for 36 elements (6 faces × 2 tris × 3).
pub fn cube() -> Mesh {
    // Helper to push one vertex into the flat array
    let mut verts: Vec<f32> = Vec::with_capacity(24 * 8);
    let scale = 10000.0; // Scale up the cube to make it visible on the map
    let mut push_v = |pos: [f32; 3], norm: [f32; 3], uv: [f32; 2]| {
        verts.push(pos[0] * scale);
        verts.push(pos[1] * scale);
        verts.push(pos[2] * scale);
        verts.push(norm[0]);
        verts.push(norm[1]);
        verts.push(norm[2]);
        verts.push(uv[0]);
        verts.push(uv[1]);
    };

    // Define the six faces: front, back, top, bottom, right, left
    // Each face: 4 verts (ccw), normal, uvs arranged (0,0),(1,0),(1,1),(0,1)
    // Front (z = +1)
    let n = [0.0, 0.0, 1.0];
    push_v([-1.0, -1.0, 1.0], n, [0.0, 0.0]);
    push_v([1.0, -1.0, 1.0], n, [1.0, 0.0]);
    push_v([1.0, 1.0, 1.0], n, [1.0, 1.0]);
    push_v([-1.0, 1.0, 1.0], n, [0.0, 1.0]);

    // Back (z = -1)
    let n = [0.0, 0.0, -1.0];
    push_v([1.0, -1.0, -1.0], n, [0.0, 0.0]);
    push_v([-1.0, -1.0, -1.0], n, [1.0, 0.0]);
    push_v([-1.0, 1.0, -1.0], n, [1.0, 1.0]);
    push_v([1.0, 1.0, -1.0], n, [0.0, 1.0]);

    // Top (y = +1)
    let n = [0.0, 1.0, 0.0];
    push_v([-1.0, 1.0, 1.0], n, [0.0, 0.0]);
    push_v([1.0, 1.0, 1.0], n, [1.0, 0.0]);
    push_v([1.0, 1.0, -1.0], n, [1.0, 1.0]);
    push_v([-1.0, 1.0, -1.0], n, [0.0, 1.0]);

    // Bottom (y = -1)
    let n = [0.0, -1.0, 0.0];
    push_v([-1.0, -1.0, -1.0], n, [0.0, 0.0]);
    push_v([1.0, -1.0, -1.0], n, [1.0, 0.0]);
    push_v([1.0, -1.0, 1.0], n, [1.0, 1.0]);
    push_v([-1.0, -1.0, 1.0], n, [0.0, 1.0]);

    // Right (x = +1)
    let n = [1.0, 0.0, 0.0];
    push_v([1.0, -1.0, 1.0], n, [0.0, 0.0]);
    push_v([1.0, -1.0, -1.0], n, [1.0, 0.0]);
    push_v([1.0, 1.0, -1.0], n, [1.0, 1.0]);
    push_v([1.0, 1.0, 1.0], n, [0.0, 1.0]);

    // Left (x = -1)
    let n = [-1.0, 0.0, 0.0];
    push_v([-1.0, -1.0, -1.0], n, [0.0, 0.0]);
    push_v([-1.0, -1.0, 1.0], n, [1.0, 0.0]);
    push_v([-1.0, 1.0, 1.0], n, [1.0, 1.0]);
    push_v([-1.0, 1.0, -1.0], n, [0.0, 1.0]);

    // Indices: 6 faces × 2 triangles × 3 indices = 36
    let mut indices: Vec<u16> = Vec::with_capacity(36);
    for face in 0..6u16 {
        let base = face * 4;
        indices.push(base + 0);
        indices.push(base + 1);
        indices.push(base + 2);
        indices.push(base + 0);
        indices.push(base + 2);
        indices.push(base + 3);
    }

    Mesh::new(verts, indices)
}

#[wasm_bindgen]
pub struct FastLayer {
    canvas_id: String,
    context: WebGl2RenderingContext,
    program: Option<WebGlProgram>,
    model: Option<Mesh>,
    vao: Option<WebGlVertexArrayObject>,
    vbo: Option<WebGlBuffer>,
    ebo: Option<WebGlBuffer>,
}

#[wasm_bindgen]
impl FastLayer {
    pub fn new(canvas_id: &str) -> FastLayer {
        let document = web_sys::window().unwrap().document().unwrap();
        let canvas = document.get_element_by_id(canvas_id).unwrap();
        let canvas: web_sys::HtmlCanvasElement = canvas
            .dyn_into::<web_sys::HtmlCanvasElement>()
            .map_err(|_| ())
            .unwrap();
        let context: WebGl2RenderingContext = canvas
            .get_context("webgl2")
            .unwrap()
            .unwrap()
            .dyn_into()
            .unwrap();

        // Enable depth testing for 3D rendering
        context.enable(WebGl2RenderingContext::DEPTH_TEST);

        FastLayer {
            canvas_id: canvas_id.to_string(),
            context,
            program: None,
            model: None,
            vao: None,
            vbo: None,
            ebo: None,
        }
    }

    pub fn compile(&mut self) {
        let vertex_source = shaders::VERTEX_SOURCE;

        let fragment_source = shaders::FRAGMENT_SOURCE;

        let vertex_shader = self
            .context
            .create_shader(WebGl2RenderingContext::VERTEX_SHADER)
            .unwrap();
        self.context.shader_source(&vertex_shader, vertex_source);
        self.context.compile_shader(&vertex_shader);

        if !self
            .context
            .get_shader_parameter(&vertex_shader, WebGl2RenderingContext::COMPILE_STATUS)
            .as_bool()
            .unwrap_or(false)
        {
            let info = self
                .context
                .get_shader_info_log(&vertex_shader)
                .unwrap_or_else(|| "Unknown error".to_string());
            panic!("Could not compile vertex shader. \n\n{}", info);
        }

        let fragment_shader = self
            .context
            .create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)
            .unwrap();
        self.context
            .shader_source(&fragment_shader, fragment_source);
        self.context.compile_shader(&fragment_shader);

        if !self
            .context
            .get_shader_parameter(&fragment_shader, WebGl2RenderingContext::COMPILE_STATUS)
            .as_bool()
            .unwrap_or(false)
        {
            let info = self
                .context
                .get_shader_info_log(&fragment_shader)
                .unwrap_or_else(|| "Unknown error".to_string());
            panic!("Could not compile fragment shader. \n\n{}", info);
        }

        let program = self.context.create_program().unwrap();
        self.context.attach_shader(&program, &vertex_shader);
        self.context.attach_shader(&program, &fragment_shader);
        self.context.link_program(&program);

        if !self
            .context
            .get_program_parameter(&program, WebGl2RenderingContext::LINK_STATUS)
            .as_bool()
            .unwrap_or(false)
        {
            let info = self
                .context
                .get_program_info_log(&program)
                .unwrap_or_else(|| "Unknown error".to_string());
            panic!("Could not link WebGL program. \n\n{}", info);
        }

        self.program = Some(program);

        // If we have a model, create/bind VAO, VBO, EBO and upload data.
        if let Some(mesh) = &self.model {
            // Create VAO
            let vao = self.context.create_vertex_array();
            self.context.bind_vertex_array(vao.as_ref());

            // Create VBO and upload vertex data
            let vbo = self.context.create_buffer();
            self.context
                .bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, vbo.as_ref());
            // Safety: view into wasm memory for Float32Array
            unsafe {
                let vert_array = js_sys::Float32Array::view(&mesh.vertices);
                self.context.buffer_data_with_array_buffer_view(
                    WebGl2RenderingContext::ARRAY_BUFFER,
                    &vert_array,
                    WebGl2RenderingContext::STATIC_DRAW,
                );
            }

            // Create EBO and upload index data
            let ebo = self.context.create_buffer();
            self.context
                .bind_buffer(WebGl2RenderingContext::ELEMENT_ARRAY_BUFFER, ebo.as_ref());
            unsafe {
                let idx_array = js_sys::Uint16Array::view(&mesh.indices);
                self.context.buffer_data_with_array_buffer_view(
                    WebGl2RenderingContext::ELEMENT_ARRAY_BUFFER,
                    &idx_array,
                    WebGl2RenderingContext::STATIC_DRAW,
                );
            }

            // Configure vertex attributes
            // Our vertex layout: [x,y,z, nx,ny,nz, u,v] => stride = 8 * 4 bytes
            if let Some(ref prog) = self.program {
                // position
                let pos_loc = self.context.get_attrib_location(prog, "a_position");
                if pos_loc >= 0 {
                    let idx: u32 = pos_loc as u32;
                    self.context.enable_vertex_attrib_array(idx);
                    // size=3 (vec3), type=FLOAT, normalized=false, stride=32, offset=0
                    self.context.vertex_attrib_pointer_with_i32(
                        idx,
                        3,
                        WebGl2RenderingContext::FLOAT,
                        false,
                        (8 * std::mem::size_of::<f32>()) as i32,
                        0,
                    );
                }
                // normal
                let normal_loc = self.context.get_attrib_location(prog, "a_normal");
                if normal_loc >= 0 {
                    let idx: u32 = normal_loc as u32;
                    self.context.enable_vertex_attrib_array(idx);
                    // size=3 (vec3), type=FLOAT, normalized=false, stride=32, offset=0
                    self.context.vertex_attrib_pointer_with_i32(
                        idx,
                        3,
                        WebGl2RenderingContext::FLOAT,
                        false,
                        (8 * std::mem::size_of::<f32>()) as i32,
                        (3 * std::mem::size_of::<f32>()) as i32,
                    );
                }
                // normal
                let uv_loc = self.context.get_attrib_location(prog, "a_uv");
                if uv_loc >= 0 {
                    let idx: u32 = uv_loc as u32;
                    self.context.enable_vertex_attrib_array(idx);
                    // size=3 (vec3), type=FLOAT, normalized=false, stride=32, offset=0
                    self.context.vertex_attrib_pointer_with_i32(
                        idx,
                        2,
                        WebGl2RenderingContext::FLOAT,
                        false,
                        (8 * std::mem::size_of::<f32>()) as i32,
                        (6 * std::mem::size_of::<f32>()) as i32,
                    );
                }
            }

            // Unbind VAO to avoid accidental state changes
            self.context.bind_vertex_array(None);

            // Save handles
            self.vao = vao;
            self.vbo = vbo;
            self.ebo = ebo;
        }
    }

    pub fn draw(&self, matrix: &[f32]) {
        if matrix.len() != 16 {
            panic!("matrix must be 16 length")
        }
        // Ensure the program, model and VAO are present
        assert!(self.program.is_some(), "No compiled program available");
        assert!(self.model.is_some(), "No model available");
        assert!(self.vao.is_some(), "No VAO available");

        // Enable depth testing for 3D rendering
        // self.context.enable(WebGl2RenderingContext::DEPTH_TEST);
        // self.context.depth_func(WebGl2RenderingContext::LEQUAL);
        // self.context.clear_color(0.0, 0.0, 0.3, 1.0);
        // self.context.clear_depth(1.0);
        // self.context.clear(
        //     WebGl2RenderingContext::COLOR_BUFFER_BIT | WebGl2RenderingContext::DEPTH_BUFFER_BIT,
        // );
        let prog = self.program.as_ref().unwrap();
        self.context.use_program(Some(prog));
        let location = self.context.get_uniform_location(prog, "u_matrix");

        if let Some(loc) = location {
            // let perspective: Mat4 =
            //     Mat4::perspective_rh_gl(3.14159 / 3.0, 785.0 / 400.0, 1.0, 2000.0);

            // // multiply perspective by matrix
            // let matrix_array: [f32; 16] = [
            //     7.585063395431608,
            //     1.2318389044942468e-15,
            //     0.0,
            //     0.0,
            //     -5.68788651470446e-32,
            //     6.159194522471234e-16,
            //     -3.4426192810028815,
            //     -3.3529093323122527,
            //     9.289023608545075e-16,
            //     -10.058727996936758,
            //     -2.1079963415815706e-16,
            //     -2.0530648408237448e-16,
            //     0.0,
            //     0.0,
            //     901.2587959866221,
            //     901.5,
            // ];

            // let perspective = perspective.mul_mat4(&Mat4::from_cols_array(matrix_array));

            // let matrix_array: [f32; 16] = [
            //     1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            // ];

            // Result main * model

            // let perspective: [f32; 16] = [
            //     7.595366038503267,
            //     1.2318389044942468e-15,
            //     0.0,
            //     0.0,
            //     -5.695612259571457e-32,
            //     6.159194522471234e-16,
            //     -3.4426192810028815,
            //     -3.3529093323122527,
            //     9.301640707405538e-16,
            //     -10.058727996936758,
            //     -2.1079963415815706e-16,
            //     -2.0530648408237448e-16,
            //     0.0,
            //     0.0,
            //     721.3069565217392,
            //     721.5,
            // ];
            // console::log_1(&JsValue::from_str(&format!(
            //     "perspective: {:?}",
            //     perspective
            // )));

            // Upload as column-major mat4
            self.context
                .uniform_matrix4fv_with_f32_array(Some(&loc), false, &matrix);
        }

        let model_location = self.context.get_uniform_location(prog, "u_model_matrix");
        if let Some(loc) = model_location {
            // console::log_1(&JsValue::from_str("model matrix"));
            // Upload identity matrix for model matrix
            let model: [f32; 16] = [
                2.4981121214570498e-8,
                -3.05930501345358e-24,
                -0.0,
                -0.0,
                -1.8732840461706885e-40,
                -1.52965250672679e-24,
                2.4981121214570498e-8,
                0.0,
                3.05930501345358e-24,
                2.4981121214570498e-8,
                1.52965250672679e-24,
                0.0,
                0.5,
                0.5,
                0.0,
                1.0,
            ];
            // let model: [f32; 16] = [];
            // // let a = perspective.mul_mat4(rhs)
            self.context
                .uniform_matrix4fv_with_f32_array(Some(&loc), false, &model);
        }

        // Bind VAO and draw the model with triangles
        let mesh = self.model.as_ref().unwrap();
        self.context.bind_vertex_array(self.vao.as_ref());
        let count = mesh.index_count() as i32;
        self.context.draw_elements_with_i32(
            WebGl2RenderingContext::TRIANGLES,
            count,
            WebGl2RenderingContext::UNSIGNED_SHORT,
            0,
        );
        self.context.bind_vertex_array(None);
    }

    pub fn load_model_from_url(&mut self, url: &str) {
        self.model = Some(cube());
        return;
        let url = url.to_string();
        spawn_local(async move {
            let window = match web_sys::window() {
                Some(w) => w,
                None => {
                    console::log_1(&JsValue::from_str("No window available"));
                    return;
                }
            };

            let fetch_promise = window.fetch_with_str(&url);
            match wasm_bindgen_futures::JsFuture::from(fetch_promise).await {
                Ok(resp_value) => {
                    let resp: web_sys::Response = resp_value.dyn_into().unwrap();
                    if !resp.ok() {
                        console::log_1(&JsValue::from_str(&format!(
                            "Failed to fetch {}: HTTP {}",
                            url,
                            resp.status()
                        )));
                        return;
                    }

                    match resp.array_buffer() {
                        Ok(ab_promise) => {
                            match wasm_bindgen_futures::JsFuture::from(ab_promise).await {
                                Ok(array_buffer) => {
                                    let u8_array = Uint8Array::new(&array_buffer);
                                    let size = u8_array.length();
                                    console::log_1(&JsValue::from_str(&format!(
                                        "Loaded model size: {}",
                                        size
                                    )));
                                }
                                Err(err) => {
                                    console::log_1(&JsValue::from_str(&format!(
                                        "Failed to read array_buffer: {:?}",
                                        err
                                    )));
                                }
                            }
                        }
                        Err(err) => {
                            console::log_1(&JsValue::from_str(&format!(
                                "Failed to call array_buffer(): {:?}",
                                err
                            )));
                        }
                    }
                }
                Err(err) => {
                    console::log_1(&JsValue::from_str(&format!("Fetch error: {:?}", err)));
                }
            }
        });
    }
}