All files / Sources/Rendering/WebGPU/UniformBuffer index.js

2.08% Statements 4/192
0% Branches 0/71
0% Functions 0/11
2.25% Lines 4/177

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356        1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1x                                                                                                     1x          
import macro from 'vtk.js/Sources/macros';
import vtkWebGPUBufferManager from 'vtk.js/Sources/Rendering/WebGPU/BufferManager';
import vtkWebGPUTypes from 'vtk.js/Sources/Rendering/WebGPU/Types';
 
const { BufferUsage } = vtkWebGPUBufferManager;
 
const { vtkErrorMacro } = macro;
 
// ----------------------------------------------------------------------------
// vtkWebGPUUniformBuffer methods
// ----------------------------------------------------------------------------
 
function vtkWebGPUUniformBuffer(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWebGPUUniformBuffer');
 
  publicAPI.addEntry = (name, type) => {
    if (model._bufferEntryNames.has(name)) {
      vtkErrorMacro(`entry named ${name} already exists`);
      return;
    }
    model.sortDirty = true;
    model._bufferEntryNames.set(name, model.bufferEntries.length);
    model.bufferEntries.push({
      name,
      type,
      sizeInBytes: vtkWebGPUTypes.getByteStrideFromShaderFormat(type),
      offset: -1,
      nativeType: vtkWebGPUTypes.getNativeTypeFromShaderFormat(type),
      packed: false,
    });
  };
 
  // UBOs have layout rules in terms of how memory is aligned so we
  // have to be careful how we order the entries. For example a vec4<f32>
  // must be aligned on a 16 byte offset, etc. See
  // https://gpuweb.github.io/gpuweb/wgsl/#memory-layouts
  // for more details. Right now you can create a situation that would fail
  // in the future we could add dummy spacer entries where needed to
  // handle alignment issues
  publicAPI.sortBufferEntries = () => {
    if (!model.sortDirty) {
      return;
    }
 
    let currOffset = 0;
    const newEntries = [];
 
    // compute the max alignment, this is required as WebGPU defines a UBO to have
    // a size that is a multiple of the maxAlignment
    let maxAlignment = 4;
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (entry.sizeInBytes % 16 === 0) {
        maxAlignment = Math.max(16, maxAlignment);
      }
      if (entry.sizeInBytes % 8 === 0) {
        maxAlignment = Math.max(8, maxAlignment);
      }
    }
 
    // pack anything whose size is a multiple of 16 bytes first
    // this includes a couple types that don't require 16 byte alignment
    // such as mat2x2<f32> but that is OK
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (entry.packed === false && entry.sizeInBytes % 16 === 0) {
        entry.packed = true;
        entry.offset = currOffset;
        newEntries.push(entry);
        currOffset += entry.sizeInBytes;
      }
    }
 
    // now it gets tough, we have the following common types (f32, i32, u32)
    // - vec2<f32> 8 byte size, 8 byte alignment
    // - vec3<f32> 12 byte size, 16 byte alignment
    // - f32 4 byte size, 4 byte alignment
 
    // try adding 12 byte, 4 byte pairs
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (entry.packed === false && entry.sizeInBytes === 12) {
        for (let i2 = 0; i2 < model.bufferEntries.length; i2++) {
          const entry2 = model.bufferEntries[i2];
          if (entry2.packed === false && entry2.sizeInBytes === 4) {
            entry.packed = true;
            entry.offset = currOffset;
            newEntries.push(entry);
            currOffset += entry.sizeInBytes;
            entry2.packed = true;
            entry2.offset = currOffset;
            newEntries.push(entry2);
            currOffset += entry2.sizeInBytes;
            break;
          }
        }
      }
    }
 
    // try adding 8 byte, 8 byte pairs
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (!entry.packed && entry.sizeInBytes % 8 === 0) {
        for (let i2 = i + 1; i2 < model.bufferEntries.length; i2++) {
          const entry2 = model.bufferEntries[i2];
          if (!entry2.packed && entry2.sizeInBytes % 8 === 0) {
            entry.packed = true;
            entry.offset = currOffset;
            newEntries.push(entry);
            currOffset += entry.sizeInBytes;
            entry2.packed = true;
            entry2.offset = currOffset;
            newEntries.push(entry2);
            currOffset += entry2.sizeInBytes;
            break;
          }
        }
      }
    }
 
    // try adding 8 byte, 4 byte 4 byte triplets
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (!entry.packed && entry.sizeInBytes % 8 === 0) {
        let found = false;
        for (let i2 = 0; !found && i2 < model.bufferEntries.length; i2++) {
          const entry2 = model.bufferEntries[i2];
          if (!entry2.packed && entry2.sizeInBytes === 4) {
            for (let i3 = i2 + 1; i3 < model.bufferEntries.length; i3++) {
              const entry3 = model.bufferEntries[i3];
              if (!entry3.packed && entry3.sizeInBytes === 4) {
                entry.packed = true;
                entry.offset = currOffset;
                newEntries.push(entry);
                currOffset += entry.sizeInBytes;
                entry2.packed = true;
                entry2.offset = currOffset;
                newEntries.push(entry2);
                currOffset += entry2.sizeInBytes;
                entry3.packed = true;
                entry3.offset = currOffset;
                newEntries.push(entry3);
                currOffset += entry3.sizeInBytes;
                found = true;
                break;
              }
            }
          }
        }
      }
    }
 
    // Add anything remaining that is larger than 4 bytes and hope we get lucky.
    // Likely if there is more than one item added here it will result
    // in a failed UBO
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (!entry.packed && entry.sizeInBytes > 4) {
        entry.packed = true;
        entry.offset = currOffset;
        newEntries.push(entry);
        currOffset += entry.sizeInBytes;
      }
    }
 
    // finally add remaining 4 byte items
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      if (!entry.packed) {
        entry.packed = true;
        entry.offset = currOffset;
        newEntries.push(entry);
        currOffset += entry.sizeInBytes;
      }
    }
 
    // update entries and entryNames
    model.bufferEntries = newEntries;
    model._bufferEntryNames.clear();
    for (let i = 0; i < model.bufferEntries.length; i++) {
      model._bufferEntryNames.set(model.bufferEntries[i].name, i);
    }
    model.sizeInBytes = currOffset;
    model.sizeInBytes =
      maxAlignment * Math.ceil(model.sizeInBytes / maxAlignment);
    model.sortDirty = false;
  };
 
  publicAPI.sendIfNeeded = (device) => {
    if (!model.UBO) {
      const req = {
        nativeArray: model.Float32Array,
        usage: BufferUsage.UniformArray,
        label: model.label,
      };
      model.UBO = device.getBufferManager().getBuffer(req);
      model.bindGroupTime.modified();
      model.sendDirty = false;
    }
 
    // send data down if needed
    if (model.sendDirty) {
      device
        .getHandle()
        .queue.writeBuffer(
          model.UBO.getHandle(),
          0,
          model.arrayBuffer,
          0,
          model.sizeInBytes
        );
      model.sendDirty = false;
    }
 
    // always updated as mappers depend on this time
    // it is more of a sentIfNeededTime
    model.sendTime.modified();
  };
 
  publicAPI.createView = (type) => {
    if (type in model === false) {
      if (!model.arrayBuffer) {
        model.arrayBuffer = new ArrayBuffer(model.sizeInBytes);
      }
      model[type] = macro.newTypedArray(type, model.arrayBuffer);
    }
  };
 
  publicAPI.setValue = (name, val) => {
    publicAPI.sortBufferEntries();
    const idx = model._bufferEntryNames.get(name);
    if (idx === undefined) {
      vtkErrorMacro(`entry named ${name} not found in UBO`);
      return;
    }
    const entry = model.bufferEntries[idx];
    publicAPI.createView(entry.nativeType);
    const view = model[entry.nativeType];
    if (entry.lastValue !== val) {
      view[entry.offset / view.BYTES_PER_ELEMENT] = val;
      model.sendDirty = true;
    }
    entry.lastValue = val;
  };
 
  publicAPI.setArray = (name, arr) => {
    publicAPI.sortBufferEntries();
    const idx = model._bufferEntryNames.get(name);
    if (idx === undefined) {
      vtkErrorMacro(`entry named ${name} not found in UBO`);
      return;
    }
    const entry = model.bufferEntries[idx];
    publicAPI.createView(entry.nativeType);
    const view = model[entry.nativeType];
    let changed = false;
    for (let i = 0; i < arr.length; i++) {
      if (!entry.lastValue || entry.lastValue[i] !== arr[i]) {
        view[entry.offset / view.BYTES_PER_ELEMENT + i] = arr[i];
        changed = true;
      }
    }
    if (changed) {
      model.sendDirty = true;
      entry.lastValue = [...arr];
    }
  };
 
  publicAPI.getBindGroupEntry = () => {
    const foo = {
      resource: {
        buffer: model.UBO.getHandle(),
      },
    };
    return foo;
  };
 
  publicAPI.getSendTime = () => model.sendTime.getMTime();
  publicAPI.getShaderCode = (binding, group) => {
    // sort the entries
    publicAPI.sortBufferEntries();
 
    const lines = [`struct ${model.label}Struct\n{`];
    for (let i = 0; i < model.bufferEntries.length; i++) {
      const entry = model.bufferEntries[i];
      lines.push(`  ${entry.name}: ${entry.type},`);
    }
    lines.push(
      `};\n@binding(${binding}) @group(${group}) var<uniform> ${model.label}: ${model.label}Struct;`
    );
    return lines.join('\n');
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  bufferEntries: null,
  bufferEntryNames: null,
  sizeInBytes: 0,
  label: null,
  bindGroupLayoutEntry: null,
  bindGroupEntry: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Build VTK API
  macro.obj(publicAPI, model);
 
  // Internal objects
  model._bufferEntryNames = new Map();
  model.bufferEntries = [];
 
  // default UBO desc
  model.bindGroupLayoutEntry = model.bindGroupLayoutEntry || {
    buffer: {
      type: 'uniform',
    },
  };
 
  model.sendTime = {};
  macro.obj(model.sendTime, { mtime: 0 });
 
  model.bindGroupTime = {};
  macro.obj(model.bindGroupTime, { mtime: 0 });
 
  model.sendDirty = true;
  model.sortDirty = true;
 
  macro.get(publicAPI, model, ['binding', 'bindGroupTime']);
  macro.setGet(publicAPI, model, [
    'bindGroupLayoutEntry',
    'device',
    'label',
    'sizeInBytes',
  ]);
 
  // Object methods
  vtkWebGPUUniformBuffer(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkWebGPUUniformBuffer');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };