summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/api/operation/rendering/draw.spec.ts
blob: 5dd500c05482ef49fdfb65be0cb59d0bc73d5198 (plain)
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
export const description = `
Tests for the general aspects of draw/drawIndexed/drawIndirect/drawIndexedIndirect.

Primitive topology tested in api/operation/render_pipeline/primitive_topology.spec.ts.
Index format tested in api/operation/command_buffer/render/state_tracking.spec.ts.
`;

import { makeTestGroup } from '../../../../common/framework/test_group.js';
import {
  assert,
  TypedArrayBufferView,
  TypedArrayBufferViewConstructor,
} from '../../../../common/util/util.js';
import { GPUTest } from '../../../gpu_test.js';

class DrawTest extends GPUTest {
  checkTriangleDraw(opts: {
    firstIndex: number | undefined;
    count: number;
    firstInstance: number | undefined;
    instanceCount: number | undefined;
    indexed: boolean;
    indirect: boolean;
    vertexBufferOffset: number;
    indexBufferOffset: number | undefined;
    baseVertex: number | undefined;
  }): void {
    // Set fallbacks when parameters are undefined in order to calculate the expected values.
    const defaulted = {
      firstIndex: opts.firstIndex ?? 0,
      count: opts.count,
      firstInstance: opts.firstInstance ?? 0,
      instanceCount: opts.instanceCount ?? 1,
      indexed: opts.indexed,
      indirect: opts.indirect,
      vertexBufferOffset: opts.vertexBufferOffset,
      indexBufferOffset: opts.indexBufferOffset ?? 0,
      baseVertex: opts.baseVertex ?? 0,
    };

    const renderTargetSize = [72, 36];

    // The test will split up the render target into a grid where triangles of
    // increasing primitive id will be placed along the X axis, and triangles
    // of increasing instance id will be placed along the Y axis. The size of the
    // grid is based on the max primitive id and instance id used.
    const numX = 6;
    const numY = 6;
    const tileSizeX = renderTargetSize[0] / numX;
    const tileSizeY = renderTargetSize[1] / numY;

    // |\
    // |   \
    // |______\
    // Unit triangle shaped like this. 0-1 Y-down.
    const triangleVertices = /* prettier-ignore */ [
      0.0, 0.0,
      0.0, 1.0,
      1.0, 1.0,
    ];

    const renderTarget = this.device.createTexture({
      size: renderTargetSize,
      usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
      format: 'rgba8unorm',
    });

    const vertexModule = this.device.createShaderModule({
      code: `
struct Inputs {
  @builtin(vertex_index) vertex_index : u32,
  @builtin(instance_index) instance_id : u32,
  @location(0) vertexPosition : vec2<f32>,
};

@vertex fn vert_main(input : Inputs
  ) -> @builtin(position) vec4<f32> {
  // 3u is the number of points in a triangle to convert from index
  // to id.
  var vertex_id : u32 = input.vertex_index / 3u;

  var x : f32 = (input.vertexPosition.x + f32(vertex_id)) / ${numX}.0;
  var y : f32 = (input.vertexPosition.y + f32(input.instance_id)) / ${numY}.0;

  // (0,1) y-down space to (-1,1) y-up NDC
  x = 2.0 * x - 1.0;
  y = -2.0 * y + 1.0;
  return vec4<f32>(x, y, 0.0, 1.0);
}
`,
    });

    const fragmentModule = this.device.createShaderModule({
      code: `
struct Output {
  value : u32
};

@group(0) @binding(0) var<storage, read_write> output : Output;

@fragment fn frag_main() -> @location(0) vec4<f32> {
  output.value = 1u;
  return vec4<f32>(0.0, 1.0, 0.0, 1.0);
}
`,
    });

    const pipeline = this.device.createRenderPipeline({
      layout: 'auto',
      vertex: {
        module: vertexModule,
        entryPoint: 'vert_main',
        buffers: [
          {
            attributes: [
              {
                shaderLocation: 0,
                format: 'float32x2',
                offset: 0,
              },
            ],
            arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
          },
        ],
      },
      fragment: {
        module: fragmentModule,
        entryPoint: 'frag_main',
        targets: [
          {
            format: 'rgba8unorm',
          },
        ],
      },
    });

    const resultBuffer = this.device.createBuffer({
      size: Uint32Array.BYTES_PER_ELEMENT,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
    });

    const resultBindGroup = this.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        {
          binding: 0,
          resource: {
            buffer: resultBuffer,
          },
        },
      ],
    });

    const commandEncoder = this.device.createCommandEncoder();
    const renderPass = commandEncoder.beginRenderPass({
      colorAttachments: [
        {
          view: renderTarget.createView(),
          clearValue: [0, 0, 0, 0],
          loadOp: 'clear',
          storeOp: 'store',
        },
      ],
    });

    renderPass.setPipeline(pipeline);
    renderPass.setBindGroup(0, resultBindGroup);

    if (defaulted.indexed) {
      // INDEXED DRAW
      assert(defaulted.baseVertex !== undefined);
      assert(defaulted.indexBufferOffset !== undefined);

      renderPass.setIndexBuffer(
        this.makeBufferWithContents(
          /* prettier-ignore */ new Uint32Array([
            // Offset the index buffer contents by empty data.
            ...new Array(defaulted.indexBufferOffset / Uint32Array.BYTES_PER_ELEMENT),

            0,  1,  2, //
            3,  4,  5, //
            6,  7,  8, //
          ]),
          GPUBufferUsage.INDEX
        ),
        'uint32',
        defaulted.indexBufferOffset
      );

      renderPass.setVertexBuffer(
        0,
        this.makeBufferWithContents(
          /* prettier-ignore */ new Float32Array([
            // Offset the vertex buffer contents by empty data.
            ...new Array(defaulted.vertexBufferOffset / Float32Array.BYTES_PER_ELEMENT),

            // selected with base_vertex=0
                                 // count=6
            ...triangleVertices, //   |   count=6;first=3
            ...triangleVertices, //   |       |
            ...triangleVertices, //           |

            // selected with base_vertex=9
                                 // count=6
            ...triangleVertices, //   |   count=6;first=3
            ...triangleVertices, //   |       |
            ...triangleVertices, //           |
          ]),
          GPUBufferUsage.VERTEX
        ),
        defaulted.vertexBufferOffset
      );

      if (defaulted.indirect) {
        const args = [
          defaulted.count,
          defaulted.instanceCount,
          defaulted.firstIndex,
          defaulted.baseVertex,
          defaulted.firstInstance,
        ] as const;
        renderPass.drawIndexedIndirect(
          this.makeBufferWithContents(new Uint32Array(args), GPUBufferUsage.INDIRECT),
          0
        );
      } else {
        const args = [
          opts.count,
          opts.instanceCount,
          opts.firstIndex,
          opts.baseVertex,
          opts.firstInstance,
        ] as const;
        renderPass.drawIndexed.apply(renderPass, [...args]);
      }
    } else {
      // NON-INDEXED DRAW
      renderPass.setVertexBuffer(
        0,
        this.makeBufferWithContents(
          /* prettier-ignore */ new Float32Array([
            // Offset the vertex buffer contents by empty data.
            ...new Array(defaulted.vertexBufferOffset / Float32Array.BYTES_PER_ELEMENT),

                                 // count=6
            ...triangleVertices, //   |   count=6;first=3
            ...triangleVertices, //   |       |
            ...triangleVertices, //           |
          ]),
          GPUBufferUsage.VERTEX
        ),
        defaulted.vertexBufferOffset
      );

      if (defaulted.indirect) {
        const args = [
          defaulted.count,
          defaulted.instanceCount,
          defaulted.firstIndex,
          defaulted.firstInstance,
        ] as const;
        renderPass.drawIndirect(
          this.makeBufferWithContents(new Uint32Array(args), GPUBufferUsage.INDIRECT),
          0
        );
      } else {
        const args = [opts.count, opts.instanceCount, opts.firstIndex, opts.firstInstance] as const;
        renderPass.draw.apply(renderPass, [...args]);
      }
    }

    renderPass.end();
    this.queue.submit([commandEncoder.finish()]);

    const green = new Uint8Array([0, 255, 0, 255]);
    const transparentBlack = new Uint8Array([0, 0, 0, 0]);

    const didDraw = defaulted.count && defaulted.instanceCount;

    this.expectGPUBufferValuesEqual(resultBuffer, new Uint32Array([didDraw ? 1 : 0]));

    const baseVertexCount = defaulted.baseVertex ?? 0;
    for (let primitiveId = 0; primitiveId < numX; ++primitiveId) {
      for (let instanceId = 0; instanceId < numY; ++instanceId) {
        let expectedColor = didDraw ? green : transparentBlack;
        if (
          primitiveId * 3 < defaulted.firstIndex + baseVertexCount ||
          primitiveId * 3 >= defaulted.firstIndex + baseVertexCount + defaulted.count
        ) {
          expectedColor = transparentBlack;
        }

        if (
          instanceId < defaulted.firstInstance ||
          instanceId >= defaulted.firstInstance + defaulted.instanceCount
        ) {
          expectedColor = transparentBlack;
        }

        this.expectSinglePixelIn2DTexture(
          renderTarget,
          'rgba8unorm',
          {
            x: (1 / 3 + primitiveId) * tileSizeX,
            y: (2 / 3 + instanceId) * tileSizeY,
          },
          {
            exp: expectedColor,
          }
        );
      }
    }
  }
}

