Babylon in Rust->WASM Example

I was able to recreate the example given in the readme in Rust by using FFI to define external functions from @babylonjs/core. Although this gives someone the opportunity to develop solely in Rust, I am unsure about the performance hit from using FFI so heavily. Anyways, just an experiment for now, but this is something that I’m very interested in exploring further, so I’ll probably do some benchmarking later to figure out how to optimize this.

#[wasm_bindgen(start)]
pub fn main() {
    let canvas = &APPLICATION.canvas.borrow();
    let engine = &APPLICATION.engine.borrow();
    let scene = &APPLICATION.scene.borrow();

    let camera = FreeCamera::new("camera", Vector3::new(0.0, 5.0, -10.0), &scene);
    camera.set_target(Vector3::zero());
    camera.attach_control(&canvas, true);

    let light = HemisphericLight::new("light", Vector3::new(0.0, 1.0, 0.0), &scene);
    light.set_intensity(0.7);

    let sphere = Mesh::create_sphere("sphere", 16, 2.0, &scene, false, 0);
    sphere.get_position().set_y(2.0);

    Mesh::create_ground("ground", 6.0, 6.0, 2, &scene);

    let render_callback = Closure::wrap(Box::new(move || {
        &APPLICATION.scene.borrow().render();
    }) as Box<dyn FnMut()>);

    engine.run_render_loop(render_callback.as_ref());
    render_callback.forget();
}

As you can see, the code is almost identical to the example in the readme, so I know now that it’s at least possible to get the API fully exposed (with tweaks here and there of course). The biggest pain point so far has been callback functions. I got it to work, but I feel like it can be done better. Still exploring.

Full source: babylon.rs · GitHub

5 Likes

Excellent!