export const description = `
Samples a depth texture and compares the sampled depth values against a reference value.

The textureSampleCompareLevel function is the same as textureSampleCompare, except that:

 * textureSampleCompareLevel always samples texels from mip level 0.
   * The function does not compute derivatives.
   * There is no requirement for textureSampleCompareLevel to be invoked in uniform control flow.
 * textureSampleCompareLevel may be invoked in any shader stage.

- TODO: test un-encodable formats.
`;

import { makeTestGroup } from '../../../../../../common/framework/test_group.js';
import { kCompareFunctions } from '../../../../../capability_info.js';
import { isDepthTextureFormat, kDepthStencilFormats } from '../../../../../format_info.js';
import { AllFeaturesMaxLimitsGPUTest } from '../../../../../gpu_test.js';

import {
  checkCallResults,
  chooseTextureSize,
  createTextureWithRandomDataAndGetTexels,
  doTextureCalls,
  generateSamplePointsCube,
  generateTextureBuiltinInputs2D,
  kCubeSamplePointMethods,
  kSamplePointMethods,
  kShortAddressModes,
  kShortAddressModeToAddressMode,
  kShortShaderStages,
  makeRandomDepthComparisonTexelGenerator,
  TextureCall,
  vec2,
  vec3,
} from './texture_utils.js';

export const g = makeTestGroup(AllFeaturesMaxLimitsGPUTest);

g.test('2d_coords')
  .specURL('https://www.w3.org/TR/WGSL/#texturesamplecomparelevel')
  .desc(
    `
fn textureSampleCompareLevel(t: texture_depth_2d, s: sampler_comparison, coords: vec2<f32>, depth_ref: f32) -> f32
fn textureSampleCompareLevel(t: texture_depth_2d, s: sampler_comparison, coords: vec2<f32>, depth_ref: f32, offset: vec2<i32>) -> f32

Parameters:
 * t  The depth texture to sample.
 * s  The sampler_comparison type.
 * coords The texture coordinates used for sampling.
 * depth_ref The reference value to compare the sampled depth value against.
 * offset
    * The optional texel offset applied to the unnormalized texture coordinate before sampling the texture.
    * This offset is applied before applying any texture wrapping modes.
    * The offset expression must be a creation-time expression (e.g. vec2<i32>(1, 2)).
    * Each offset component must be at least -8 and at most 7.
      Values outside of this range will result in a shader-creation error.
`
  )
  .params(u =>
    u
      .combine('stage', kShortShaderStages)
      .combine('format', kDepthStencilFormats)
      // filter out stencil only formats
      .filter(t => isDepthTextureFormat(t.format))
      .combine('filt', ['nearest', 'linear'] as const)
      .combine('modeU', kShortAddressModes)
      .combine('modeV', kShortAddressModes)
      .combine('offset', [false, true] as const)
      .beginSubcases()
      .combine('samplePoints', kSamplePointMethods)
      .combine('compare', kCompareFunctions)
  )
  .fn(async t => {
    const {
      format,
      stage,
      samplePoints,
      modeU,
      modeV,
      filt: minFilter,
      compare,
      offset,
    } = t.params;
    t.skipIfTextureFormatNotSupported(format);

    const size = chooseTextureSize({ minSize: 16, minBlocks: 4, format });

    const descriptor: GPUTextureDescriptor = {
      format,
      size,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
      mipLevelCount: 3,
    };
    const { texels, texture } = await createTextureWithRandomDataAndGetTexels(t, descriptor, {
      generator: makeRandomDepthComparisonTexelGenerator(descriptor, compare),
    });
    const sampler: GPUSamplerDescriptor = {
      addressModeU: kShortAddressModeToAddressMode[modeU],
      addressModeV: kShortAddressModeToAddressMode[modeV],
      compare,
      minFilter,
      magFilter: minFilter,
      mipmapFilter: minFilter,
    };

    const calls: TextureCall<vec2>[] = generateTextureBuiltinInputs2D(50, {
      method: samplePoints,
      textureBuiltin: 'textureSampleCompareLevel',
      sampler,
      descriptor,
      derivatives: true,
      depthRef: true,
      offset,
      hashInputs: [stage, format, samplePoints, modeU, modeV, minFilter, offset],
    }).map(({ coords, derivativeMult, arrayIndex, depthRef, offset }) => {
      return {
        builtin: 'textureSampleCompareLevel',
        coordType: 'f',
        coords,
        derivativeMult,
        depthRef,
        offset,
      };
    });
    const textureType = 'texture_depth_2d';
    const viewDescriptor = {};
    const results = await doTextureCalls(
      t,
      texture,
      viewDescriptor,
      textureType,
      sampler,
      calls,
      stage
    );
    const res = await checkCallResults(
      t,
      { texels, descriptor, viewDescriptor },
      textureType,
      sampler,
      calls,
      results,
      stage,
      texture
    );
    t.expectOK(res);
  });

