agglomerative-clustering 3.6.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,7 +16,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
16
16
  - **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
17
17
  - **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
18
18
  - **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
19
- - **Small and portable.** About 82 KB of WebAssembly (40 KB gzipped)<!-- bench/spikes/wasm-size/results-size.txt -->, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
19
+ - **Small and portable.** About 86 KB of WebAssembly (41 KB gzipped)<!-- bench/spikes/slicing-mapping/results-size.txt -->, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
20
20
 
21
21
  ## Install
22
22
 
@@ -1,3 +1,3 @@
1
1
  "use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
2
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
3
3
  ;return Module}module.exports=createWasmModule;
@@ -1,2 +1,2 @@
1
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
1
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
2
  ;return Module}export default createWasmModule;
Binary file
package/dist/index.cjs CHANGED
@@ -645,7 +645,8 @@ const check = k => {
645
645
  // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
646
646
  // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
647
647
  // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
648
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices (see clusterInSlices)
648
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
649
+ // (see clusterInSlices and mapInSlices)
649
650
  // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
650
651
  // indexed output also gives them their own entry, which counts towards k
651
652
 
@@ -662,7 +663,7 @@ const parseOptions = (options, allowed, image) => {
662
663
  options = (0, _shared.snapshot)(options);
663
664
  for (const key of Object.keys(options)) {
664
665
  if (!allowed.includes(key)) {
665
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal, checked before they start: for progress, map the image in strips of rows (https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#cancelling-or-showing-progress-while-mapping-a-large-image).' : '';
666
+ const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
666
667
  throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
667
668
  }
668
669
  }
@@ -740,9 +741,7 @@ const parseOptions = (options, allowed, image) => {
740
741
  const controlOptions = ['signal', 'onProgress'];
741
742
  const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
742
743
  const quantizeOptions = [...clusterOptions, 'dither', 'width'];
743
- // The functions that only map pixels take just `signal`, checked before they start: mapping runs in one piece (milliseconds
744
- // for a photo, seconds for a large image dithered; the guides show how to map in strips or cancel through a worker).
745
- const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
744
+ const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
746
745
  const quantizeIndexOptions = quantizeOptions;
747
746
  const mapIndexOptions = [...mapOptions, 'transparent'];
748
747
 
@@ -819,7 +818,7 @@ const call = (wasm, buffers, fn, precision) => {
819
818
  };
820
819
 
821
820
  // ----- Interruptible work -------------------------------------------------------------------------------------------
822
- // A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
821
+ // A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
823
822
  // event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
824
823
  // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
825
824
  // result is the same either way: the slices are the same steps in the same order.
@@ -868,6 +867,20 @@ const reporter = o => {
868
867
  };
869
868
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
870
869
 
870
+ // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
871
+ // the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
872
+ // Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
873
+ // 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
874
+ // about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
875
+ const mappingCost = [0.45, 0.37];
876
+ const clusteringShare = (o, k) => {
877
+ const dithered = o.dither > 0 && o.width > 0;
878
+ const ordered = dithered && o.ditherMethod === 2;
879
+ const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
880
+ const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
881
+ return 1 / (1 + cost);
882
+ };
883
+
871
884
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
872
885
  const clusterInSlices = async (wasm, image, o, report, share) => {
873
886
  checkAborted(o.signal);
@@ -911,6 +924,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
911
924
  }
912
925
  };
913
926
 
927
+ // Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
928
+ // `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
929
+ // clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
930
+ // finishes in its first slice doesn't yield.
931
+ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
932
+ checkAborted(o.signal);
933
+ const bytes = source.palette || source.clustering;
934
+ const imagePointer = allocate(wasm, image.data.length);
935
+ let sourcePointer = 0;
936
+ let job = 0;
937
+ let aborted = false;
938
+ try {
939
+ sourcePointer = allocate(wasm, bytes.length);
940
+ wasm.HEAPU8.set(image.data, imagePointer);
941
+ wasm.HEAPU8.set(bytes, sourcePointer);
942
+ const palette = source.palette ? sourcePointer : 0,
943
+ clustering = source.clustering ? sourcePointer : 0;
944
+ job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
945
+ if (!job) {
946
+ throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
947
+ }
948
+ // The job has its own copy of the palette, so the source can go now.
949
+ wasm._free(sourcePointer);
950
+ sourcePointer = 0;
951
+ report(from);
952
+ while (true) {
953
+ const progress = wasm._mapping_job_step(job, sliceMs);
954
+ if (progress >= 1000) {
955
+ break;
956
+ }
957
+ report(from + (1 - from) * progress / 1000);
958
+ await yieldNow();
959
+ checkAborted(o.signal);
960
+ }
961
+ const pointer = wasm._mapping_job_result(job);
962
+ try {
963
+ return unpack(wasm, pointer);
964
+ } finally {
965
+ wasm._free(pointer);
966
+ }
967
+ } catch (error) {
968
+ if (!isAbort(error)) {
969
+ throw error;
970
+ }
971
+ aborted = true;
972
+ discard(wasm);
973
+ throw outOfMemory(image.data.length, o.precision);
974
+ } finally {
975
+ if (!aborted) {
976
+ if (job) {
977
+ wasm._mapping_job_free(job);
978
+ }
979
+ if (sourcePointer) {
980
+ wasm._free(sourcePointer);
981
+ }
982
+ wasm._free(imagePointer);
983
+ retireIfLarge(wasm);
984
+ }
985
+ }
986
+ };
987
+
914
988
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
915
989
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
916
990
  // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
@@ -1093,9 +1167,12 @@ const quantize = async (image, k, options) => {
1093
1167
  const wasm = Module || (await acquire());
1094
1168
  if (isControlled(o)) {
1095
1169
  const report = reporter(o);
1096
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1097
- checkAborted(o.signal);
1098
- const mapped = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1170
+ const share = clusteringShare(o, k);
1171
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1172
+ const mapped = wrap(await mapInSlices(wasm, image, {
1173
+ clustering,
1174
+ k
1175
+ }, o.colorSpace, false, 0, o, report, share));
1099
1176
  report(1);
1100
1177
  return mapped;
1101
1178
  }
@@ -1114,6 +1191,15 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1114
1191
  const wasm = Module || (await acquire());
1115
1192
  checkAborted(o.signal);
1116
1193
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1194
+ if (isControlled(o)) {
1195
+ const report = reporter(o);
1196
+ const mapped = wrap(await mapInSlices(wasm, image, {
1197
+ clustering,
1198
+ k
1199
+ }, colorSpace, false, 0, o, report, 0));
1200
+ report(1);
1201
+ return mapped;
1202
+ }
1117
1203
  const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1118
1204
  return result;
1119
1205
  };
@@ -1130,6 +1216,14 @@ const quantizeWithPalette = async (image, palette, options) => {
1130
1216
  warn(o.signal);
1131
1217
  const wasm = Module || (await acquire());
1132
1218
  checkAborted(o.signal);
1219
+ if (isControlled(o)) {
1220
+ const report = reporter(o);
1221
+ const mapped = wrap(await mapInSlices(wasm, image, {
1222
+ palette
1223
+ }, space, false, 0, o, report, 0));
1224
+ report(1);
1225
+ return mapped;
1226
+ }
1133
1227
  const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1134
1228
  return result;
1135
1229
  };
@@ -1144,9 +1238,12 @@ const quantizeToIndices = async (image, k, options) => {
1144
1238
  const wasm = Module || (await acquire());
1145
1239
  if (isControlled(o)) {
1146
1240
  const report = reporter(o);
1147
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1148
- checkAborted(o.signal);
1149
- const indexed = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
1241
+ const share = clusteringShare(o, k);
1242
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1243
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1244
+ clustering,
1245
+ k
1246
+ }, o.colorSpace, true, o.transparent, o, report, share), original, (0, _shared.colorSpaceName)(o.colorSpace));
1150
1247
  report(1);
1151
1248
  return indexed;
1152
1249
  }
