Packages

Run WebAssembly from Elixir. Load WASM modules in Rust, Go, C — call them like native functions.

Current section

Files

Jump to
firebird lib wasm_modules physics.ex
Raw

lib/wasm_modules/physics.ex

defmodule Firebird.WasmModules.Physics do
Module.register_attribute(__MODULE__, :wasm, accumulate: true)
@moduledoc """
Simple physics calculations compiled to WebAssembly.
Demonstrates integer-based physics computations. Uses scaled integers
(multiply by 1000) for fixed-point arithmetic since the WASM target
only supports integers and floats.
"""
@wasm true
def distance(velocity, time), do: velocity * time
@wasm true
def kinetic_energy(mass, velocity) do
# KE = 1/2 * m * v^2 (returns 2x for integer math)
mass * velocity * velocity
end
@wasm true
def gravitational_force(m1, m2, r) do
# F ∝ m1 * m2 / r^2 (simplified, no G constant)
div(m1 * m2, r * r)
end
@wasm true
def projectile_range(v0, angle_deg) do
# Simplified: range = v0^2 * sin(2*angle) / g
# For 45 degrees (optimal): range = v0^2 / g
# Using g = 10 for simplicity
if angle_deg == 45 do
div(v0 * v0, 10)
else
# Approximate for other angles
div(v0 * v0 * angle_deg * (90 - angle_deg), 10 * 45 * 45)
end
end
@wasm true
def momentum(mass, velocity), do: mass * velocity
@wasm true
def acceleration(force, mass), do: div(force, mass)
@wasm true
def work(force, displacement), do: force * displacement
@wasm true
def manhattan_distance(x1, y1, x2, y2) do
abs_diff(x1, x2) + abs_diff(y1, y2)
end
@wasm true
def abs_diff(a, b) do
if a >= b do
a - b
else
b - a
end
end
end