g.test('3d_coords')
  .specURL('https://www.w3.org/TR/WGSL/#texturesamplecomparelevel')
  .desc(
    `
fn textureSampleCompareLevel(t: texture_depth_cube, s: sampler_comparison, coords: vec3<f32>, depth_ref: f32) -> f32

Parameters:
 * t  The depth texture to sample.
 * s  The sampler_comparison type.
 * coords The texture coordinates used for sampling.
 * depth_ref The reference value to compare the sampled depth value against.
`
  )
  .params(u =>
    u
      .combine('stage', kShortShaderStages)
      .combine('format', kDepthStencilFormats)
      // filter out stencil only formats
      .filter(t => isDepthTextureFormat(t.format))
      .combine('filt', ['nearest', 'linear'] as const)
      .combine('mode', kShortAddressModes)
      .beginSubcases()
      .combine('samplePoints', kCubeSamplePointMethods)
      .combine('compare', kCompareFunctions)
  )
  .fn(async t => {
    const { format, stage, samplePoints, mode, filt: minFilter, compare } = t.params;
    t.skipIfTextureFormatNotSupported(format);

    const viewDimension: GPUTextureViewDimension = 'cube';
    const size = chooseTextureSize({ minSize: 16, minBlocks: 2, format, viewDimension });

    const descriptor: GPUTextureDescriptor = {
      format,
      ...(t.isCompatibility && { textureBindingViewDimension: viewDimension }),
      size,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
      // MAINTENANCE_TODO: change to 3
      mipLevelCount: 1,
    };
    const { texels, texture } = await createTextureWithRandomDataAndGetTexels(t, descriptor, {
      generator: makeRandomDepthComparisonTexelGenerator(descriptor, compare),
    });
    const sampler: GPUSamplerDescriptor = {
      addressModeU: kShortAddressModeToAddressMode[mode],
      addressModeV: kShortAddressModeToAddressMode[mode],
      addressModeW: kShortAddressModeToAddressMode[mode],
      compare,
      minFilter,
      magFilter: minFilter,
      mipmapFilter: minFilter,
    };

    const calls: TextureCall<vec3>[] = generateSamplePointsCube(50, {
      method: samplePoints,
      sampler,
      descriptor,
      derivatives: true,
      depthRef: true,
      textureBuiltin: 'textureSampleCompareLevel',
      hashInputs: [stage, format, samplePoints, mode, minFilter, compare],
    }).map(({ coords, derivativeMult, depthRef }) => {
      return {
        builtin: 'textureSampleCompareLevel',
        coordType: 'f',
        coords,
        derivativeMult,
        depthRef,
      };
    });
    const viewDescriptor = {
      dimension: viewDimension,
    };
    const textureType = 'texture_depth_cube';
    const results = await doTextureCalls(
      t,
      texture,
      viewDescriptor,
      textureType,
      sampler,
      calls,
      stage
    );
    const res = await checkCallResults(
      t,
      { texels, descriptor, viewDescriptor },
      textureType,
      sampler,
      calls,
      results,
      stage,
      texture
    );
    t.expectOK(res);
  });