@@ -1168,6 +1265,15 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1168
1265
 
1169
1266
  // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1170
1267
  const cutoff = o.transparentGiven ? o.transparent : header.transparent;
1268
+ if (isControlled(o)) {
1269
+ const report = reporter(o);
1270
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1271
+ clustering,
1272
+ k
1273
+ }, colorSpace, true, cutoff, o, report, 0), original, (0, _shared.colorSpaceName)(header.colorSpace));
1274
+ report(1);
1275
+ return indexed;
1276
+ }
1171
1277
  const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, (0, _shared.colorSpaceName)(header.colorSpace));
1172
1278
  return result;
1173
1279
  };
@@ -1185,6 +1291,14 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1185
1291
  warn(o.signal);
1186
1292
  const wasm = Module || (await acquire());
1187
1293
  checkAborted(o.signal);
1294
+ if (isControlled(o)) {
1295
+ const report = reporter(o);
1296
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1297
+ palette
1298
+ }, space, true, o.transparent, o, report, 0), original, paletteSpace);
1299
+ report(1);
1300
+ return indexed;
1301
+ }
1188
1302
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1189
1303
  return result;
1190
1304
  };
package/dist/index.d.cts CHANGED
@@ -175,27 +175,25 @@ export type ColorSpace = 'rgb' | 'oklab';
175
175
  /** How pixel opacity affects clustering. */
