Skip to content

Instantly share code, notes, and snippets.

@lardratboy
Last active November 11, 2024 23:55
Show Gist options
  • Save lardratboy/28eca6f89926353553f5b1a3aed68f22 to your computer and use it in GitHub Desktop.
Save lardratboy/28eca6f89926353553f5b1a3aed68f22 to your computer and use it in GitHub Desktop.
Asked claude.ai for a wrapper around the DataView class - results were interesting
// Data type ranges and normalization functions
const DATA_RANGES = {
'int8': [-128, 127],
'uint8': [0, 255],
'int16': [-32768, 32767],
'uint16': [0, 65535],
'int32': [-2147483648, 2147483647],
'uint32': [0, 4294967295],
};
const TYPE_SIZES = {
'int8': 1, 'uint8': 1,
'int16': 2, 'uint16': 2,
'int32': 4, 'uint32': 4,
};
const GET_METHODS = {
'int8': 'getInt8',
'uint8': 'getUint8',
'int16': 'getInt16',
'uint16': 'getUint16',
'int32': 'getInt32',
'uint32': 'getUint32',
};
// Create normalization functions for each data type
const createNormalizer = (dataType) => {
const [min, max] = DATA_RANGES[dataType];
const oorange = 2 / (max - min);
return value => ((value - min) * oorange) - 1;
};
// Create a data reader function for specific type and endianness
const createDataReader = (view, dataType, isLittleEndian) => {
const method = GET_METHODS[dataType];
const fn = view[method].bind(view);
return offset => fn(offset, isLittleEndian);
};
function processDataAs(buffer, dataType, isLittleEndian) {
const view = new DataView(buffer);
const points = [];
const colors = [];
const typeSize = TYPE_SIZES[dataType];
const maxTuples = Math.floor(buffer.byteLength / (typeSize * 3));
// Create optimized functions outside the loop
const normalize = createNormalizer(dataType);
const readData = createDataReader(view, dataType, isLittleEndian);
let baseOffset = 0;
try {
for (let i = 0; i < maxTuples; i++) {
// Read and normalize coordinates
const x = normalize(readData(baseOffset)); baseOffset += typeSize;
const y = normalize(readData(baseOffset)); baseOffset += typeSize;
const z = normalize(readData(baseOffset)); baseOffset += typeSize;
points.push(x, y, z);
colors.push( (x+1)/2, (y+1)/2, (z+1)/2 );
}
} catch (e) {
console.error('Error reading data at offset:', baseOffset);
}
return { points, colors, numPoints: points.length / 3 };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment