0

我使用 wgpu 作为我的项目的图形后端。

这是我目前的实现:

pub fn draw_line(
    points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
    let mut vertices: Vec<Vertex> = Vec::new();
    let mut indices: Vec<u16> = Vec::new();

    let w = WIDTH / 2.0;

    let x1 = points[0][0];
    let x2 = points[1][0];
    let y1 = points[0][1];
    let y2 = points[1][1];

    let color: [f32; 3] = [1.0, 1.0, 1.0];

    vertices.push(Vertex { position: [x1,  y1 - w, 0.0],   color });
    vertices.push(Vertex { position: [x1,  y1 + w, 0.0],   color });
    vertices.push(Vertex { position: [x2,  y2 + w, 0.0],   color });
    vertices.push(Vertex { position: [x2,  y2 - w, 0.0],   color });

    indices.push(2);
    indices.push(1);
    indices.push(0);
    indices.push(2);
    indices.push(0);
    indices.push(3);

    return (vertices, indices);
}

但是当试图在 2 个点之间画一条线时,线的宽度相对于这些点的高度差会发生扭曲。并且 point1 的 X 和 Y 值必须小于 point2 上的值,否则它们不会显示,因为 wgpu 需要顺时针或逆时针正面

line_1 line_2

对于 2 点之间的一条线,是否有更好的函数可以返回顶点和索引

4

1 回答 1

1

未经测试但应该可以工作:

pub fn draw_line(
    points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
    let mut vertices: Vec<Vertex> = Vec::new();
    let mut indices: Vec<u16> = Vec::new();

    let w = WIDTH / 2.0;

    let x1 = points[0][0];
    let x2 = points[1][0];
    let y1 = points[0][1];
    let y2 = points[1][1];

    let color: [f32; 3] = [1.0, 1.0, 1.0];

    let dx = x2 - x1;
    let dy = y2 - y1;
    let l = dx.hypot (dy);
    let u = dx * WIDTH * 0.5 / l;
    let v = dy * WIDTH * 0.5 / l;

    vertices.push(Vertex { position: [x1 + v,  y1 - u, 0.0],   color });
    vertices.push(Vertex { position: [x1 - v,  y1 + u, 0.0],   color });
    vertices.push(Vertex { position: [x2 - v,  y2 + u, 0.0],   color });
    vertices.push(Vertex { position: [x2 + v,  y2 - u, 0.0],   color });

    indices.push(2);
    indices.push(1);
    indices.push(0);
    indices.push(2);
    indices.push(0);
    indices.push(3);

    return (vertices, indices);
}
于 2021-08-16T14:56:30.833 回答