/* 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 * @param {*} module * @param {Array} coords - An array of coordinate pairs */ export function storeCoords(module, coords) { const buffer = module._malloc(coords.length * 2 * 8) const heap = new Float64Array(module.HEAPF64.buffer, buffer, coords.length * 2) for (let i = 0; i < coords.length; i++) { heap[2*i] = coords[i][0] heap[2*i + 1] = coords[i][1] } return buffer } /** * Loads coordinates from the memory by the result pointer. * Frees the resultpointer and the result before returning * @param {*} module * @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength */ export function loadResultAndFreeMemory(module, result) { const [resultPointer, resultLength] = new Uint32Array(module.HEAPU32.buffer, result, 2) const simplified = new Float64Array(module.HEAPF64.buffer, resultPointer, resultLength) const coords = unflattenCoords(simplified) module._free(result) module._free(resultPointer) return coords } /** * Loads coordinates from the memory by the result pointer without freeing memory. * For benchmarking purposes * @param {*} module * @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength */ export function loadResult(module, result) { const [resultPointer, resultLength] = new Uint32Array(module.HEAPU32.buffer, result, 2) const simplified = new Float64Array(module.HEAPF64.buffer, resultPointer, resultLength) return unflattenCoords(simplified) } /** * Transforms a flat array to an array coordinate pairs * @param {Array} flattened - length must be even */ export function unflattenCoords (flattened) { const coords = [] let x, y for (let i = 0; i < flattened.length; i += 2) { x = flattened[i] y = flattened[i + 1] coords.push([x, y]) } return coords }