summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/api/validation/queue/copyToTexture/CopyExternalImageToTexture.spec.ts
blob: 4ac240d66ec2e0f6d0ff6c1a4c713f9b9aef6df7 (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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
export const description = `
copyExternalImageToTexture Validation Tests in Queue.
Note that we don't need to add tests on the destination texture dimension as currently we require
the destination texture should have RENDER_ATTACHMENT usage, which is only allowed to be used on 2D
textures.
`;

import {
  getResourcePath,
  getCrossOriginResourcePath,
} from '../../../../../common/framework/resources.js';
import { makeTestGroup } from '../../../../../common/framework/test_group.js';
import { raceWithRejectOnTimeout, unreachable, assert } from '../../../../../common/util/util.js';
import { kTextureUsages } from '../../../../capability_info.js';
import {
  kTextureFormatInfo,
  kTextureFormats,
  kValidTextureFormatsForCopyE2T,
} from '../../../../format_info.js';
import { kResourceStates } from '../../../../gpu_test.js';
import {
  CanvasType,
  createCanvas,
  createOnscreenCanvas,
  createOffscreenCanvas,
} from '../../../../util/create_elements.js';
import { ValidationTest } from '../../validation_test.js';

const kDefaultBytesPerPixel = 4; // using 'bgra8unorm' or 'rgba8unorm'
const kDefaultWidth = 32;
const kDefaultHeight = 32;
const kDefaultDepth = 1;
const kDefaultMipLevelCount = 6;

function computeMipMapSize(width: number, height: number, mipLevel: number) {
  return {
    mipWidth: Math.max(width >> mipLevel, 1),
    mipHeight: Math.max(height >> mipLevel, 1),
  };
}

interface WithMipLevel {
  mipLevel: number;
}

interface WithDstOriginMipLevel extends WithMipLevel {
  dstOrigin: Required<GPUOrigin3DDict>;
}

// Helper function to generate copySize for src OOB test
function generateCopySizeForSrcOOB({ srcOrigin }: { srcOrigin: Required<GPUOrigin2DDict> }) {
  // OOB origin fails even with no-op copy.
  if (srcOrigin.x > kDefaultWidth || srcOrigin.y > kDefaultHeight) {
    return [{ width: 0, height: 0, depthOrArrayLayers: 0 }];
  }

  const justFitCopySize = {
    width: kDefaultWidth - srcOrigin.x,
    height: kDefaultHeight - srcOrigin.y,
    depthOrArrayLayers: 1,
  };

  return [
    justFitCopySize, // correct size, maybe no-op copy.
    {
      width: justFitCopySize.width + 1,
      height: justFitCopySize.height,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers,
    }, // OOB in width
    {
      width: justFitCopySize.width,
      height: justFitCopySize.height + 1,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers,
    }, // OOB in height
    {
      width: justFitCopySize.width,
      height: justFitCopySize.height,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers + 1,
    }, // OOB in depthOrArrayLayers
  ];
}

// Helper function to generate dst origin value based on mipLevel.
function generateDstOriginValue({ mipLevel }: WithMipLevel) {
  const origin = computeMipMapSize(kDefaultWidth, kDefaultHeight, mipLevel);

  return [
    { x: 0, y: 0, z: 0 },
    { x: origin.mipWidth - 1, y: 0, z: 0 },
    { x: 0, y: origin.mipHeight - 1, z: 0 },
    { x: origin.mipWidth, y: 0, z: 0 },
    { x: 0, y: origin.mipHeight, z: 0 },
    { x: 0, y: 0, z: kDefaultDepth },
    { x: origin.mipWidth + 1, y: 0, z: 0 },
    { x: 0, y: origin.mipHeight + 1, z: 0 },
    { x: 0, y: 0, z: kDefaultDepth + 1 },
  ];
}

// Helper function to generate copySize for dst OOB test
function generateCopySizeForDstOOB({ mipLevel, dstOrigin }: WithDstOriginMipLevel) {
  const dstMipMapSize = computeMipMapSize(kDefaultWidth, kDefaultHeight, mipLevel);

  // OOB origin fails even with no-op copy.
  if (
    dstOrigin.x > dstMipMapSize.mipWidth ||
    dstOrigin.y > dstMipMapSize.mipHeight ||
    dstOrigin.z > kDefaultDepth
  ) {
    return [{ width: 0, height: 0, depthOrArrayLayers: 0 }];
  }

  const justFitCopySize = {
    width: dstMipMapSize.mipWidth - dstOrigin.x,
    height: dstMipMapSize.mipHeight - dstOrigin.y,
    depthOrArrayLayers: kDefaultDepth - dstOrigin.z,
  };

  return [
    justFitCopySize,
    {
      width: justFitCopySize.width + 1,
      height: justFitCopySize.height,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers,
    }, // OOB in width
    {
      width: justFitCopySize.width,
      height: justFitCopySize.height + 1,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers,
    }, // OOB in height
    {
      width: justFitCopySize.width,
      height: justFitCopySize.height,
      depthOrArrayLayers: justFitCopySize.depthOrArrayLayers + 1,
    }, // OOB in depthOrArrayLayers
  ];
}

class CopyExternalImageToTextureTest extends ValidationTest {
  onlineCrossOriginUrl = 'https://raw.githubusercontent.com/gpuweb/gpuweb/main/logo/webgpu.png';

  getImageData(width: number, height: number): ImageData {
    if (typeof ImageData === 'undefined') {
      this.skip('ImageData is not supported.');
    }

    const pixelSize = kDefaultBytesPerPixel * width * height;
    const imagePixels = new Uint8ClampedArray(pixelSize);
    return new ImageData(imagePixels, width, height);
  }

  getCanvasWithContent(
    canvasType: CanvasType,
    width: number,
    height: number,
    content: HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageBitmap
  ): HTMLCanvasElement | OffscreenCanvas {
    const canvas = createCanvas(this, canvasType, 1, 1);
    const ctx = canvas.getContext('2d');
    switch (canvasType) {
      case 'onscreen':
        assert(ctx instanceof CanvasRenderingContext2D);
        break;
      case 'offscreen':
        assert(ctx instanceof OffscreenCanvasRenderingContext2D);
        break;
    }
    ctx.drawImage(content, 0, 0);

    return canvas;
  }

  createImageBitmap(image: ImageBitmapSource | OffscreenCanvas): Promise<ImageBitmap> {
    if (typeof createImageBitmap === 'undefined') {
      this.skip('Creating ImageBitmaps is not supported.');
    }
    return createImageBitmap(image);
  }

  runTest(
    imageBitmapCopyView: GPUImageCopyExternalImage,
    textureCopyView: GPUImageCopyTextureTagged,
    copySize: GPUExtent3D,
    validationScopeSuccess: boolean,
    exceptionName?: string
  ): void {
    // copyExternalImageToTexture will generate two types of errors. One is synchronous exceptions;
    // the other is asynchronous validation error scope errors.
    if (exceptionName) {
      this.shouldThrow(exceptionName, () => {
        this.device.queue.copyExternalImageToTexture(
          imageBitmapCopyView,
          textureCopyView,
          copySize
        );
      });
    } else {
      this.expectValidationError(() => {
        this.device.queue.copyExternalImageToTexture(
          imageBitmapCopyView,
          textureCopyView,
          copySize
        );
      }, !validationScopeSuccess);
    }
  }
}

export const g = makeTestGroup(CopyExternalImageToTextureTest);

g.test('source_image,crossOrigin')
  .desc(
    `
  Test contents of source image is [clean, cross-origin].

  Load crossOrigin image or same origin image and init the source
  images.

  Check whether 'SecurityError' is generated when source image is not origin clean.
  `
  )
  .params(u =>
    u //
      .combine('sourceImage', ['canvas', 'offscreenCanvas', 'imageBitmap'])
      .combine('isOriginClean', [true, false])
      .beginSubcases()
      .combine('contentFrom', ['image', 'imageBitmap', 'canvas', 'offscreenCanvas'] as const)
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { sourceImage, isOriginClean, contentFrom, copySize } = t.params;
    if (typeof document === 'undefined') {
      t.skip('DOM is not available to create an image element.');
    }

    const crossOriginUrl = getCrossOriginResourcePath('webgpu.png', t.onlineCrossOriginUrl);
    const originCleanUrl = getResourcePath('webgpu.png');
    const img = document.createElement('img');
    img.src = isOriginClean ? originCleanUrl : crossOriginUrl;

    // Load image
    const timeout_ms = 5000;
    try {
      await raceWithRejectOnTimeout(img.decode(), timeout_ms, 'load image timeout');
    } catch (e) {
      if (isOriginClean) {
        throw e;
      } else {
        t.skip('Cannot load cross origin image in time');
        return;
      }
    }

    // The externalImage contents can be updated by:
    // - decoded image element
    // - canvas/offscreenCanvas with image draw on it.
    // - imageBitmap created with the image.
    // Test covers all of these cases to ensure origin clean checks works.
    let source: HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageBitmap;
    switch (contentFrom) {
      case 'image': {
        source = img;
        break;
      }
      case 'imageBitmap': {
        source = await t.createImageBitmap(img);
        break;
      }
      case 'canvas':
      case 'offscreenCanvas': {
        const canvasType = contentFrom === 'offscreenCanvas' ? 'offscreen' : 'onscreen';
        source = t.getCanvasWithContent(canvasType, 1, 1, img);
        break;
      }
      default:
        unreachable();
    }

    // Update the externalImage content with source.
    let externalImage: HTMLCanvasElement | OffscreenCanvas | ImageBitmap;
    switch (sourceImage) {
      case 'imageBitmap': {
        externalImage = await t.createImageBitmap(source);
        break;
      }
      case 'canvas':
      case 'offscreenCanvas': {
        const canvasType = contentFrom === 'offscreenCanvas' ? 'offscreen' : 'onscreen';
        externalImage = t.getCanvasWithContent(canvasType, 1, 1, source);
        break;
      }
      default:
        unreachable();
    }

    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    t.runTest(
      { source: externalImage },
      { texture: dstTexture },
      copySize,
      true, // No validation errors.
      isOriginClean ? '' : 'SecurityError'
    );
  });

