mt-polygon-simplification/lib/wasm-util/coordinates.js

80 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2019-07-14 20:37:26 +02:00
/*
Utility functions to store and load coordinates to and from module memory
Coordinates are assumed to be an array of coordinate pairs ([[x1,y1], [x2,y2], [x3,y3]])
*/
/**
* Allocate memory for coordinates and stores them in a flat representation.
* Returns a pointer to the buffer. The length of the buffer is coords.length * 2
2019-07-15 09:57:53 +02:00
* @param {*} module
2019-07-14 20:37:26 +02:00
* @param {Array} coords - An array of coordinate pairs
*/
export function storeCoords(module, coords) {
2019-07-15 09:57:53 +02:00
const flatSize = coords.length * 2
const offset = module._malloc(flatSize * Float64Array.BYTES_PER_ELEMENT)
const heapView = new Float64Array(module.HEAPF64.buffer, offset, flatSize)
2019-07-14 20:37:26 +02:00
for (let i = 0; i < coords.length; i++) {
2019-07-15 09:57:53 +02:00
heapView[2 * i] = coords[i][0]
heapView[2 * i + 1] = coords[i][1]
2019-07-14 20:37:26 +02:00
}
2019-07-15 09:57:53 +02:00
return offset
2019-07-14 20:37:26 +02:00
}
/**
* Loads coordinates from the memory by the result pointer.
* Frees the resultpointer and the result before returning
2019-07-15 09:57:53 +02:00
* @param {*} module
2019-07-14 20:37:26 +02:00
* @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength
*/
2019-07-16 17:31:20 +02:00
export function loadResultAndFreeMemory(module, resultInfo) {
2019-07-15 09:57:53 +02:00
const [resultPointer, resultLength] = new Uint32Array(
module.HEAPU32.buffer,
2019-07-16 17:31:20 +02:00
resultInfo,
2019-07-15 09:57:53 +02:00
2
)
const simplified = new Float64Array(
module.HEAPF64.buffer,
resultPointer,
resultLength
)
2019-07-14 20:37:26 +02:00
const coords = unflattenCoords(simplified)
2019-07-16 17:31:20 +02:00
module._free(resultInfo)
2019-07-14 20:37:26 +02:00
module._free(resultPointer)
return coords
}
/**
* Loads coordinates from the memory by the result pointer without freeing memory.
* For benchmarking purposes
2019-07-15 09:57:53 +02:00
* @param {*} module
2019-07-14 20:37:26 +02:00
* @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength
*/
export function loadResult(module, result) {
2019-07-15 09:57:53 +02:00
const [resultPointer, resultLength] = new Uint32Array(
module.HEAPU32.buffer,
result,
2
)
const simplified = new Float64Array(
module.HEAPF64.buffer,
resultPointer,
resultLength
)
2019-07-14 20:37:26 +02:00
return unflattenCoords(simplified)
}
/**
* Transforms a flat array to an array coordinate pairs
* @param {Array} flattened - length must be even
*/
2019-07-15 09:57:53 +02:00
export function unflattenCoords(flattened) {
2019-07-14 20:37:26 +02:00
const coords = []
let x, y
for (let i = 0; i < flattened.length; i += 2) {
2019-07-15 09:57:53 +02:00
x = flattened[i]
y = flattened[i + 1]
coords.push([x, y])
2019-07-14 20:37:26 +02:00
}
return coords
}