export const g = makeTestGroup(DrawTest);

g.test('arguments')
  .desc(
    `Test that draw arguments are passed correctly by drawing triangles in a grid.
Horizontally across the texture are triangles with increasing "primitive id".
Vertically down the screen are triangles with increasing instance id.
Increasing the |first| param should skip some of the beginning triangles on the horizontal axis.
Increasing the |first_instance| param should skip of the beginning triangles on the vertical axis.
The vertex buffer contains two sets of disjoint triangles, and base_vertex is used to select the second set.
The test checks that the center of all of the expected triangles is drawn, and the others are empty.
The fragment shader also writes out to a storage buffer. If the draw is zero-sized, check that no value is written.

Params:
  - first= {0, 3} - either the firstVertex or firstIndex
  - count= {0, 3, 6} - either the vertexCount or indexCount
  - first_instance= {0, 2}
  - instance_count= {0, 1, 4}
  - indexed= {true, false}
  - indirect= {true, false}
  - vertex_buffer_offset= {0, 32}
  - index_buffer_offset= {0, 16} - only for indexed draws
  - base_vertex= {0, 9} - only for indexed draws
  `
  )
  .params(u =>
    u
      .combine('first', [0, 3] as const)
      .combine('count', [0, 3, 6] as const)
      .combine('first_instance', [0, 2] as const)
      .combine('instance_count', [0, 1, 4] as const)
      .combine('indexed', [false, true])
      .combine('indirect', [false, true])
      .combine('vertex_buffer_offset', [0, 32] as const)
      .expand('index_buffer_offset', p => (p.indexed ? ([0, 16] as const) : [undefined]))
      .expand('base_vertex', p => (p.indexed ? ([0, 9] as const) : [undefined]))
  )
  .beforeAllSubcases(t => {
    if (t.params.first_instance > 0 && t.params.indirect) {
      t.selectDeviceOrSkipTestCase('indirect-first-instance');
    }
  })
  .fn(async t => {
    t.checkTriangleDraw({
      firstIndex: t.params.first,
      count: t.params.count,
      firstInstance: t.params.first_instance,
      instanceCount: t.params.instance_count,
      indexed: t.params.indexed,
      indirect: t.params.indirect,
      vertexBufferOffset: t.params.vertex_buffer_offset,
      indexBufferOffset: t.params.index_buffer_offset,
      baseVertex: t.params.base_vertex,
    });
  });

