From b7cb925178d54cabe2ebb9eaee71ad3ca401ce2a Mon Sep 17 00:00:00 2001 From: David Altenburg Date: Tue, 24 Jun 2025 13:43:05 -0700 Subject: [PATCH] Fix WebAssembly module initialization in worker.js - Update worker.js to properly initialize the modularized WebAssembly module - Use createSimplifyModule() instead of expecting a global Module object - Make prepare_and_simplify and simplify functions async to handle initialization - Add EXPORTED_RUNTIME_METHODS to Makefile to export HEAPU8 and HEAPU32 This fixes the "Module._malloc is not a function" error that occurred because the WebAssembly module is built with MODULARIZE=1 flag. --- Makefile | 1 + worker.js | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index f3b6921..c3906b1 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ CXX := Main.cpp O3 := -O3 WASM := -s NO_FILESYSTEM=1 -s ALLOW_MEMORY_GROWTH=1 -s WASM=1 \ -s EXPORTED_FUNCTIONS='["_simplify", "_malloc", "_free"]' \ + -s EXPORTED_RUNTIME_METHODS='["HEAPU8", "HEAPU32"]' \ -s ENVIRONMENT='web,worker' \ -s MODULARIZE=1 \ -s EXPORT_ES6=0 \ diff --git a/worker.js b/worker.js index a098903..bfa8f20 100644 --- a/worker.js +++ b/worker.js @@ -2,20 +2,28 @@ self.addEventListener('message', function(e) { prepare_and_simplify(e.data.blob, e.data.percentage); }, false); -var Module = {} // imported script installs functions on `Module` +var Module = null; self.importScripts("Fast-Quadric-Mesh-Simplification.js"); -function prepare_and_simplify(file, percentage) { +async function initializeModule() { + if (!Module) { + Module = await createSimplifyModule(); + } + return Module; +} + +async function prepare_and_simplify(file, percentage) { + await initializeModule(); var fr = new FileReader(); fr.readAsArrayBuffer(file); - fr.onloadend = function () { - const outputData = simplify(new Uint8Array(fr.result), percentage); + fr.onloadend = async function () { + const outputData = await simplify(new Uint8Array(fr.result), percentage); let file = new Blob([outputData], {type: 'application/sla'}); self.postMessage({"blob":file}); } } -function simplify(inputArray, percentage) { +async function simplify(inputArray, percentage) { // Allocate memory for the input buffer and copy the data const inputPtr = Module._malloc(inputArray.byteLength); Module.HEAPU8.set(inputArray, inputPtr);