g.test('source_imageBitmap,state')
  .desc(
    `
  Test ImageBitmap as source image in state [valid, closed].

  Call imageBitmap.close() to transfer the imageBitmap into
  'closed' state.

  Check whether 'InvalidStateError' is generated when ImageBitmap is
  closed.
  `
  )
  .params(u =>
    u //
      .combine('closed', [false, true])
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { closed, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));
    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    if (closed) imageBitmap.close();

    t.runTest(
      { source: imageBitmap },
      { texture: dstTexture },
      copySize,
      true, // No validation errors.
      closed ? 'InvalidStateError' : ''
    );
  });

g.test('source_canvas,state')
  .desc(
    `
  Test HTMLCanvasElement as source image in state
  [nocontext, 'placeholder-nocontext', 'placeholder-hascontext', valid].

  Nocontext means using a canvas without any context as copy param.

  Call 'transferControlToOffscreen' on HTMLCanvasElement will cause the
  canvas control right transfer. And this canvas is in state 'placeholder'
  Whether getContext in new generated offscreenCanvas won't affect the origin
  canvas state.


  Check whether 'OperationError' is generated when HTMLCanvasElement has no
  context.

  Check whether 'InvalidStateError' is generated when HTMLCanvasElement is
  in 'placeholder' state.
    `
  )
  .params(u =>
    u //
      .combine('state', ['nocontext', 'placeholder-nocontext', 'placeholder-hascontext', 'valid'])
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(t => {
    const { state, copySize } = t.params;
    const canvas = createOnscreenCanvas(t, 1, 1);
    if (typeof canvas.transferControlToOffscreen === 'undefined') {
      t.skip("Browser doesn't support HTMLCanvasElement.transferControlToOffscreen");
      return;
    }

    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    let exceptionName: string = '';

    switch (state) {
      case 'nocontext': {
        exceptionName = 'OperationError';
        break;
      }
      case 'placeholder-nocontext': {
        canvas.transferControlToOffscreen();
        exceptionName = 'InvalidStateError';
        break;
      }
      case 'placeholder-hascontext': {
        const offscreenCanvas = canvas.transferControlToOffscreen();
        t.tryTrackForCleanup(offscreenCanvas.getContext('webgl'));
        exceptionName = 'InvalidStateError';
        break;
      }
      case 'valid': {
        assert(canvas.getContext('2d') !== null);
        break;
      }
      default:
        unreachable();
    }

    t.runTest(
      { source: canvas },
      { texture: dstTexture },
      copySize,
      true, // No validation errors.
      exceptionName
    );
  });

g.test('source_offscreenCanvas,state')
  .desc(
    `
  Test OffscreenCanvas as source image in state [valid, detached].

  Nocontext means using a canvas without any context as copy param.

  Transfer OffscreenCanvas with MessageChannel will detach the OffscreenCanvas.

  Check whether 'OperationError' is generated when HTMLCanvasElement has no
  context.

  Check whether 'InvalidStateError' is generated when OffscreenCanvas is
  detached.
  `
  )
  .params(u =>
    u //
      .combine('state', ['nocontext', 'detached-nocontext', 'detached-hascontext', 'valid'])
      .beginSubcases()
      .combine('getContextInOffscreenCanvas', [false, true])
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { state, copySize } = t.params;
    const offscreenCanvas = createOffscreenCanvas(t, 1, 1);
    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    let exceptionName: string = '';
    switch (state) {
      case 'nocontext': {
        exceptionName = 'OperationError';
        break;
      }
      case 'detached-nocontext': {
        const messageChannel = new MessageChannel();
        messageChannel.port1.postMessage(offscreenCanvas, [offscreenCanvas]);

        exceptionName = 'InvalidStateError';
        break;
      }
      case 'detached-hascontext': {
        const messageChannel = new MessageChannel();
        const port2FirstMessage = new Promise(resolve => {
          messageChannel.port2.onmessage = m => resolve(m);
        });

        messageChannel.port1.postMessage(offscreenCanvas, [offscreenCanvas]);

        const receivedOffscreenCanvas = (await port2FirstMessage) as MessageEvent;
        t.tryTrackForCleanup(receivedOffscreenCanvas.data.getContext('webgl'));

        exceptionName = 'InvalidStateError';
        break;
      }
      case 'valid': {
        offscreenCanvas.getContext('webgl');
        break;
      }
      default:
        unreachable();
    }

    t.runTest(
      { source: offscreenCanvas },
      { texture: dstTexture },
      copySize,
      true, // No validation errors.
      exceptionName
    );
  });