g.test('default_arguments')
  .desc(
    `
  Test that defaults arguments are passed correctly by drawing triangles in a grid when they are not
  defined. This test is written based on the 'arguments' with 'undefined' value in the parameters.
    - mode= {draw, drawIndexed}
    - arg= {instance_count, first_index, first_instance, base_vertex}
  `
  )
  .params(u =>
    u
      .combine('mode', ['draw', 'drawIndexed'])
      .beginSubcases()
      .combine('instance_count', [undefined, 4] as const)
      .combine('first_index', [undefined, 3] as const)
      .combine('first_instance', [undefined, 2] as const)
      .expand('base_vertex', p =>
        p.mode === 'drawIndexed' ? ([undefined, 9] as const) : [undefined]
      )
  )
  .fn(async t => {
    const kVertexCount = 3;
    const kVertexBufferOffset = 32;
    const kIndexBufferOffset = 16;

    t.checkTriangleDraw({
      firstIndex: t.params.first_index,
      count: kVertexCount,
      firstInstance: t.params.first_instance,
      instanceCount: t.params.instance_count,
      indexed: t.params.mode === 'drawIndexed',
      indirect: false, // indirect
      vertexBufferOffset: kVertexBufferOffset,
      indexBufferOffset: kIndexBufferOffset,
      baseVertex: t.params.base_vertex,
    });
  });

