createResource method

  1. @override
ByteBuffer createResource()
override

Implementation

@override
ByteBuffer createResource() {
  var previousIndex = -1;
  final entries = _storage.entries.sortedBy((c) => c.key);

  final packed = <double>[];
  var offsetBytes = 0; // current write cursor in bytes

  for (final e in entries) {
    if (previousIndex + 1 != e.key) {
      final field = slot.fields.indexed.firstWhere(
        (e) => e.$1 == previousIndex + 1,
      );
      throw StateError('Uniform ${slot.name}.${field.$2} was not set');
    }
    previousIndex = e.key;

    final values = e.value.data; // original component values
    final componentCount = values.length;

    final type = _UniformValueType.fromComponentCount(componentCount);

    // align current offset
    final aligned = type.align(offsetBytes);
    if (aligned != offsetBytes) {
      final padFloats = (aligned - offsetBytes) ~/ 4;
      for (var i = 0; i < padFloats; i++) {
        packed.add(0.0);
      }
      offsetBytes = aligned;
    }

    packed.addAll(values);
    // add padding if needed
    final paddingNeeded = type.paddedComponentCount - componentCount;
    for (var i = 0; i < paddingNeeded; i++) {
      packed.add(0.0);
    }

    offsetBytes += type.sizeBytes;
  }

  return Float32List.fromList(packed).buffer;
}