g.test('arrayed_2d_coords')
  .specURL('https://www.w3.org/TR/WGSL/#texturesamplecomparelevel')
  .desc(
    `
A is i32 or u32

fn textureSampleCompareLevel(t: texture_depth_2d_array, s: sampler_comparison, coords: vec2<f32>, array_index: A, depth_ref: f32) -> f32
fn textureSampleCompareLevel(t: texture_depth_2d_array, s: sampler_comparison, coords: vec2<f32>, array_index: A, depth_ref: f32, offset: vec2<i32>) -> f32

Parameters:
 * t  The depth texture to sample.
 * s  The sampler_comparison type.
 * coords The texture coordinates used for sampling.
 * array_index: The 0-based texture array index to sample.
 * depth_ref The reference value to compare the sampled depth value against.
 * offset
    * The optional texel offset applied to the unnormalized texture coordinate before sampling the texture.
    * This offset is applied before applying any texture wrapping modes.
    * The offset expression must be a creation-time expression (e.g. vec2<i32>(1, 2)).
    * Each offset component must be at least -8 and at most 7.
      Values outside of this range will result in a shader-creation error.
`
  )
  .params(u =>
    u
      .combine('stage', kShortShaderStages)
      .combine('format', kDepthStencilFormats)
      // filter out stencil only formats
      .filter(t => isDepthTextureFormat(t.format))
      .combine('filt', ['nearest', 'linear'] as const)
      .combine('modeU', kShortAddressModes)
      .combine('modeV', kShortAddressModes)
      .combine('offset', [false, true] as const)
      .beginSubcases()
      .combine('samplePoints', kSamplePointMethods)
      .combine('A', ['i32', 'u32'] as const)
      .combine('compare', kCompareFunctions)
      .combine('depthOrArrayLayers', [1, 8] as const)
  )
  .fn(async t => {
    const {
      format,
      stage,
      samplePoints,
      A,
      modeU,
      modeV,
      filt: minFilter,
      compare,
      offset,
      depthOrArrayLayers,
    } = t.params;
    t.skipIfTextureFormatNotSupported(format);

    const [width, height] = chooseTextureSize({ minSize: 16, minBlocks: 4, format });
    const size = { width, height, depthOrArrayLayers };

    const descriptor: GPUTextureDescriptor = {
      format,
      size,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
      mipLevelCount: 3,
      ...(t.isCompatibility && { textureBindingViewDimension: '2d-array' }),
    };
    const { texels, texture } = await createTextureWithRandomDataAndGetTexels(t, descriptor, {
      generator: makeRandomDepthComparisonTexelGenerator(descriptor, compare),
    });
    const sampler: GPUSamplerDescriptor = {
      addressModeU: kShortAddressModeToAddressMode[modeU],
      addressModeV: kShortAddressModeToAddressMode[modeV],
      compare,
      minFilter,
      magFilter: minFilter,
      mipmapFilter: minFilter,
    };

    const calls: TextureCall<vec2>[] = generateTextureBuiltinInputs2D(50, {
      method: samplePoints,
      textureBuiltin: 'textureSampleCompareLevel',
      sampler,
      descriptor,
      derivatives: true,
      arrayIndex: { num: texture.depthOrArrayLayers, type: A },
      depthRef: true,
      offset,
      hashInputs: [stage, format, samplePoints, A, modeU, modeV, minFilter, offset],
    }).map(({ coords, derivativeMult, arrayIndex, depthRef, offset }) => {
      return {
        builtin: 'textureSampleCompareLevel',
        coordType: 'f',
        coords,
        derivativeMult,
        arrayIndex,
        arrayIndexType: A === 'i32' ? 'i' : 'u',
        depthRef,
        offset,
      };
    });
    const textureType = 'texture_depth_2d_array';
    const viewDescriptor: GPUTextureViewDescriptor = { dimension: '2d-array' };
    const results = await doTextureCalls(
      t,
      texture,
      viewDescriptor,
      textureType,
      sampler,
      calls,
      stage
    );
    const res = await checkCallResults(
      t,
      { texels, descriptor, viewDescriptor },
      textureType,
      sampler,
      calls,
      results,
      stage,
      texture
    );
    t.expectOK(res);
  });