176
176
  export type AlphaMode = 'weight' | 'ignore';
177
177
 
178
- /** Cancelling a call. Every function that takes an image has it. */
178
+ /** Cancelling a call: the base of `ProgressOptions`, which every function that takes an image has. */
179
179
  export interface CancelOptions {
180
180
  /**
181
- * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
182
- * signal between them, so an abort takes effect within a slice, not after the whole clustering. It rejects with
183
- * the signal's `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it
184
- * has the signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. On the functions
185
- * that only map pixels (`quantizeFromClustering`, `quantizeWithPalette` and their indexed forms) it is checked once,
186
- * before the call starts. Pixel mapping, which follows the clustering, can't be
187
- * interrupted (the guides show how to map a large image in strips, or cancel it through a worker). The call's result is the same as without a signal. In the worker entry the worker stops
188
- * working on a call that clusters, and a call still waiting its turn never starts; a mapping already running finishes.
181
+ * Cancels the call. A call given a `signal` clusters and maps in slices of about 10 ms and checks the signal
182
+ * between them, so an abort takes effect within a slice, not after the whole call. It rejects with the signal's
183
+ * `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it has the
184
+ * signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. The call's result is the
185
+ * same as without a signal. In the worker entry the worker stops working on the call too, and a call still waiting
186
+ * its turn never starts.
189
187
  */
190
188
  signal?: AbortSignal | undefined;
191
189
  }
192
190
 
193
- /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
191
+ /** Cancelling a long call and watching its progress, for every function that takes an image. Both are optional and can be used apart. */
194
192
  export interface ProgressOptions extends CancelOptions {
195
193
  /**
196
- * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
197
- * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
198
- * slices, so other tasks (such as painting) get a turn while it works.
194
+ * Called with the fraction done, from 0 to 1, as the call runs: between slices (about every 10 ms; a small image
195
+ * may report only 0 and 1), never going backwards, ending with 1. It is approximate and not linear in time. Giving
196
+ * it also makes the call run in slices, so other tasks (such as painting) get a turn while it works.
199
197
  */
200
198
  onProgress?: ((progress: number) => void) | undefined;
201
199
  }
@@ -257,8 +255,8 @@ export type DitherOptions =
257
255
  | { method?: 'floyd-steinberg' | 'atkinson' | undefined; strength?: number | undefined; steps?: undefined }
