9. WebGPU 平移变换

本文介绍了如何在图形编程中使用顶点缓冲区和索引缓冲区来构建图形,通过着色器将像素空间转换为裁剪空间,并实现了平移变换。文章提供了一个F形图形的例子,详细展示了如何设置顶点数据、统一缓冲区以及如何在渲染过程中应用平移。最后,通过添加用户界面允许动态调整平移值,展示了图形的实时变换功能。
摘要由CSDN通过智能技术生成

我们将开始编写与顶点缓冲区文章中的示例类似的代码,但这次将绘制单个 F 而不是一堆圆,并使用索引缓冲区来保持数据更小。

让我们在像素空间而不是裁剪空间中工作,就像 Canvas 2D API 我们将制作一个 F,将从 6 个三角形构建它
在这里插入图片描述

这是 F 的数据

function createFVertices() {
  const vertexData = new Float32Array([
    // left column
    0 ,   0, //0
    30,   0, //1
    0 , 150, //2
    30, 150, //3
 
    // top rung
    30 ,  0, //4
    100,  0, //5
    30 , 30, //6
    100, 30, //7
 
    // middle rung
    30, 60,  //8
    70, 60,  //9
    30, 90,  //10
    70, 90,  //11
  ]);
 
  const indexData = new Uint32Array([
    0,  1,  2,    2,  1,  3,  // left column
    4,  5,  6,    6,  5,  7,  // top run
    8,  9, 10,   10,  9, 11,  // middle run
  ]);
 
  return {
    vertexData,
    indexData,
    numVertices: indexData.length,
  };
}

上面的顶点数据在像素空间中,因此需要将其转换为裁剪空间。可以通过将分辨率传递给着色器并进行一些数学运算来做到这一点。下边是操作步骤。

struct Uniforms {
  color: vec4f,
  resolution: vec2f,
};
 
struct Vertex {
  @location(0) position: vec2f,
};
 
struct VSOutput {
  @builtin(position) position: vec4f,
};
 
@group(0) @binding(0) var<uniform> uni: Uniforms;
 
@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  
  let position = vert.position;
 
  // convert the position from pixels to a 0.0 to 1.0 value
  let zeroToOne = position / uni.resolution;
 
  // convert from 0 <-> 1 to 0 <-> 2
  let zeroToTwo = zeroToOne * 2.0;
 
  // covert from 0 <-> 2 to -1 <-> +1 (clip space)
  let flippedClipSpace = zeroToTwo - 1.0;
 
  // flip Y
  let clipSpace = flippedClipSpace * vec2f(1, -1);
 
  vsOut.position = vec4f(clipSpace, 0.0, 1.0);
  return vsOut;
}
 
@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
  return uni.color;
}

使用顶点位置并将其除以分辨率。这给了一个在画布上从 0 到 1 的值。然后乘以 2 以获得画布上从 0 到 2 的值。然后减去 1。现在我们的值在裁剪空间中,但它被翻转了,因为裁剪空间向上 Y 正向,而画布 2d 向下 Y 正向。所以将 Y 乘以 -1 来翻转它。现在有了所需的裁剪空间值,可以从着色器中输出它。

现在只有一个属性,所以渲染管线看起来像这样

  const pipeline = device.createRenderPipeline({
    label: 'just 2d position',
    layout: 'auto',
    vertex: {
      module,
      entryPoint: 'vs',
      buffers: [
        {
          arrayStride: (2) * 4, // (2) floats, 4 bytes each
          attributes: [
            {shaderLocation: 0, offset: 0, format: 'float32x2'},  // position
          ],
        },
      ],
    },
    fragment: {
      module,
      entryPoint: 'fs',
      targets: [{ format: presentationFormat }],
    },
  });

需要为uniforms设置一个缓冲区

  // color, resolution, padding
  const uniformBufferSize = (4 + 2) * 4 + 8;
  const uniformBuffer = device.createBuffer({
    label: 'uniforms',
    size: uniformBufferSize,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
  });
 
  const uniformValues = new Float32Array(uniformBufferSize / 4);
 
  // offsets to the various uniform values in float32 indices
  const kColorOffset = 0;
  const kResolutionOffset = 4;
 
  const colorValue = uniformValues.subarray(kColorOffset, kColorOffset + 4);
  const resolutionValue = uniformValues.subarray(kResolutionOffset, kResolutionOffset + 2);
 
  // The color will not change so let's set it once at init time
  colorValue.set([Math.random(), Math.random(), Math.random(), 1]);