g.test('destination_texture,state')
  .desc(
    `
  Test dst texture is [valid, invalid, destroyed].

  Check that an error is generated when texture is an error texture.
  Check that an error is generated when texture is in destroyed state.
  `
  )
  .params(u =>
    u //
      .combine('state', kResourceStates)
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { state, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));
    const dstTexture = t.createTextureWithState(state);

    t.runTest({ source: imageBitmap }, { texture: dstTexture }, copySize, state === 'valid');
  });

g.test('destination_texture,device_mismatch')
  .desc(
    'Tests copyExternalImageToTexture cannot be called with a destination texture created from another device'
  )
  .paramsSubcasesOnly(u => u.combine('mismatched', [true, false]))
  .beforeAllSubcases(t => {
    t.selectMismatchedDeviceOrSkipTestCase(undefined);
  })
  .fn(async t => {
    const { mismatched } = t.params;
    const sourceDevice = mismatched ? t.mismatchedDevice : t.device;
    const copySize = { width: 1, height: 1, depthOrArrayLayers: 1 };

    const texture = sourceDevice.createTexture({
      size: copySize,
      format: 'rgba8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));

    t.runTest({ source: imageBitmap }, { texture }, copySize, !mismatched);
  });

g.test('destination_texture,usage')
  .desc(
    `
  Test dst texture usages

  Check that an error is generated when texture is created without usage COPY_DST | RENDER_ATTACHMENT.
  `
  )
  .params(u =>
    u //
      .combine('usage', kTextureUsages)
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { usage, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));
    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format: 'rgba8unorm',
      usage,
    });

    t.runTest(
      { source: imageBitmap },
      { texture: dstTexture },
      copySize,
      !!(usage & GPUTextureUsage.COPY_DST && usage & GPUTextureUsage.RENDER_ATTACHMENT)
    );
  });

