diff --git a/index.js b/index.js index 31124d4..a68ec59 100644 --- a/index.js +++ b/index.js @@ -70,39 +70,40 @@ if (typeof Module === 'undefined') { var Module = {}; } -Module["instantiateWasm"] = function(imports, receiveInstance) { - console.log("쪼개진 WASM 파일(aa, ab, ac) 다운로드 및 병합 시작..."); +// 🌟 핵심 수정: 웹 워커(Worker) 환경이 아닐 때만 실행하도록 분기 처리 +if (typeof importScripts === 'undefined') { + Module["instantiateWasm"] = function(imports, receiveInstance) { + console.log("메인 스레드: 쪼개진 WASM 파일(aa, ab, ac) 다운로드 및 병합 시작..."); - Promise.all([ - fetch('index.wasm.part-aa').then(res => res.arrayBuffer()), - fetch('index.wasm.part-ab').then(res => res.arrayBuffer()), - fetch('index.wasm.part-ac').then(res => res.arrayBuffer()) - ]).then(buffers => { - // 1. 총 용량 계산해서 빈 도화지 만들기 - const totalLength = buffers.reduce((sum, buf) => sum + buf.byteLength, 0); - const combined = new Uint8Array(totalLength); + Promise.all([ + fetch('index.wasm.part-aa').then(res => res.arrayBuffer()), + fetch('index.wasm.part-ab').then(res => res.arrayBuffer()), + fetch('index.wasm.part-ac').then(res => res.arrayBuffer()) + ]).then(buffers => { + const totalLength = buffers.reduce((sum, buf) => sum + buf.byteLength, 0); + const combined = new Uint8Array(totalLength); - // 2. 조각들을 순서대로 이어 붙이기 - let offset = 0; - for (const buf of buffers) { - combined.set(new Uint8Array(buf), offset); - offset += buf.byteLength; - } + let offset = 0; + for (const buf of buffers) { + combined.set(new Uint8Array(buf), offset); + offset += buf.byteLength; + } - console.log("WASM 병합 완료! WebAssembly 컴파일 시작..."); + console.log("WASM 병합 완료! WebAssembly 컴파일 시작..."); - // 3. 합쳐진 데이터를 WebAssembly로 컴파일 - return WebAssembly.instantiate(combined, imports); - }).then(instance => { - // 4. Emscripten 엔진에 실행 인스턴스 넘겨주기 - receiveInstance(instance.instance, instance.module); - }).catch(err => { - console.error("WASM 다운로드 또는 병합 중 치명적 오류 발생:", err); - }); + return WebAssembly.instantiate(combined, imports); + }).then(instance => { + // 컴파일된 모듈(instance.module)을 Emscripten에 넘겨주면, 엔진이 알아서 워커들에게 공유합니다. + receiveInstance(instance.instance, instance.module); + }).catch(err => { + console.error("WASM 다운로드 또는 병합 중 치명적 오류 발생:", err); + }); - // Emscripten에게 우리가 비동기로 직접 로딩할 것이라고 알려줌 - return {}; -}; + return {}; + }; +} else { + console.log("워커 스레드 초기화됨 (메인 스레드가 넘겨주는 WASM을 대기합니다)"); +} // --- 여기까지 추가 --- // Determine the runtime environment we are in. You can customize this by