summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/api/operation/texture_view/format_reinterpretation.spec.ts
blob: 30c8ddd962ae2a8139b4574373cd621e5670e289 (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
export const description = `
Test texture views can reinterpret the format of the original texture.
`;

import { makeTestGroup } from '../../../../common/framework/test_group.js';
import {
  EncodableTextureFormat,
  kRenderableColorTextureFormats,
  kRegularTextureFormats,
  viewCompatible,
} from '../../../capability_info.js';
import { GPUTest } from '../../../gpu_test.js';
import { TexelView } from '../../../util/texture/texel_view.js';
import { textureContentIsOKByT2B } from '../../../util/texture/texture_ok.js';

export const g = makeTestGroup(GPUTest);

const kColors = [
  { R: 1.0, G: 0.0, B: 0.0, A: 0.8 },
  { R: 0.0, G: 1.0, B: 0.0, A: 0.7 },
  { R: 0.0, G: 0.0, B: 0.0, A: 0.6 },
  { R: 0.0, G: 0.0, B: 0.0, A: 0.5 },
  { R: 1.0, G: 1.0, B: 1.0, A: 0.4 },
  { R: 0.7, G: 0.0, B: 0.0, A: 0.3 },
  { R: 0.0, G: 0.8, B: 0.0, A: 0.2 },
  { R: 0.0, G: 0.0, B: 0.9, A: 0.1 },
  { R: 0.1, G: 0.2, B: 0.0, A: 0.3 },
  { R: 0.4, G: 0.3, B: 0.6, A: 0.8 },
];

const kTextureSize = 16;

function makeInputTexelView(format: EncodableTextureFormat) {
  return TexelView.fromTexelsAsColors(
    format,
    coords => {
      const pixelPos = coords.y * kTextureSize + coords.x;
      return kColors[pixelPos % kColors.length];
    },
    { clampToFormatRange: true }
  );
}

function makeBlitPipeline(
  device: GPUDevice,
  format: GPUTextureFormat,
  multisample: { sample: number; render: number }
) {
  return device.createRenderPipeline({
    layout: 'auto',
    vertex: {
      module: device.createShaderModule({
        code: `
          @vertex fn main(@builtin(vertex_index) VertexIndex : u32) -> @builtin(position) vec4<f32> {
            var pos = array<vec2<f32>, 6>(
                                        vec2<f32>(-1.0, -1.0),
                                        vec2<f32>(-1.0,  1.0),
                                        vec2<f32>( 1.0, -1.0),
                                        vec2<f32>(-1.0,  1.0),
                                        vec2<f32>( 1.0, -1.0),
                                        vec2<f32>( 1.0,  1.0));
            return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
          }`,
      }),
      entryPoint: 'main',
    },
    fragment: {
      module:
        multisample.sample > 1
          ? device.createShaderModule({
              code: `
            @group(0) @binding(0) var src: texture_multisampled_2d<f32>;
            @fragment fn main(@builtin(position) coord: vec4<f32>) -> @location(0) vec4<f32> {
              var result : vec4<f32>;
              for (var i = 0; i < ${multisample.sample}; i = i + 1) {
                result = result + textureLoad(src, vec2<i32>(coord.xy), i);
              }
              return result * ${1 / multisample.sample};
            }`,
            })
          : device.createShaderModule({
              code: `
            @group(0) @binding(0) var src: texture_2d<f32>;
            @fragment fn main(@builtin(position) coord: vec4<f32>) -> @location(0) vec4<f32> {
              return textureLoad(src, vec2<i32>(coord.xy), 0);
            }`,
            }),
      entryPoint: 'main',
      targets: [{ format }],
    },
    multisample: {
      count: multisample.render,
    },
  });
}

g.test('texture_binding')
  .desc(`Test that a regular texture allocated as 'format' is correctly sampled as 'viewFormat'.`)
  .params(u =>
    u //
      .combine('format', kRegularTextureFormats)
      .combine('viewFormat', kRegularTextureFormats)
      .filter(
        ({ format, viewFormat }) => format !== viewFormat && viewCompatible(format, viewFormat)
      )
  )
  .fn(async t => {
    const { format, viewFormat } = t.params;

    // Make an input texel view.
    const inputTexelView = makeInputTexelView(format);

    // Create the initial texture with the contents if the input texel view.
    const texture = t.makeTextureWithContents(inputTexelView, {
      size: [kTextureSize, kTextureSize],
      usage: GPUTextureUsage.TEXTURE_BINDING,
      viewFormats: [viewFormat],
    });

    // Reinterpret the texture as the view format.
    // Make a texel view of the format that also reinterprets the data.
    const reinterpretedView = texture.createView({ format: viewFormat });
    const reinterpretedTexelView = TexelView.fromTexelsAsBytes(viewFormat, inputTexelView.bytes);

    // Create a pipeline to write data out to rgba8unorm.
    const pipeline = t.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: t.device.createShaderModule({
          code: `
          @group(0) @binding(0) var src: texture_2d<f32>;
          @group(0) @binding(1) var dst: texture_storage_2d<rgba8unorm, write>;
          @compute @workgroup_size(1, 1) fn main(
            @builtin(global_invocation_id) global_id: vec3<u32>,
          ) {
            var coord = vec2<i32>(global_id.xy);
            textureStore(dst, coord, textureLoad(src, coord, 0));
          }`,
        }),
        entryPoint: 'main',
      },
    });

    // Create an rgba8unorm output texture.
    const outputTexture = t.trackForCleanup(
      t.device.createTexture({
        format: 'rgba8unorm',
        size: [kTextureSize, kTextureSize],
        usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC,
      })
    );

    // Execute a compute pass to load data from the reinterpreted view and
    // write out to the rgba8unorm texture.
    const commandEncoder = t.device.createCommandEncoder();
    const pass = commandEncoder.beginComputePass();
    pass.setPipeline(pipeline);
    pass.setBindGroup(
      0,
      t.device.createBindGroup({
        layout: pipeline.getBindGroupLayout(0),
        entries: [
          {
            binding: 0,
            resource: reinterpretedView,
          },
          {
            binding: 1,
            resource: outputTexture.createView(),
          },
        ],
      })
    );
    pass.dispatchWorkgroups(kTextureSize, kTextureSize);
    pass.end();
    t.device.queue.submit([commandEncoder.finish()]);

    const result = await textureContentIsOKByT2B(
      t,
      { texture: outputTexture },
      [kTextureSize, kTextureSize],
      {
        expTexelView: TexelView.fromTexelsAsColors('rgba8unorm', reinterpretedTexelView.color, {
          clampToFormatRange: true,
        }),
      },
      { maxDiffULPsForNormFormat: 1 }
    );
    t.expectOK(result);
  });