g.test('destination_texture,sample_count')
  .desc(
    `
  Test dst texture sample count.

  Check that an error is generated when sample count it not 1.
  `
  )
  .params(u =>
    u //
      .combine('sampleCount', [1, 4])
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { sampleCount, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));
    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      sampleCount,
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    t.runTest({ source: imageBitmap }, { texture: dstTexture }, copySize, sampleCount === 1);
  });

g.test('destination_texture,mipLevel')
  .desc(
    `
  Test dst mipLevel.

  Check that an error is generated when mipLevel is too large.
  `
  )
  .params(u =>
    u //
      .combine('mipLevel', [0, kDefaultMipLevelCount - 1, kDefaultMipLevelCount])
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .fn(async t => {
    const { mipLevel, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));
    const dstTexture = t.device.createTexture({
      size: { width: kDefaultWidth, height: kDefaultHeight, depthOrArrayLayers: kDefaultDepth },
      mipLevelCount: kDefaultMipLevelCount,
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    t.runTest(
      { source: imageBitmap },
      { texture: dstTexture, mipLevel },
      copySize,
      mipLevel < kDefaultMipLevelCount
    );
  });

g.test('destination_texture,format')
  .desc(
    `
  Test dst texture format.

  Check that an error is generated when texture format is not valid.
  `
  )
  .params(u =>
    u
      .combine('format', kTextureFormats)
      .beginSubcases()
      .combine('copySize', [
        { width: 0, height: 0, depthOrArrayLayers: 0 },
        { width: 1, height: 1, depthOrArrayLayers: 1 },
      ])
  )
  .beforeAllSubcases(t => {
    const { format } = t.params;
    t.skipIfTextureFormatNotSupported(format);
    t.selectDeviceOrSkipTestCase(kTextureFormatInfo[format].feature);
  })
  .fn(async t => {
    const { format, copySize } = t.params;

    const imageBitmap = await t.createImageBitmap(t.getImageData(1, 1));

    // createTexture with all possible texture format may have validation error when using
    // compressed texture format.
    t.device.pushErrorScope('validation');
    const dstTexture = t.device.createTexture({
      size: { width: 1, height: 1, depthOrArrayLayers: 1 },
      format,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });
    void t.device.popErrorScope();

    const success = (kValidTextureFormatsForCopyE2T as readonly string[]).includes(format);

    t.runTest({ source: imageBitmap }, { texture: dstTexture }, copySize, success);
  });

g.test('OOB,source')
  .desc(
    `
  Test source image origin and copy size

  Check that an error is generated when source.externalImage.origin + copySize is too large.
  `
  )
  .paramsSubcasesOnly(u =>
    u
      .combine('srcOrigin', [
        { x: 0, y: 0 }, // origin is on top-left
        { x: kDefaultWidth - 1, y: 0 }, // x near the border
        { x: 0, y: kDefaultHeight - 1 }, // y is near the border
        { x: kDefaultWidth, y: kDefaultHeight }, // origin is on bottom-right
        { x: kDefaultWidth + 1, y: 0 }, // x is too large
        { x: 0, y: kDefaultHeight + 1 }, // y is too large
      ])
      .expand('copySize', generateCopySizeForSrcOOB)
  )
  .fn(async t => {
    const { srcOrigin, copySize } = t.params;
    const imageBitmap = await t.createImageBitmap(t.getImageData(kDefaultWidth, kDefaultHeight));
    const dstTexture = t.device.createTexture({
      size: {
        width: kDefaultWidth + 1,
        height: kDefaultHeight + 1,
        depthOrArrayLayers: kDefaultDepth,
      },
      mipLevelCount: kDefaultMipLevelCount,
      format: 'bgra8unorm',
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    let success = true;

    if (
      srcOrigin.x + copySize.width > kDefaultWidth ||
      srcOrigin.y + copySize.height > kDefaultHeight ||
      copySize.depthOrArrayLayers > 1
    ) {
      success = false;
    }

    t.runTest(
      { source: imageBitmap, origin: srcOrigin },
      { texture: dstTexture },
      copySize,
      true,
      success ? '' : 'OperationError'
    );
  });

g.test('OOB,destination')
  .desc(
    `
  Test dst texture copy origin and copy size

  Check that an error is generated when destination.texture.origin + copySize is too large.
  Check that 'OperationError' is generated when copySize.depth is larger than 1.
  `
  )
  .paramsSubcasesOnly(u =>
    u
      .combine('mipLevel', [0, 1, kDefaultMipLevelCount - 2])
      .expand('dstOrigin', generateDstOriginValue)
      .expand('copySize', generateCopySizeForDstOOB)
  )
  .fn(async t => {
    const { mipLevel, dstOrigin, copySize } = t.params;

    const imageBitmap = await t.createImageBitmap(
      t.getImageData(kDefaultWidth + 1, kDefaultHeight + 1)
    );
    const dstTexture = t.device.createTexture({
      size: {
        width: kDefaultWidth,
        height: kDefaultHeight,
        depthOrArrayLayers: kDefaultDepth,
      },
      format: 'bgra8unorm',
      mipLevelCount: kDefaultMipLevelCount,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
    });

    let success = true;
    let hasOperationError = false;
    const dstMipMapSize = computeMipMapSize(kDefaultWidth, kDefaultHeight, mipLevel);

    if (
      copySize.depthOrArrayLayers > 1 ||
      dstOrigin.x + copySize.width > dstMipMapSize.mipWidth ||
      dstOrigin.y + copySize.height > dstMipMapSize.mipHeight ||
      dstOrigin.z + copySize.depthOrArrayLayers > kDefaultDepth
    ) {
      success = false;
    }
    if (copySize.depthOrArrayLayers > 1) {
      hasOperationError = true;
    }

    t.runTest(
      { source: imageBitmap },
      {
        texture: dstTexture,
        mipLevel,
        origin: dstOrigin,
      },
      copySize,
      success,
      hasOperationError ? 'OperationError' : ''
    );
  });