g.test('arrayed_3d_coords')
  .specURL('https://www.w3.org/TR/WGSL/#texturesamplecomparelevel')
  .desc(
    `
A is i32 or u32

fn textureSampleCompareLevel(t: texture_depth_cube_array, s: sampler_comparison, coords: vec3<f32>, array_index: A, depth_ref: f32) -> f32

Parameters:
 * t  The depth texture to sample.
 * s  The sampler_comparison type.
 * coords The texture coordinates used for sampling.
 * array_index: The 0-based texture array index to sample.
 * depth_ref The reference value to compare the sampled depth value against.
`
  )
  .params(u =>
    u
      .combine('stage', kShortShaderStages)
      .combine('format', kDepthStencilFormats)
      // filter out stencil only formats
      .filter(t => isDepthTextureFormat(t.format))
      .combine('filt', ['nearest', 'linear'] as const)
      .combine('mode', kShortAddressModes)
      .beginSubcases()
      .combine('samplePoints', kCubeSamplePointMethods)
      .combine('A', ['i32', 'u32'] as const)
      .combine('compare', kCompareFunctions)
  )
  .fn(async t => {
    const { format, A, stage, samplePoints, mode, filt: minFilter, compare } = t.params;
    t.skipIfTextureViewDimensionNotSupported('cube-array');
    t.skipIfTextureFormatNotSupported(t.params.format);

    const viewDimension: GPUTextureViewDimension = 'cube-array';
    const size = chooseTextureSize({ minSize: 8, minBlocks: 2, format, viewDimension });

    const descriptor: GPUTextureDescriptor = {
      format,
      ...(t.isCompatibility && { textureBindingViewDimension: viewDimension }),
      size,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
    };
    const { texels, texture } = await createTextureWithRandomDataAndGetTexels(t, descriptor, {
      generator: makeRandomDepthComparisonTexelGenerator(descriptor, compare),
    });
    const sampler: GPUSamplerDescriptor = {
      addressModeU: kShortAddressModeToAddressMode[mode],
      addressModeV: kShortAddressModeToAddressMode[mode],
      addressModeW: kShortAddressModeToAddressMode[mode],
      compare,
      minFilter,
      magFilter: minFilter,
      mipmapFilter: minFilter,
    };

    const calls: TextureCall<vec3>[] = generateSamplePointsCube(50, {
      method: samplePoints,
      sampler,
      descriptor,
      derivatives: true,
      textureBuiltin: 'textureSampleCompareLevel',
      arrayIndex: { num: texture.depthOrArrayLayers / 6, type: A },
      depthRef: true,
      hashInputs: [stage, format, samplePoints, mode, minFilter],
    }).map(({ coords, derivativeMult, depthRef, arrayIndex }) => {
      return {
        builtin: 'textureSampleCompareLevel',
        arrayIndex,
        arrayIndexType: A === 'i32' ? 'i' : 'u',
        coordType: 'f',
        coords,
        derivativeMult,
        depthRef,
      };
    });
    const viewDescriptor = {
      dimension: viewDimension,
    };
    const textureType = 'texture_depth_cube_array';
    const results = await doTextureCalls(
      t,
      texture,
      viewDescriptor,
      textureType,
      sampler,
      calls,
      stage
    );
    const res = await checkCallResults(
      t,
      { texels, descriptor, viewDescriptor },
      textureType,
      sampler,
      calls,
      results,
      stage,
      texture
    );
    t.expectOK(res);
  });