g.test('vertex_attributes,basic')
  .desc(
    `Test basic fetching of vertex attributes.
  Each vertex attribute is a single value and written out into a storage buffer.
  Tests that vertices with offsets/strides for instanced/non-instanced attributes are
  fetched correctly. Not all vertex formats are tested.

  Params:
  - vertex_attribute_count= {1, 4, 8, 16}
  - vertex_buffer_count={1, 4, 8} - where # attributes is > 0
  - vertex_format={uint32, float32}
  - step_mode= {undefined, vertex, instance, mixed} - where mixed only applies for vertex_buffer_count > 1
  `
  )
  .params(u =>
    u
      .combine('vertex_attribute_count', [1, 4, 8, 16])
      .combine('vertex_buffer_count', [1, 4, 8])
      .combine('vertex_format', ['uint32', 'float32'] as const)
      .combine('step_mode', [undefined, 'vertex', 'instance', 'mixed'] as const)
      .unless(p => p.vertex_attribute_count < p.vertex_buffer_count)
      .unless(p => p.step_mode === 'mixed' && p.vertex_buffer_count <= 1)
  )
  .fn(t => {
    const vertexCount = 4;
    const instanceCount = 4;

    const attributesPerVertexBuffer =
      t.params.vertex_attribute_count / t.params.vertex_buffer_count;
    assert(Math.round(attributesPerVertexBuffer) === attributesPerVertexBuffer);

    let shaderLocation = 0;
    let attributeValue = 0;
    const bufferLayouts: GPUVertexBufferLayout[] = [];

    let ExpectedDataConstructor: TypedArrayBufferViewConstructor;
    switch (t.params.vertex_format) {
      case 'uint32':
        ExpectedDataConstructor = Uint32Array;
        break;
      case 'float32':
        ExpectedDataConstructor = Float32Array;
        break;
    }

    // Populate |bufferLayouts|, |vertexBufferData|, and |vertexBuffers|.
    // We will use this to both create the render pipeline, and produce the
    // expected data on the CPU.
    // Attributes in each buffer will be interleaved.
    const vertexBuffers: GPUBuffer[] = [];
    const vertexBufferData: TypedArrayBufferView[] = [];
    for (let b = 0; b < t.params.vertex_buffer_count; ++b) {
      const vertexBufferValues: number[] = [];

      let offset = 0;
      let stepMode = t.params.step_mode;

      // If stepMode is mixed, alternate between vertex and instance.
      if (stepMode === 'mixed') {
        stepMode = (['vertex', 'instance'] as const)[b % 2];
      }

      let vertexOrInstanceCount: number;
      switch (stepMode) {
        case undefined:
        case 'vertex':
          vertexOrInstanceCount = vertexCount;
          break;
        case 'instance':
          vertexOrInstanceCount = instanceCount;
          break;
      }

      const attributes: GPUVertexAttribute[] = [];
      for (let a = 0; a < attributesPerVertexBuffer; ++a) {
        const attribute: GPUVertexAttribute = {
          format: t.params.vertex_format,
          shaderLocation,
          offset,
        };
        attributes.push(attribute);

        offset += ExpectedDataConstructor.BYTES_PER_ELEMENT;
        shaderLocation += 1;
      }

      for (let v = 0; v < vertexOrInstanceCount; ++v) {
        for (let a = 0; a < attributesPerVertexBuffer; ++a) {
          vertexBufferValues.push(attributeValue);
          attributeValue += 1.234; // Values will get rounded later if we make a Uint32Array.
        }
      }

      bufferLayouts.push({
        attributes,
        arrayStride: offset,
        stepMode,
      });

      const data = new ExpectedDataConstructor(vertexBufferValues);
      vertexBufferData.push(data);
      vertexBuffers.push(t.makeBufferWithContents(data, GPUBufferUsage.VERTEX));
    }

    // Create an array of shader locations [0, 1, 2, 3, ...] for easy iteration.
    const vertexInputShaderLocations = new Array(shaderLocation).fill(0).map((_, i) => i);

    // Create the expected data buffer.
    const expectedData = new ExpectedDataConstructor(
      vertexCount * instanceCount * vertexInputShaderLocations.length
    );

    // Populate the expected data. This is a CPU-side version of what we expect the shader
    // to do.
    for (let vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
      for (let instanceIndex = 0; instanceIndex < instanceCount; ++instanceIndex) {
        bufferLayouts.forEach((bufferLayout, b) => {
          for (const attribute of bufferLayout.attributes) {
            const primitiveId = vertexCount * instanceIndex + vertexIndex;
            const outputIndex =
              primitiveId * vertexInputShaderLocations.length + attribute.shaderLocation;

            let vertexOrInstanceIndex: number;
            switch (bufferLayout.stepMode) {
              case undefined:
              case 'vertex':
                vertexOrInstanceIndex = vertexIndex;
                break;
              case 'instance':
                vertexOrInstanceIndex = instanceIndex;
                break;
            }

            const view = new ExpectedDataConstructor(
              vertexBufferData[b].buffer,
              bufferLayout.arrayStride * vertexOrInstanceIndex + attribute.offset,
              1
            );
            expectedData[outputIndex] = view[0];
          }
        });
      }
    }

    let wgslFormat: string;
    switch (t.params.vertex_format) {
      case 'uint32':
        wgslFormat = 'u32';
        break;
      case 'float32':
        wgslFormat = 'f32';
        break;
    }

    // Maximum inter-stage shader location is 14, and we need to consume one for primitiveId, 12 for
    // location 0 to 11,  and combine the remaining vertex inputs into one location (one
    // vec4<wgslFormat> when vertex_attribute_count === 16).
    const interStageScalarShaderLocation = Math.min(shaderLocation, 12);
    const interStageScalarShaderLocations = new Array(interStageScalarShaderLocation)
      .fill(0)
      .map((_, i) => i);

    let accumulateVariableDeclarationsInVertexShader = '';
    let accumulateVariableAssignmentsInVertexShader = '';
    let accumulateVariableDeclarationsInFragmentShader = '';
    let accumulateVariableAssignmentsInFragmentShader = '';
    // The remaining 3 vertex attributes
    if (t.params.vertex_attribute_count === 16) {
      accumulateVariableDeclarationsInVertexShader = `
        @location(13) @interpolate(flat) outAttrib13 : vec4<${wgslFormat}>,
      `;
      accumulateVariableAssignmentsInVertexShader = `
      output.outAttrib13 =
          vec4<${wgslFormat}>(input.attrib12, input.attrib13, input.attrib14, input.attrib15);
      `;
      accumulateVariableDeclarationsInFragmentShader = `
      @location(13) @interpolate(flat) attrib13 : vec4<${wgslFormat}>,
      `;
      accumulateVariableAssignmentsInFragmentShader = `
      outBuffer.primitives[input.primitiveId].attrib12 = input.attrib13.x;
      outBuffer.primitives[input.primitiveId].attrib13 = input.attrib13.y;
      outBuffer.primitives[input.primitiveId].attrib14 = input.attrib13.z;
      outBuffer.primitives[input.primitiveId].attrib15 = input.attrib13.w;
      `;
    }

    const pipeline = t.device.createRenderPipeline({
      layout: 'auto',
      vertex: {
        module: t.device.createShaderModule({
          code: `
struct Inputs {
  @builtin(vertex_index) vertexIndex : u32,
  @builtin(instance_index) instanceIndex : u32,
${vertexInputShaderLocations.map(i => `  @location(${i}) attrib${i} : ${wgslFormat},`).join('\n')}
};

struct Outputs {
  @builtin(position) Position : vec4<f32>,
${interStageScalarShaderLocations
  .map(i => `  @location(${i}) @interpolate(flat) outAttrib${i} : ${wgslFormat},`)
  .join('\n')}
  @location(${interStageScalarShaderLocations.length}) @interpolate(flat) primitiveId : u32,
${accumulateVariableDeclarationsInVertexShader}
};

@vertex fn main(input : Inputs) -> Outputs {
  var output : Outputs;
${interStageScalarShaderLocations.map(i => `  output.outAttrib${i} = input.attrib${i};`).join('\n')}
${accumulateVariableAssignmentsInVertexShader}

  output.primitiveId = input.instanceIndex * ${instanceCount}u + input.vertexIndex;
  output.Position = vec4<f32>(0.0, 0.0, 0.5, 1.0);
  return output;
}
          `,
        }),
        entryPoint: 'main',
        buffers: bufferLayouts,
      },
      fragment: {
        module: t.device.createShaderModule({
          code: `
struct Inputs {
${interStageScalarShaderLocations
  .map(i => `  @location(${i}) @interpolate(flat) attrib${i} : ${wgslFormat},`)
  .join('\n')}
  @location(${interStageScalarShaderLocations.length}) @interpolate(flat) primitiveId : u32,
${accumulateVariableDeclarationsInFragmentShader}
};

struct OutPrimitive {
${vertexInputShaderLocations.map(i => `  attrib${i} : ${wgslFormat},`).join('\n')}
};
struct OutBuffer {
  primitives : array<OutPrimitive>
};
@group(0) @binding(0) var<storage, read_write> outBuffer : OutBuffer;

@fragment fn main(input : Inputs) {
${interStageScalarShaderLocations
  .map(i => `  outBuffer.primitives[input.primitiveId].attrib${i} = input.attrib${i};`)
  .join('\n')}
${accumulateVariableAssignmentsInFragmentShader}
}
          `,
        }),
        entryPoint: 'main',
        targets: [
          {
            format: 'rgba8unorm',
            writeMask: 0,
          },
        ],
      },
      primitive: {
        topology: 'point-list',
      },
    });

    const resultBuffer = t.device.createBuffer({
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
      size: vertexCount * instanceCount * vertexInputShaderLocations.length * 4,
    });

    const resultBindGroup = t.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        {
          binding: 0,
          resource: {
            buffer: resultBuffer,
          },
        },
      ],
    });

    const commandEncoder = t.device.createCommandEncoder();
    const renderPass = commandEncoder.beginRenderPass({
      colorAttachments: [
        {
          // Dummy render attachment - not used (WebGPU doesn't allow using a render pass with no
          // attachments)
          view: t.device
            .createTexture({
              usage: GPUTextureUsage.RENDER_ATTACHMENT,
              size: [1],
              format: 'rgba8unorm',
            })
            .createView(),
          clearValue: [0, 0, 0, 0],
          loadOp: 'clear',
          storeOp: 'store',
        },
      ],
    });

    renderPass.setPipeline(pipeline);
    renderPass.setBindGroup(0, resultBindGroup);
    for (let i = 0; i < t.params.vertex_buffer_count; ++i) {
      renderPass.setVertexBuffer(i, vertexBuffers[i]);
    }
    renderPass.draw(vertexCount, instanceCount);
    renderPass.end();
    t.device.queue.submit([commandEncoder.finish()]);

    t.expectGPUBufferValuesEqual(resultBuffer, expectedData);
  });

g.test('vertex_attributes,formats')
  .desc(
    `Test all vertex formats are fetched correctly.

    Runs a basic vertex shader which loads vertex data from two attributes which
    may have different formats. Write data out to a storage buffer and check that
    it was loaded correctly.

    Params:
      - vertex_format_1={...all_vertex_formats}
      - vertex_format_2={...all_vertex_formats}
  `
  )
  .unimplemented();

g.test(`largeish_buffer`)
  .desc(
    `
    Test a very large range of buffer is bound.
    For a render pipeline that use a vertex step mode and a instance step mode vertex buffer, test
    that :
    - For draw, drawIndirect, drawIndexed and drawIndexedIndirect:
        - The bound range of vertex step mode vertex buffer is significantly larger than necessary
        - The bound range of instance step mode vertex buffer is significantly larger than necessary
        - A large buffer is bound to an unused slot
    - For drawIndexed and drawIndexedIndirect:
        - The bound range of index buffer is significantly larger than necessary
    - For drawIndirect and drawIndexedIndirect:
        - The indirect buffer is significantly larger than necessary
`
  )
  .unimplemented();