diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml new file mode 100644 index 00000000..05f7428f --- /dev/null +++ b/.github/workflows/wasm.yml @@ -0,0 +1,65 @@ +name: 🌐 Build WASM + +# Builds the WebAssembly module (issue #171) and runs the Node smoke test. The +# .wasm is built here rather than committed: it is a megabyte of generated +# output, and a stale binary next to live sources is worse than a two minute +# build. + +on: + push: + branches: + - "master" + - "dev" + pull_request: + branches: [ "master", "dev" ] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build-wasm: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + # No LFS: the WASM build reads no test data, and emcmake turns the + # integrity check off by default. + + - name: Cache Emscripten SDK + id: emsdk-cache + uses: actions/cache@v4 + with: + path: ~/emsdk + key: emsdk-${{ runner.os }}-6.0.6 + + - name: Install Emscripten + if: steps.emsdk-cache.outputs.cache-hit != 'true' + run: | + # Pinned to the version the module was developed and tested against. + git clone --depth 1 https://github.com/emscripten-core/emsdk.git ~/emsdk + ~/emsdk/emsdk install 6.0.6 + ~/emsdk/emsdk activate 6.0.6 + + - name: Build the WebAssembly module + run: | + source ~/emsdk/emsdk_env.sh + emcmake cmake -S . -B build-wasm -DCMAKE_BUILD_TYPE=Release + cmake --build build-wasm -j"$(nproc)" + + - name: Report size + run: | + { + echo "### WebAssembly build" + echo "| file | raw | gzip | brotli |" + echo "| --- | --- | --- | --- |" + for f in bin/forefire.wasm bin/forefire.mjs; do + printf '| `%s` | %s | %s | %s |\n' "$(basename "$f")" \ + "$(stat -c%s "$f" | numfmt --to=iec)" \ + "$(gzip -c "$f" | wc -c | numfmt --to=iec)" \ + "$(brotli -c "$f" | wc -c | numfmt --to=iec)" + done + } | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Smoke test under Node + run: node bindings/wasm/smoke.mjs bin/forefire.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 36a0d091..f6769e36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,11 @@ Merged since v2.5.0, not yet released. the first step towards a WebAssembly build and a slim wheel. Commands that read or write NetCDF files report that the build has no NetCDF support. The default stays on. ([#171]) +- An experimental WebAssembly build: `emcmake cmake` compiles the engine + without NetCDF into an ES module whose embind API mirrors `pyforefire`, with + typed arrays in place of NumPy arrays. `FOREFIRE_BUILD_CLI` and + `FOREFIRE_BUILD_WASM` control the two executables. See + `bindings/wasm/README.md`. ([#171]) ### Fixed diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b4f3d2d..871674c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,8 +43,28 @@ else() set(_ff_default_tests ON) endif() +# Emscripten has no NetCDF and no reason for one: a browser build reads its +# data from JS typed arrays. Detecting it here rather than making the caller +# pass the flags keeps `emcmake cmake` a one-liner. +if(EMSCRIPTEN) + set(_ff_default_mpi OFF) + set(_ff_default_native OFF) + set(_ff_default_python OFF) + set(_ff_default_static ON) + set(_ff_default_tools OFF) + set(_ff_default_lfs OFF) + set(_ff_default_netcdf OFF) + set(_ff_default_cli OFF) + set(_ff_default_tests OFF) +else() + set(_ff_default_netcdf ON) + set(_ff_default_cli ON) +endif() + option(FOREFIRE_ENABLE_MPI "Enable MPI coupling when MPI is available" ${_ff_default_mpi}) -option(FOREFIRE_ENABLE_NETCDF "Build the NetCDF-backed I/O paths" ON) +option(FOREFIRE_ENABLE_NETCDF "Build the NetCDF-backed I/O paths" ${_ff_default_netcdf}) +option(FOREFIRE_BUILD_CLI "Build the interactive forefire command line shell" ${_ff_default_cli}) +option(FOREFIRE_BUILD_WASM "Build the Emscripten/embind module" ${EMSCRIPTEN}) option(FOREFIRE_NATIVE_ARCH "Optimise for the build machine's CPU (-march=native)" ${_ff_default_native}) option(FOREFIRE_BUILD_PYTHON "Build the pyforefire Python extension module" ${_ff_default_python}) option(FOREFIRE_STATIC_CORE "Build the ForeFire core as a static library" ${_ff_default_static}) @@ -270,6 +290,12 @@ if(FOREFIRE_WARNINGS_AS_ERRORS AND _ff_warning_flags) endif() endif() +if(EMSCRIPTEN) + # Emscripten defaults to -fno-exceptions; the command parser signals bad + # input by throwing, so every translation unit needs them enabled. + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fexceptions") +endif() + # ---------------------------------- # Output Directories # ---------------------------------- @@ -330,10 +356,14 @@ endif() # ---------------------------------- # Main Project Executable # ---------------------------------- -add_executable(forefire app/forefire/ForeFire.cpp app/forefire/AdvancedLineEditor.cpp) -target_link_libraries(forefire PRIVATE forefireL) -if(_ff_warning_flags) - target_compile_options(forefire PRIVATE ${_ff_warning_flags}) +# The shell is termios-driven and has no meaning in a browser, so a WASM build +# skips it and ships the embind module below instead. +if(FOREFIRE_BUILD_CLI) + add_executable(forefire app/forefire/ForeFire.cpp app/forefire/AdvancedLineEditor.cpp) + target_link_libraries(forefire PRIVATE forefireL) + if(_ff_warning_flags) + target_compile_options(forefire PRIVATE ${_ff_warning_flags}) + endif() endif() # ---------------------------------- @@ -344,6 +374,44 @@ if(FOREFIRE_BUILD_TESTS) add_subdirectory(tests/unit) endif() +# ---------------------------------- +# WebAssembly Module +# ---------------------------------- +if(FOREFIRE_BUILD_WASM) + add_executable(forefire_wasm bindings/wasm/forefire_wasm.cpp) + target_link_libraries(forefire_wasm PRIVATE forefireL) + # Two things are non-obvious here. embind refuses to compile below C++17, + # so this one translation unit moves up while the core stays on C++11 — + # both sit on the same libc++. And the output is an ES module, which Node + # only recognises from a .js file when a package.json says so, hence .mjs. + set_target_properties(forefire_wasm PROPERTIES + OUTPUT_NAME "forefire" + SUFFIX ".mjs" + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED ON) + target_link_options(forefire_wasm PRIVATE + "--bind" + # A single ES module plus its .wasm, so a static page can import it. + "-sMODULARIZE=1" + "-sEXPORT_ES6=1" + "-sEXPORT_NAME=createForeFire" + "-sENVIRONMENT=web,worker,node" + # The domain allocates its grids up front and can grow well past the + # 16 MB default; the fire domain sizes are not known at build time. + "-sALLOW_MEMORY_GROWTH=1" + "-sINITIAL_MEMORY=64MB" + "-sSTACK_SIZE=4MB" + # C++ exceptions are load-bearing here: BadOption and friends are how + # the command parser reports bad input. + "-fexceptions" + # There is no main(): the module is driven entirely through embind. + # FS stays exported so callers can stage fuels.csv and read back what + # print[] writes. + "-sEXPORTED_RUNTIME_METHODS=['FS']" + "-sFORCE_FILESYSTEM=1") + target_compile_options(forefire_wasm PRIVATE "-fexceptions") +endif() + # ---------------------------------- # Python Extension Module # ---------------------------------- @@ -386,7 +454,9 @@ if(NOT _ff_wheel_build) set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE") # Adjust as necessary # Specify installation directories - install(TARGETS forefire RUNTIME DESTINATION bin) + if(FOREFIRE_BUILD_CLI) + install(TARGETS forefire RUNTIME DESTINATION bin) + endif() if(NOT FOREFIRE_STATIC_CORE) # With a static core there is no libforefireL to install: it is linked # straight into the executables. diff --git a/bindings/wasm/README.md b/bindings/wasm/README.md new file mode 100644 index 00000000..57eb87c0 --- /dev/null +++ b/bindings/wasm/README.md @@ -0,0 +1,110 @@ +# ForeFire in WebAssembly + +Follow-up to [issue #171](https://github.com/forefireAPI/forefire/issues/171): +compile the engine to WebAssembly and run a simulation with no NetCDF, in Node +or in a browser tab. + +This is an experimental build, not a supported one yet. It answers the three +questions the issue left open: does it link, does it run, how big is it. + +`.github/workflows/wasm.yml` builds the module and runs `smoke.mjs` on every +pull request. The `.wasm` is built in CI rather than committed: it is a +megabyte of generated output, and a stale binary sitting next to live sources +is worse than a two minute build. + +## What made it possible + +`#include ` sat in `src/DataBroker.h`, and the `using namespace netCDF` +next to it pulled the dependency into 48 of the 58 files in `src/`. +`-DFOREFIRE_ENABLE_NETCDF=OFF` (#208) compiles that include out, along with +every code path behind it, and leaves a stub in each entry point that reports +the missing support. The command table is unchanged, so a script that reaches +for NetCDF gets a message instead of a link error. + +Nothing else needed touching. MPI was already behind `MPI_COUPLING`, the HTTP +server and `popen` are never reached from the WASM entry point, and `termios` +lives only in the CLI shell, which a WASM build does not compile. + +## Building + +Needs Emscripten. With the SDK image: + +```sh +podman run --rm -v "$PWD":/w:z -w /w docker.io/emscripten/emsdk:6.0.6 bash -lc ' + emcmake cmake -S . -B build-wasm -DCMAKE_BUILD_TYPE=Release && + cmake --build build-wasm -j8' +``` + +`emcmake` sets `EMSCRIPTEN`, which turns off NetCDF, MPI, the Python module, +the unit tests and the CLI shell, and turns on `forefire_wasm`. The outputs +land in `bin/`: + +| File | Size | gzip | brotli | +| --- | --- | --- | --- | +| `forefire.wasm` | 990 KB | 298 KB | 224 KB | +| `forefire.mjs` | 131 KB | 33 KB | — | + +Roughly 257 KB over the wire with brotli, for the whole engine and all its +propagation and flux models. + +## Running + +Headless, under Node: + +```sh +node bindings/wasm/smoke.mjs bin/forefire.mjs +``` + +## The API + +`forefire.mjs` is an ES module exporting a `createForeFire()` factory. It +mirrors the pybind11 module in `bindings/python`, with typed arrays in place of +NumPy arrays — see +[Running from NumPy arrays](../../docs/source/user_guide/python_arrays.rst) for +the concepts, which carry over unchanged. + +```js +import createForeFire from "./forefire.mjs"; + +const Module = await createForeFire(); +const ff = new Module.ForeFire(); + +ff.setString("propagationModel", "WindDriven"); +ff.execute("FireDomain[sw=(0,0,0);ne=(4000,4000,0);t=0]"); +ff.addLayer("propagation", "WindDriven", "propagationModel"); +ff.addIndexLayer("table", "fuel", 0, 0, 0, 4000, 4000, 0, 200, 200, 1, 1, fuelArray); +ff.execute("startFire[loc=(2000,2000,0.);t=0]"); +ff.execute("step[dt=30]"); +const front = ff.execute("print[]"); +``` + +The layer methods take the four dimensions explicitly — `nx, ny, nz, nt` — where +the NumPy binding reads them off the array's shape. Otherwise the contract is +identical: pass a flat C-order `(t, z, y, x)` array, indexed +`x + nx * (y + ny * (z + nz * t))`, exactly as `numpy.ndarray.ravel()` would +give you. The binding transposes it into the x-major order the data layers +index with, the same shuffle `_pyforefire.cpp` performs. + +## What was measured + +- **All 58 files in `src/` compile** under `em++` with + `FOREFIRE_ENABLE_NETCDF=OFF`. Zero errors. The only diagnostics are seven + `-Wvla-cxx-extension` warnings, the latent portability issue #171 already + flags. +- **It links and runs.** `smoke.mjs` runs a full 240 s simulation. +- **The answers match the Python binding.** `smoke.mjs` is a line-for-line port + of the worked example in the NumPy documentation. Run against a native + `pyforefire` built from the same tree, the two agree exactly: 349 front nodes, + x 1980..3905, y 1763..2308, the front stretched downwind as the doc describes. + +## Known limits + +- **Single-threaded.** Emscripten pthreads need `SharedArrayBuffer` and + COOP/COEP headers, which is exactly the deployment complexity a static page + is meant to avoid. Nothing in the engine's simulation path threads today — + only the HTTP server does, and it is not reachable here. +- **The embind translation unit is C++17**; the core stays C++11. embind + refuses to compile below C++17, and mixing is fine against one libc++. +- **No file I/O worth the name.** `FS` is exported so a caller can stage + `fuels.csv` or read back what `print[]` writes, but there is no landscape + file support at all — arrays are the only way in. diff --git a/bindings/wasm/forefire_wasm.cpp b/bindings/wasm/forefire_wasm.cpp new file mode 100644 index 00000000..dc403a1f --- /dev/null +++ b/bindings/wasm/forefire_wasm.cpp @@ -0,0 +1,226 @@ +/** + * @file forefire_wasm.cpp + * @brief Emscripten/embind entry point for the browser build. + * + * A spike for issue #171. The shape deliberately mirrors the pybind11 module + * in bindings/python: one Command per instance, commands driven as strings, + * gridded inputs handed over as typed arrays instead of NumPy arrays. + * + * Everything here assumes FF_NO_NETCDF, so there is no file-backed landscape + * loading: the caller builds the domain and its layers from JS. + */ + +#include +#include + +#include +#include +#include + +#include "Command.h" +#include "FireDomain.h" +#include "include/Version.h" + +using namespace libforefire; + +namespace { + +/*! \brief Copy a JS TypedArray into a contiguous C++ vector. */ +template +std::vector toVector(const emscripten::val &array) { + const size_t length = array["length"].as(); + std::vector out(length); + if (length == 0) return out; + // A view over the heap slice the vector already owns; the JS side does the + // copy, which avoids a per-element val round trip. + emscripten::val heap = emscripten::val(emscripten::typed_memory_view(length, out.data())); + heap.call("set", array); + return out; +} + +/*! \brief Transpose a (t,z,y,x) C-order buffer into the x-major order the data + * layers index with. + * + * XYZTDataLayer and FuelDataLayer read their values as + * `x*(ny*nz*nt) + y*(nz*nt) + z*nt + t`, not as the row-major layout a caller + * naturally builds. The pybind11 binding does this same shuffle before + * handing NumPy data over; skipping it silently transposes the field, which + * for a two-plane wind layer swaps the u and v responses and sends the fire + * off at ninety degrees to the wind. + */ +template +std::vector toLayerOrder(const std::vector &src, size_t nx, size_t ny, + size_t nz, size_t nt) { + std::vector out(src.size()); + for (size_t it = 0; it < nt; ++it) + for (size_t iz = 0; iz < nz; ++iz) + for (size_t iy = 0; iy < ny; ++iy) + for (size_t ix = 0; ix < nx; ++ix) { + const size_t from = ix + nx * (iy + ny * (iz + nz * it)); + const size_t to = ix * (ny * nz * nt) + iy * (nz * nt) + iz * nt + it; + out[to] = src[from]; + } + return out; +} + +class ForeFireWasm { + Command executor; + +public: + ForeFireWasm() : executor() {} + + /*! \brief Run one ForeFire command, returning whatever it printed. */ + std::string execute(const std::string &command) { + std::ostringstream captured; + executor.setOstringstream(&captured); + std::string cmd(command); + executor.ExecuteCommand(cmd); + return captured.str(); + } + + /*! \brief Current front geometry, in the shell's own dump format. */ + std::string dumpString() { return executor.dumpString(); } + + double getTime() { return executor.getTime(); } + + void setInt(const std::string &name, int value) { + executor.currentSession.params->setInt(name, value); + } + int getInt(const std::string &name) { + return executor.currentSession.params->getInt(name); + } + void setDouble(const std::string &name, double value) { + executor.currentSession.params->setDouble(name, value); + } + double getDouble(const std::string &name) { + return executor.currentSession.params->getDouble(name); + } + void setString(const std::string &name, const std::string &value) { + executor.currentSession.params->setParameter(name, value); + } + std::string getString(const std::string &name) { + return executor.currentSession.params->getParameter(name); + } + + /*! \brief Attach a model-backed layer, e.g. ("propagation", "WindDriven", + * "propagationModel"). Distinct from the addLayer *command*, which + * builds constant layers instead. */ + void addLayer(const std::string &type, const std::string &name, + const std::string &key) { + FireDomain *domain = executor.getDomain(); + if (domain == 0) return; + domain->addLayer(type, name, key); + } + + /*! \brief Register a continuous field (altitude, wind, moisture, ...). */ + bool addScalarLayer(const std::string &type, const std::string &name, + double x0, double y0, double t0, + double width, double height, double timespan, + int nx, int ny, int nz, int nt, + const emscripten::val &values) { + FireDomain *domain = executor.getDomain(); + if (domain == 0) return false; + std::vector data = toVector(values); + size_t nnx = nx, nny = ny, nnz = nz, nnt = nt; + if (data.size() != nnx * nny * nnz * nnt) return false; + data = toLayerOrder(data, nnx, nny, nnz, nnt); + // addScalarLayer keeps the pointer, so the layer needs storage that + // outlives this call; the domain owns it from here on. + double *owned = new double[data.size()]; + std::copy(data.begin(), data.end(), owned); + return domain->addScalarLayer(type, name, x0, y0, t0, width, height, + timespan, nnx, nny, nnz, nnt, owned); + } + + /*! \brief Register an index field (fuel map, flux model map). */ + bool addIndexLayer(const std::string &type, const std::string &name, + double x0, double y0, double t0, + double width, double height, double timespan, + int nx, int ny, int nz, int nt, + const emscripten::val &values) { + FireDomain *domain = executor.getDomain(); + if (domain == 0) return false; + std::vector data = toVector(values); + size_t nnx = nx, nny = ny, nnz = nz, nnt = nt; + if (data.size() != nnx * nny * nnz * nnt) return false; + data = toLayerOrder(data, nnx, nny, nnz, nnt); + int *owned = new int[data.size()]; + std::copy(data.begin(), data.end(), owned); + return domain->addIndexLayer(type, name, x0, y0, t0, width, height, + timespan, nnx, nny, nnz, nnt, owned); + } + + /*! \brief Read a layer back as {shape:[nt,nz,ny,nx], data:Float64Array}. */ + emscripten::val getDoubleArray(const std::string &name) { + FireDomain *domain = executor.getDomain(); + if (domain == 0) return emscripten::val::null(); + const double t = domain->getSimulationTime(); + + FFArray *src = 0; + FluxLayer *fluxLayer = domain->getFluxLayer(name); + if (fluxLayer != 0) { + fluxLayer->getMatrix(&src, t); + } else { + DataLayer *dataLayer = domain->getDataLayer(name); + if (dataLayer == 0) return emscripten::val::null(); + dataLayer->getMatrix(&src, t); + } + if (src == 0) return emscripten::val::null(); + + const size_t nnx = src->getDim("x"); + const size_t nny = src->getDim("y"); + const size_t nnz = src->getDim("z"); + const size_t nnt = src->getDim("t"); + const double *data = src->getData(); + + // Same Fortran-to-C reshuffle the NumPy binding does, so the JS view + // indexes as [t][z][y][x]. + std::vector reshaped(nnx * nny * nnz * nnt); + for (size_t it = 0; it < nnt; ++it) + for (size_t iz = 0; iz < nnz; ++iz) + for (size_t iy = 0; iy < nny; ++iy) + for (size_t ix = 0; ix < nnx; ++ix) { + const size_t cIndex = ix + nnx * (iy + nny * (iz + nnz * it)); + const size_t fIndex = it + nnt * (iz + nnz * (iy + nny * ix)); + reshaped[cIndex] = data[fIndex]; + } + + emscripten::val shape = emscripten::val::array(); + shape.call("push", nnt); + shape.call("push", nnz); + shape.call("push", nny); + shape.call("push", nnx); + + emscripten::val out = emscripten::val::object(); + out.set("shape", shape); + // slice() forces a copy out of the heap view, which would otherwise + // dangle the moment `reshaped` goes out of scope or the heap grows. + out.set("data", emscripten::val(emscripten::typed_memory_view( + reshaped.size(), reshaped.data())) + .call("slice")); + return out; + } +}; + +std::string version() { return std::string(ff_version); } + +} // namespace + +EMSCRIPTEN_BINDINGS(forefire) { + emscripten::function("version", &version); + emscripten::class_("ForeFire") + .constructor<>() + .function("execute", &ForeFireWasm::execute) + .function("dumpString", &ForeFireWasm::dumpString) + .function("getTime", &ForeFireWasm::getTime) + .function("setInt", &ForeFireWasm::setInt) + .function("getInt", &ForeFireWasm::getInt) + .function("setDouble", &ForeFireWasm::setDouble) + .function("getDouble", &ForeFireWasm::getDouble) + .function("setString", &ForeFireWasm::setString) + .function("getString", &ForeFireWasm::getString) + .function("addLayer", &ForeFireWasm::addLayer) + .function("addScalarLayer", &ForeFireWasm::addScalarLayer) + .function("addIndexLayer", &ForeFireWasm::addIndexLayer) + .function("getDoubleArray", &ForeFireWasm::getDoubleArray); +} diff --git a/bindings/wasm/smoke.mjs b/bindings/wasm/smoke.mjs new file mode 100644 index 00000000..0f449568 --- /dev/null +++ b/bindings/wasm/smoke.mjs @@ -0,0 +1,115 @@ +/** + * Smoke test for the WebAssembly build (issue #171). + * + * The JS twin of docs/source/user_guide/python_arrays.rst: a 4 km square + * domain, a uniform fuel map and a wind field, all built as typed arrays, with + * no NetCDF and no files. Run it with: + * + * node bindings/wasm/smoke.mjs path/to/forefire.mjs + */ + +import { pathToFileURL } from "node:url"; +import { resolve } from "node:path"; + +const modulePath = process.argv[2]; +if (!modulePath) { + console.error("usage: node smoke.mjs "); + process.exit(2); +} + +// Resolved against the working directory, the way a path typed on a command +// line is meant to be — not against this file, which would send +// `bin/forefire.mjs` looking inside bindings/wasm/. +const { default: createForeFire } = await import(pathToFileURL(resolve(modulePath)).href); + +const Module = await createForeFire(); +console.log("ForeFire version:", Module.version()); + +const ff = new Module.ForeFire(); + +// Fuel table inline: WindDriven only reads vv_coeff, Kcurv and beta. +ff.setString("fuelsTable", "Index;vv_coeff;Kcurv;beta\n1;1.0;1.0;1.0\n2;0.3;1.0;1.0"); +ff.setDouble("defaultFuelType", 1.0); + +const solver = { + spatialIncrement: 0.5, + minimalPropagativeFrontDepth: 10, + perimeterResolution: 10, + initialFrontDepth: 0.1, + relax: 1.0, + smoothing: 0, + minSpeed: 0.0, + bmapLayer: 1, + windReductionFactor: 1.0, +}; +for (const [key, value] of Object.entries(solver)) ff.setDouble(key, value); +ff.setString("propagationModel", "WindDriven"); + +const L = 4000.0; +console.log(ff.execute(`FireDomain[sw=(0,0,0);ne=(${L},${L},0);t=0]`)); + +const W = 200; +const H = 200; + +// Fuel index 1 everywhere. Shape (t=1, z=1, y=W, x=H), flattened C-order. +const fuel = new Int32Array(W * H).fill(1); + +// Wind layers are (t=1, z=2, y=W, x=H): plane 0 is the u-ward response, plane +// 1 the v-ward one, matching the NumPy example's windU/windV split. +const windU = new Float64Array(2 * W * H); +windU.fill(1.0, 0, W * H); +const windV = new Float64Array(2 * W * H); +windV.fill(1.0, W * H); + +ff.addLayer("propagation", "WindDriven", "propagationModel"); +console.log("fuel layer:", ff.addIndexLayer("table", "fuel", 0, 0, 0, L, L, 0, H, W, 1, 1, fuel)); +console.log("windU layer:", ff.addScalarLayer("windScalDir", "windU", 0, 0, 0, L, L, 0, H, W, 2, 1, windU)); +console.log("windV layer:", ff.addScalarLayer("windScalDir", "windV", 0, 0, 0, L, L, 0, H, W, 2, 1, windV)); + +ff.execute("startFire[loc=(2000,2000,0.);t=0]"); + +let t = 0; +for (let i = 0; i < 8; i++) { + ff.execute(`trigger[wind;loc=(0.,0.,0.);vel=(8,0,0);t=${t}]`); + ff.execute("step[dt=30]"); + t += 30; +} + +const out = ff.execute("print[]"); +console.log(`\nsimulated t = ${ff.getTime()} s`); + +// The print output is the shell's own front format: lines of "x, y, z" triples +// inside FireNode[...] entries. Pull the coordinates out to check the front +// actually moved downwind. +const coords = [...out.matchAll(/loc=\(([-\d.eE+]+),([-\d.eE+]+),/g)].map((m) => [ + parseFloat(m[1]), + parseFloat(m[2]), +]); + +if (coords.length === 0) { + console.error("no front nodes in print[] output:\n" + out.slice(0, 800)); + process.exit(1); +} + +const xs = coords.map((c) => c[0]); +const ys = coords.map((c) => c[1]); +console.log(`front nodes: ${coords.length}`); +console.log( + `x range: ${Math.min(...xs).toFixed(0)}..${Math.max(...xs).toFixed(0)} ` + + `y range: ${Math.min(...ys).toFixed(0)}..${Math.max(...ys).toFixed(0)}` +); + +// The wind blows along +x at 8 m/s for 240 s, so the front should be stretched +// well downwind and only modestly across it. Checking both axes catches a +// transposed layer, which otherwise looks like a perfectly healthy fire that +// happens to run at ninety degrees to the wind. +const spreadX = Math.max(...xs) - Math.min(...xs); +const spreadY = Math.max(...ys) - Math.min(...ys); +if (spreadX < 1000 || spreadX < 2 * spreadY) { + console.error( + `front did not run downwind: x spread ${spreadX.toFixed(0)} m, ` + + `y spread ${spreadY.toFixed(0)} m` + ); + process.exit(1); +} +console.log("\nOK");