在渲染时需要设置分辨率

  function render() {
    ...
 
    // Set the uniform values in our JavaScript side Float32Array
    resolutionValue.set([canvas.width, canvas.height]);
 
    // upload the uniform values to the uniform buffer
    device.queue.writeBuffer(uniformBuffer, 0, uniformValues);

Before we run it lets make the background of the canvas look like graph paper. We’ll set it’s scale so each grid cell of the graph paper is 10x10 pixels and every 100x100 pixels we’ll draw a bolder line.

在运行它之前,需要让画布的背景看起来像方格纸。将设置它的比例,使方格纸的每个网格单元为 10x10 像素,且每 100x100 像素我们将绘制一条粗线。效果图如下
在这里插入图片描述

:root {
  --bg-color: #fff;
  --line-color-1: #AAA;
  --line-color-2: #DDD;
}
@media (prefers-color-scheme: dark) {
  :root {
    --bg-color: #000;
    --line-color-1: #666;
    --line-color-2: #333;
  }
}
canvas {
  display: block;  /* make the canvas act like a block   */
  width: 100%;     /* make the canvas fill its container */
  height: 100%;
  background-color: var(--bg-color);
  background-image: linear-gradient(var(--line-color-1) 1.5px, transparent 1.5px),
      linear-gradient(90deg, var(--line-color-1) 1.5px, transparent 1.5px),
      linear-gradient(var(--line-color-2) 1px, transparent 1px),
      linear-gradient(90deg, var(--line-color-2) 1px, transparent 1px);
  background-position: -1.5px -1.5px, -1.5px -1.5px, -1px -1px, -1px -1px;
  background-size: 100px 100px, 100px 100px, 10px 10px, 10px 10px;  
}

上面的 CSS 应该处理浅色和深色情况。

到目前为止,所有的示例都使用了不透明的画布。为了使其透明,以便可以看到刚刚设置的背景,需要进行一些更改。

首先需要在配置画布为 ‘premultiplied’ 时设置 alphaMode 。它默认为 ‘opaque’ 。

  context.configure({
    device,
    format: presentationFormat,
    alphaMode: 'premultiplied',
  });

然后需要在 GPURenderPassDescriptor 中将画布清除为 0, 0, 0, 0。因为默认的 clearValue 是 0, 0, 0, 0 可以删除将它设置为其他内容。

  const renderPassDescriptor = {
    label: 'our basic canvas renderPass',
    colorAttachments: [
      {
        // view: <- to be filled out when we render
        //clearValue: [0.3, 0.3, 0.3, 1],
        loadOp: 'clear',
        storeOp: 'store',
      },
    ],
  };

有了这个,这是F的显示结果

在这里插入图片描述

注意 F 相对于它后面的网格的大小。 F 数据的顶点位置使 F 宽 100 像素,高 150 像素,与我们显示的相匹配。 F 从 0,0 开始,向右延伸到 100,0,向下延伸到 0,150

现在已经有了基础,让我们添加平移变换。

Translation is just the process of moving things so all we need to do is add translation to our uniforms and add that to our position
平移变换只是移动事物的过程,所以需要做的就是将平移添加到我们的uniforms 并将其与位置相加

struct Uniforms {
  color: vec4f,
  resolution: vec2f,
  translation: vec2f, //here
};
 
struct Vertex {
  @location(0) position: vec2f,
};
 
struct VSOutput {
  @builtin(position) position: vec4f,
};
 
@group(0) @binding(0) var<uniform> uni: Uniforms;
 
@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  
  // Add in the translation
  //let position = vert.position;
  let position = vert.position + uni.translation;
 
  // convert the position from pixels to a 0.0 to 1.0 value
  let zeroToOne = position / uni.resolution;
 
  // convert from 0 <-> 1 to 0 <-> 2
  let zeroToTwo = zeroToOne * 2.0;
 
  // covert from 0 <-> 2 to -1 <-> +1 (clip space)
  let flippedClipSpace = zeroToTwo - 1.0;
 
  // flip Y
  let clipSpace = flippedClipSpace * vec2f(1, -1);
 
  vsOut.position = vec4f(clipSpace, 0.0, 1.0);
  return vsOut;
}
 
@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
  return uni.color;
}

需要为uniforms 缓冲区增加空间

  // color, resolution, padding
  //const uniformBufferSize = (4 + 2) * 4 + 8;
  // color, resolution, translation
  const uniformBufferSize = (4 + 2 + 2) * 4; //here
  const uniformBuffer = device.createBuffer({
    label: 'uniforms',
    size: uniformBufferSize,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
  });
 
  const uniformValues = new Float32Array(uniformBufferSize / 4);
 
  // offsets to the various uniform values in float32 indices
  const kColorOffset = 0;
  const kResolutionOffset = 4;
  const kTranslationOffset = 6; //here
 
  const colorValue = uniformValues.subarray(kColorOffset, kColorOffset + 4);
  const resolutionValue = uniformValues.subarray(kResolutionOffset, kResolutionOffset + 2);
  const translationValue = uniformValues.subarray(kTranslationOffset, kTranslationOffset + 2); //here

然后需要在渲染时设置平移

  const settings = {
    translation: [0, 0],
  };
 
  function render() {
    ...
 
    // Set the uniform values in our JavaScript side Float32Array
    resolutionValue.set([canvas.width, canvas.height]);
    translationValue.set(settings.translation);//here
 
    // upload the uniform values to the uniform buffer
    device.queue.writeBuffer(uniformBuffer, 0, uniformValues);

最后添加一个 UI,这样就可以调整平移距离

import GUI from '/3rdparty/muigui-0.x.module.js';
 
...
  const settings = {
    translation: [0, 0],
  };
 
  const gui = new GUI();
  gui.onChange(render);
  gui.add(settings.translation, '0', 0, 1000).name('translation.x');
  gui.add(settings.translation, '1', 0, 1000).name('translation.y');

现在添加了平移

在这里插入图片描述

请注意它与我们的像素网格相匹配。如果我们将平移设置为 200,300,则绘制 F 时其 0,0 左上角顶点位于 200,300。

这篇文章可能看起来非常简单。尽管我们将其命名为“offset”,但之前已经在几个示例中使用了平移。本文是系列文章的一部分。虽然它很简单,但希望它的要点在我们继续本系列的上下文中有意义。

接下来是旋转。

原文地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值