g.test('render_and_resolve_attachment')
  .desc(
    `Test that a color render attachment allocated as 'format' is correctly rendered to as 'viewFormat',
and resolved to an attachment allocated as 'format' viewed as 'viewFormat'.

Other combinations aren't possible because the render and resolve targets must both match
in view format and match in base format.`
  )
  .params(u =>
    u //
      .combine('format', kRenderableColorTextureFormats)
      .combine('viewFormat', kRenderableColorTextureFormats)
      .filter(
        ({ format, viewFormat }) => format !== viewFormat && viewCompatible(format, viewFormat)
      )
      .combine('sampleCount', [1, 4])
  )
  .fn(async t => {
    const { format, viewFormat, sampleCount } = t.params;

    // Make an input texel view.
    const inputTexelView = makeInputTexelView(format);

    // Create the renderTexture as |format|.
    const renderTexture = t.trackForCleanup(
      t.device.createTexture({
        format,
        size: [kTextureSize, kTextureSize],
        usage:
          GPUTextureUsage.RENDER_ATTACHMENT |
          (sampleCount > 1 ? GPUTextureUsage.TEXTURE_BINDING : GPUTextureUsage.COPY_SRC),
        viewFormats: [viewFormat],
        sampleCount,
      })
    );

    const resolveTexture =
      sampleCount === 1
        ? undefined
        : t.trackForCleanup(
            t.device.createTexture({
              format,
              size: [kTextureSize, kTextureSize],
              usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
              viewFormats: [viewFormat],
            })
          );

    // Create the sample source with the contents of the input texel view.
    // We will sample this texture into |renderTexture|. It uses the same format to keep the same
    // number of bits of precision.
    const sampleSource = t.makeTextureWithContents(inputTexelView, {
      size: [kTextureSize, kTextureSize],
      usage: GPUTextureUsage.TEXTURE_BINDING,
    });

    // Reinterpret the renderTexture as |viewFormat|.
    const reinterpretedRenderView = renderTexture.createView({ format: viewFormat });
    const reinterpretedResolveView =
      resolveTexture && resolveTexture.createView({ format: viewFormat });

    // Create a pipeline to blit a src texture to the render attachment.
    const pipeline = makeBlitPipeline(t.device, viewFormat, {
      sample: 1,
      render: sampleCount,
    });

    // Execute a render pass to sample |sampleSource| into |texture| viewed as |viewFormat|.
    const commandEncoder = t.device.createCommandEncoder();
    const pass = commandEncoder.beginRenderPass({
      colorAttachments: [
        {
          view: reinterpretedRenderView,
          resolveTarget: reinterpretedResolveView,
          loadOp: 'load',
          storeOp: 'store',
        },
      ],
    });
    pass.setPipeline(pipeline);
    pass.setBindGroup(
      0,
      t.device.createBindGroup({
        layout: pipeline.getBindGroupLayout(0),
        entries: [
          {
            binding: 0,
            resource: sampleSource.createView(),
          },
        ],
      })
    );
    pass.draw(6);
    pass.end();

    // If the render target is multisampled, we'll manually resolve it to check
    // the contents.
    const singleSampleRenderTexture = resolveTexture
      ? t.trackForCleanup(
          t.device.createTexture({
            format,
            size: [kTextureSize, kTextureSize],
            usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
          })
        )
      : renderTexture;

    if (resolveTexture) {
      // Create a pipeline to blit the multisampled render texture to a non-multisample texture.
      // We are basically performing a manual resolve step to the same format as the original
      // render texture to check its contents.
      const pipeline = makeBlitPipeline(t.device, format, { sample: sampleCount, render: 1 });
      const pass = commandEncoder.beginRenderPass({
        colorAttachments: [
          {
            view: singleSampleRenderTexture.createView(),
            loadOp: 'load',
            storeOp: 'store',
          },
        ],
      });
      pass.setPipeline(pipeline);
      pass.setBindGroup(
        0,
        t.device.createBindGroup({
          layout: pipeline.getBindGroupLayout(0),
          entries: [
            {
              binding: 0,
              resource: renderTexture.createView(),
            },
          ],
        })
      );
      pass.draw(6);
      pass.end();
    }

    // Submit the commands.
    t.device.queue.submit([commandEncoder.finish()]);

    // Check the rendered contents.
    const renderViewTexels = TexelView.fromTexelsAsColors(viewFormat, inputTexelView.color, {
      clampToFormatRange: true,
    });
    t.expectOK(
      await textureContentIsOKByT2B(
        t,
        { texture: singleSampleRenderTexture },
        [kTextureSize, kTextureSize],
        { expTexelView: renderViewTexels },
        { maxDiffULPsForNormFormat: 2 }
      )
    );

    // Check the resolved contents.
    if (resolveTexture) {
      const resolveView = TexelView.fromTexelsAsColors(viewFormat, renderViewTexels.color, {
        clampToFormatRange: true,
      });

      const result = await textureContentIsOKByT2B(
        t,
        { texture: resolveTexture },
        [kTextureSize, kTextureSize],
        { expTexelView: resolveView },
        { maxDiffULPsForNormFormat: 2 }
      );
      t.expectOK(result);
    }
  });