typegpu
Version:
A thin layer between JS and WebGPU/WGSL that improves development experience and allows for faster iteration.
37 lines (36 loc) • 1.32 kB
JavaScript
import { Measurer } from 'typed-binary';
import { roundUp } from "../mathUtils.js";
import alignIO from "./alignIO.js";
import { alignmentOf, customAlignmentOf } from "./alignmentOf.js";
import { isUnstruct } from "./dataTypes.js";
import { sizeOf } from "./sizeOf.js";
const cachedOffsets = new WeakMap();
export function offsetsForProps(struct) {
const cached = cachedOffsets.get(struct);
if (cached) {
return cached;
}
const measurer = new Measurer();
const offsets = {};
let lastEntry;
for (const key in struct.propTypes) {
const prop = struct.propTypes[key];
if (prop === undefined) {
throw new Error(`Property ${key} is undefined in struct`);
}
const beforeAlignment = measurer.size;
alignIO(measurer, isUnstruct(struct) ? customAlignmentOf(prop) : alignmentOf(prop));
if (lastEntry) {
lastEntry.padding = measurer.size - beforeAlignment;
}
const propSize = sizeOf(prop);
offsets[key] = { offset: measurer.size, size: propSize };
lastEntry = offsets[key];
measurer.add(propSize);
}
if (lastEntry) {
lastEntry.padding = roundUp(sizeOf(struct), alignmentOf(struct)) - measurer.size;
}
cachedOffsets.set(struct, offsets);
return offsets;
}