258
256
  | { method: 'ordered'; strength?: number | undefined; steps?: DitherSteps | undefined };
259
257
 
260
- /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. They take `signal` (checked before mapping starts) but no `onProgress`: mapping runs in one piece. */
261
- export interface MappingOptions extends CancelOptions {
258
+ /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. With `signal` or `onProgress`, mapping runs in slices, as clustering does. */
259
+ export interface MappingOptions extends ProgressOptions {
262
260
  /**
263
261
  * The space pixels are matched to their nearest palette colour in. The default is the space the colours were made in:
264
262
  * the clustering's in `quantizeFromClustering`, a `Palette`'s own in `quantizeWithPalette` and
package/dist/index.d.ts CHANGED
@@ -175,27 +175,25 @@ export type ColorSpace = 'rgb' | 'oklab';
175
175
  /** How pixel opacity affects clustering. */
176
176
  export type AlphaMode = 'weight' | 'ignore';
177
177
 
178
- /** Cancelling a call. Every function that takes an image has it. */
178
+ /** Cancelling a call: the base of `ProgressOptions`, which every function that takes an image has. */
179
179
  export interface CancelOptions {
180
180
  /**
181
- * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
182
- * signal between them, so an abort takes effect within a slice, not after the whole clustering. It rejects with
183
- * the signal's `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it
184
- * has the signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. On the functions
185
- * that only map pixels (`quantizeFromClustering`, `quantizeWithPalette` and their indexed forms) it is checked once,
186
- * before the call starts. Pixel mapping, which follows the clustering, can't be
187
- * interrupted (the guides show how to map a large image in strips, or cancel it through a worker). The call's result is the same as without a signal. In the worker entry the worker stops
188
- * working on a call that clusters, and a call still waiting its turn never starts; a mapping already running finishes.
181
+ * Cancels the call. A call given a `signal` clusters and maps in slices of about 10 ms and checks the signal
182
+ * between them, so an abort takes effect within a slice, not after the whole call. It rejects with the signal's
183
+ * `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it has the
184
+ * signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. The call's result is the
185
+ * same as without a signal. In the worker entry the worker stops working on the call too, and a call still waiting
186
+ * its turn never starts.
189
187
  */
190
188
  signal?: AbortSignal | undefined;
191
189
  }
192
190
 
193
- /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
191
+ /** Cancelling a long call and watching its progress, for every function that takes an image. Both are optional and can be used apart. */
194
192
  export interface ProgressOptions extends CancelOptions {
195
193
  /**
196
- * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
197
- * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
198
- * slices, so other tasks (such as painting) get a turn while it works.
194
+ * Called with the fraction done, from 0 to 1, as the call runs: between slices (about every 10 ms; a small image
195
+ * may report only 0 and 1), never going backwards, ending with 1. It is approximate and not linear in time. Giving
196
+ * it also makes the call run in slices, so other tasks (such as painting) get a turn while it works.
199
197
  */
200
198
  onProgress?: ((progress: number) => void) | undefined;
201
199
  }
@@ -257,8 +255,8 @@ export type DitherOptions =
257
255
  | { method?: 'floyd-steinberg' | 'atkinson' | undefined; strength?: number | undefined; steps?: undefined }
258
256
  | { method: 'ordered'; strength?: number | undefined; steps?: DitherSteps | undefined };
259
257
 
260
- /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. They take `signal` (checked before mapping starts) but no `onProgress`: mapping runs in one piece. */
261
- export interface MappingOptions extends CancelOptions {
258
+ /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. With `signal` or `onProgress`, mapping runs in slices, as clustering does. */
259
+ export interface MappingOptions extends ProgressOptions {
262
260
  /**
263
261
  * The space pixels are matched to their nearest palette colour in. The default is the space the colours were made in:
264
262
  * the clustering's in `quantizeFromClustering`, a `Palette`'s own in `quantizeWithPalette` and
package/dist/index.mjs CHANGED
@@ -569,7 +569,8 @@ const check = k => {
569
569
  // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
570
570
  // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
571
571
  // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
572
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices (see clusterInSlices)
572
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
573
+ // (see clusterInSlices and mapInSlices)
573
574
  // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
574
575
  // indexed output also gives them their own entry, which counts towards k
575
576
 
@@ -586,7 +587,7 @@ const parseOptions = (options, allowed, image) => {
586
587
  options = snapshot(options);
587
588
  for (const key of Object.keys(options)) {
588
589
  if (!allowed.includes(key)) {
589
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal, checked before they start: for progress, map the image in strips of rows (https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#cancelling-or-showing-progress-while-mapping-a-large-image).' : '';
590
+ const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
590
591
  throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
591
592
  }
592
593
  }
@@ -664,9 +665,7 @@ const parseOptions = (options, allowed, image) => {
664
665
  const controlOptions = ['signal', 'onProgress'];
665
666
  const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
666
667
  const quantizeOptions = [...clusterOptions, 'dither', 'width'];
667
- // The functions that only map pixels take just `signal`, checked before they start: mapping runs in one piece (milliseconds
668
- // for a photo, seconds for a large image dithered; the guides show how to map in strips or cancel through a worker).
669
- const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
668
+ const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
670
669
  const quantizeIndexOptions = quantizeOptions;
671
670
  const mapIndexOptions = [...mapOptions, 'transparent'];
672
671
 
@@ -743,7 +742,7 @@ const call = (wasm, buffers, fn, precision) => {
743
742
  };
744
743
 
745
744
  // ----- Interruptible work -------------------------------------------------------------------------------------------
746
- // A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
745
+ // A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
747
746
  // event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
748
747
  // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
749
748
  // result is the same either way: the slices are the same steps in the same order.
@@ -792,6 +791,20 @@ const reporter = o => {
792
791
  };
793
792
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
794
793
 
794
+ // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
795
+ // the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
796
+ // Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
797
+ // 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
798
+ // about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
799
+ const mappingCost = [0.45, 0.37];
800
+ const clusteringShare = (o, k) => {
801
+ const dithered = o.dither > 0 && o.width > 0;
802
+ const ordered = dithered && o.ditherMethod === 2;
803
+ const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
804
+ const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
805
+ return 1 / (1 + cost);
806
+ };
807
+
795
808
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
796
809
  const clusterInSlices = async (wasm, image, o, report, share) => {
797
810
  checkAborted(o.signal);
@@ -835,6 +848,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
835
848
  }
836
849
  };
837
850
 
851
+ // Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
852
+ // `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
853
+ // clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
854
+ // finishes in its first slice doesn't yield.
855
+ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
856
+ checkAborted(o.signal);
857
+ const bytes = source.palette || source.clustering;
858
+ const imagePointer = allocate(wasm, image.data.length);
859
+ let sourcePointer = 0;
860
+ let job = 0;
861
+ let aborted = false;
862
+ try {
863
+ sourcePointer = allocate(wasm, bytes.length);
864
+ wasm.HEAPU8.set(image.data, imagePointer);
865
+ wasm.HEAPU8.set(bytes, sourcePointer);
866
+ const palette = source.palette ? sourcePointer : 0,
867
+ clustering = source.clustering ? sourcePointer : 0;
868
+ job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
869
+ if (!job) {
870
+ throw fail('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
871
+ }
872
+ // The job has its own copy of the palette, so the source can go now.
873
+ wasm._free(sourcePointer);
874
+ sourcePointer = 0;
875
+ report(from);
876
+ while (true) {
877
+ const progress = wasm._mapping_job_step(job, sliceMs);
878
+ if (progress >= 1000) {
879
+ break;
880
+ }
881
+ report(from + (1 - from) * progress / 1000);
882
+ await yieldNow();
883
+ checkAborted(o.signal);
884
+ }
885
+ const pointer = wasm._mapping_job_result(job);
886
+ try {
887
+ return unpack(wasm, pointer);
888
+ } finally {
889
+ wasm._free(pointer);
890
+ }
891
+ } catch (error) {
892
+ if (!isAbort(error)) {
893
+ throw error;
894
+ }
895
+ aborted = true;
896
+ discard(wasm);
897
+ throw outOfMemory(image.data.length, o.precision);
898
+ } finally {
899
+ if (!aborted) {
900
+ if (job) {
901
+ wasm._mapping_job_free(job);
902
+ }
903
+ if (sourcePointer) {
904
+ wasm._free(sourcePointer);
905
+ }
906
+ wasm._free(imagePointer);
907
+ retireIfLarge(wasm);
908
+ }
909
+ }
910
+ };
911
+
838
912
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
839
913
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
840
914
  // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
@@ -1011,9 +1085,12 @@ export const quantize = async (image, k, options) => {
1011
1085
  const wasm = Module || (await acquire());
1012
1086
  if (isControlled(o)) {
1013
1087
  const report = reporter(o);
1014
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1015
- checkAborted(o.signal);
1016
- const mapped = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1088
+ const share = clusteringShare(o, k);
1089
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1090
+ const mapped = wrap(await mapInSlices(wasm, image, {
1091
+ clustering,
1092
+ k
1093
+ }, o.colorSpace, false, 0, o, report, share));
1017
1094
  report(1);
1018
1095
  return mapped;
1019
1096
  }
@@ -1031,6 +1108,15 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
1031
1108
  const wasm = Module || (await acquire());
1032
1109
  checkAborted(o.signal);
1033
1110
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1111
+ if (isControlled(o)) {
1112
+ const report = reporter(o);
1113
+ const mapped = wrap(await mapInSlices(wasm, image, {
1114
+ clustering,
1115
+ k
1116
+ }, colorSpace, false, 0, o, report, 0));
1117
+ report(1);
1118
+ return mapped;
1119
+ }
1034
1120
  const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1035
1121
  return result;
1036
1122
  };
@@ -1046,6 +1132,14 @@ export const quantizeWithPalette = async (image, palette, options) => {
1046
1132
  warn(o.signal);
1047
1133
  const wasm = Module || (await acquire());
1048
1134
  checkAborted(o.signal);
1135
+ if (isControlled(o)) {
1136
+ const report = reporter(o);
1137
+ const mapped = wrap(await mapInSlices(wasm, image, {
1138
+ palette
1139
+ }, space, false, 0, o, report, 0));
1140
+ report(1);
1141
+ return mapped;
1142
+ }
1049
1143
  const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1050
1144
  return result;
1051
1145
  };
@@ -1059,9 +1153,12 @@ export const quantizeToIndices = async (image, k, options) => {
1059
1153
  const wasm = Module || (await acquire());
1060
1154
  if (isControlled(o)) {
1061
1155
  const report = reporter(o);
1062
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1063
- checkAborted(o.signal);
1064
- const indexed = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, colorSpaceName(o.colorSpace));
1156
+ const share = clusteringShare(o, k);
1157
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1158
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1159
+ clustering,
1160
+ k
1161
+ }, o.colorSpace, true, o.transparent, o, report, share), original, colorSpaceName(o.colorSpace));
1065
1162
  report(1);
1066
1163
  return indexed;
1067
1164
  }
@@ -1082,6 +1179,15 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
1082
1179
 
1083
1180
  // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1084
1181
  const cutoff = o.transparentGiven ? o.transparent : header.transparent;
1182
+ if (isControlled(o)) {
1183
+ const report = reporter(o);
1184
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1185
+ clustering,
1186
+ k
1187
+ }, colorSpace, true, cutoff, o, report, 0), original, colorSpaceName(header.colorSpace));
1188
+ report(1);
1189
+ return indexed;
1190
+ }
1085
1191
  const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, colorSpaceName(header.colorSpace));
1086
1192
  return result;
1087
1193
  };
@@ -1098,6 +1204,14 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1098
1204
  warn(o.signal);
1099
1205
  const wasm = Module || (await acquire());
1100
1206
  checkAborted(o.signal);
1207
+ if (isControlled(o)) {
1208
+ const report = reporter(o);
1209
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1210
+ palette
1211
+ }, space, true, o.transparent, o, report, 0), original, paletteSpace);
1212
+ report(1);
1213
+ return indexed;
1214
+ }
1101
1215
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1102
1216
  return result;
1103
1217
  };
package/dist/shared.cjs CHANGED
@@ -13,7 +13,7 @@ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat
13
13
 
14
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
15
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
16
- const version = exports.version = '3.6.0';
16
+ const version = exports.version = '3.7.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.6.0';
7
+ export const version = '3.7.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -129,8 +129,8 @@ const respond = async ({
129
129
  }, post) => {
130
130
  const controller = check ? alreadyAborted() : controllers.get(id);
131
131
  try {
132
- // The call before this one may have run in one piece (mapping does), with no turn of the event loop for a cancel
133
- // of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
132
+ // The call before this one may have run in one piece (a call without a signal does), with no turn of the event
133
+ // loop for a cancel of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
134
134
  if (controller && !controller.signal.aborted) {
135
135
  await nextTurn();
136
136
  }
package/dist/worker.cjs CHANGED
@@ -471,7 +471,7 @@ const initOptions = (options, allowScript) => {
471
471
 
472
472
  // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
473
473
  // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
474
- const takeControls = (options, progressAllowed = true, ditherAllowed = true) => {
474
+ const takeControls = (options, ditherAllowed = true) => {
475
475
  // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
476
476
  // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
477
477
  if (!(0, _shared.isOptionsObject)(options)) {
@@ -504,7 +504,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
504
504
  options.dither = copy;
505
505
  }
506
506
  // The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
507
- // A wrong one (or a callback where only a signal is taken) crosses as `null` instead, which the worker's validation
507
+ // A wrong one crosses as `null` instead, which the worker's validation
508
508
  // rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
509
509
  // those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
510
510
  const {
@@ -512,7 +512,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
512
512
  onProgress
513
513
  } = options;
514
514
  const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
515
- const badProgress = onProgress !== undefined && (!progressAllowed || typeof onProgress !== 'function');
515
+ const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
516
516
  const {
517
517
  signal: _signal,
518
518
  onProgress: _onProgress,
@@ -577,10 +577,8 @@ const optionsPosition = {
577
577
  const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
578
578
  const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
579
579
  const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
580
- // These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
581
580
  // The functions that only cluster, and so take no dither option.
582
581
  const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
583
- const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
584
582
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
585
583
 
586
584
  // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
@@ -888,7 +886,7 @@ const makeWorker = (options, allowScript) => {
888
886
  options,
889
887
  signal,
890
888
  onProgress
891
- } = takeControls(rest[position], !mappingOnlyFunctions.includes(name), !clusteringOnlyFunctions.includes(name));
889
+ } = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
892
890
  let args = rest.slice();
893
891
  if (position < args.length) {
894
892
  args[position] = options;
@@ -968,7 +966,7 @@ const makeWorker = (options, allowScript) => {
968
966
  options,
969
967
  signal,
970
968
  onProgress
971
- } = takeControls(clusterOptions, true, false);
969
+ } = takeControls(clusterOptions, false);
972
970
  if (signal && signal.aborted) {
973
971
  throw abortReason(signal);
974
972
  }
@@ -1011,7 +1009,7 @@ const makeWorker = (options, allowScript) => {
1011
1009
  const withControls = (method, leading, mapOptions) => {
1012
1010
  let taken;
1013
1011
  try {
1014
- taken = takeControls(mapOptions, false);
1012
+ taken = takeControls(mapOptions);
1015
1013
  } catch (error) {
1016
1014
  return Promise.reject(error);
1017
1015
  }
package/dist/worker.mjs CHANGED
@@ -402,7 +402,7 @@ const initOptions = (options, allowScript) => {
402
402
 
403
403
  // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
404
404
  // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
405
- const takeControls = (options, progressAllowed = true, ditherAllowed = true) => {
405
+ const takeControls = (options, ditherAllowed = true) => {
406
406
  // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
407
407
  // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
408
408
  if (!isOptionsObject(options)) {
@@ -435,7 +435,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
435
435
  options.dither = copy;
436
436
  }
437
437
  // The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
438
- // A wrong one (or a callback where only a signal is taken) crosses as `null` instead, which the worker's validation
438
+ // A wrong one crosses as `null` instead, which the worker's validation
439
439
  // rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
440
440
  // those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
441
441
  const {
@@ -443,7 +443,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
443
443
  onProgress
444
444
  } = options;
445
445
  const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
446
- const badProgress = onProgress !== undefined && (!progressAllowed || typeof onProgress !== 'function');
446
+ const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
447
447
  const {
448
448
  signal: _signal,
449
449
  onProgress: _onProgress,
@@ -508,10 +508,8 @@ const optionsPosition = {
508
508
  const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
509
509
  const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
510
510
  const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
511
- // These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
512
511
  // The functions that only cluster, and so take no dither option.
513
512
  const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
514
- const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
515
513
  const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
516
514
 
517
515
  // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
@@ -819,7 +817,7 @@ const makeWorker = (options, allowScript) => {
819
817
  options,
820
818
  signal,
821
819
  onProgress
822
- } = takeControls(rest[position], !mappingOnlyFunctions.includes(name), !clusteringOnlyFunctions.includes(name));
820
+ } = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
823
821
  let args = rest.slice();
824
822
  if (position < args.length) {
825
823
  args[position] = options;
@@ -899,7 +897,7 @@ const makeWorker = (options, allowScript) => {
899
897
  options,
900
898
  signal,
901
899
  onProgress
902
- } = takeControls(clusterOptions, true, false);
900
+ } = takeControls(clusterOptions, false);
903
901
  if (signal && signal.aborted) {
904
902
  throw abortReason(signal);
905
903
  }
@@ -942,7 +940,7 @@ const makeWorker = (options, allowScript) => {
942
940
  const withControls = (method, leading, mapOptions) => {
943
941
  let taken;
944
942
  try {
945
- taken = takeControls(mapOptions, false);
943
+ taken = takeControls(mapOptions);
946
944
  } catch (error) {
947
945
  return Promise.reject(error);
948
946
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.6.0",
3
+ "version": "3.7.0",
4
4
  "description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
5
5
  "license": "MIT",
6
6
  "author": "Rohan Fredriksson",
@@ -81,7 +81,7 @@
81
81
  "README.md"
82
82
  ],
83
83
  "scripts": {
84
- "build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_get_palette','_get_palette_from_clustering','_get_palette_weights','_quantize','_quantize_with_clustering','_quantize_with_palette','_quantize_indices','_quantize_indices_with_clustering','_quantize_indices_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
84
+ "build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_mapping_job_start','_mapping_job_step','_mapping_job_result','_mapping_job_free','_get_palette','_get_palette_from_clustering','_get_palette_weights','_quantize','_quantize_with_clustering','_quantize_with_palette','_quantize_indices','_quantize_indices_with_clustering','_quantize_indices_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
85
85
  "build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker-thread.js\" --out-file-extension .cjs && node scripts/patch-cjs.mjs",
86
86
  "build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
87
87
  "build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts'); fs.writeFileSync('dist/worker.d.cts', fs.readFileSync('src/worker.d.ts', 'utf8').replaceAll(\\\"'./index.js'\\\", \\\"'./index.cjs'\\\"));\"",