5

我正在尝试将该cgmath库集成到我的第一次实验中glium,但我不知道如何将我的Matrix4对象传递给draw()调用。

我的uniforms对象是这样定义的:

let uniforms = uniform! {
    matrix: cgmath::Matrix4::from_scale(0.1)
};

这是我的draw电话:

target.draw(&vertex_buffer, &index_slice, &program, &uniforms, &Default::default())
      .unwrap();

无法与消息一起编译

error[E0277]: the trait bound `cgmath::Matrix4<{float}>: glium::uniforms::AsUniformValue` is not satisfied

我完全是 Rust 的初学者,但我相信我自己无法实现这个特性,因为它和Matrix4类型都在一个与我分开的板条箱中。

真的没有比手动将矩阵转换为浮点数组更好的选择了吗?

4

1 回答 1

7

我确实相信我自己无法实现这个特性,因为它和Matrix4类型都在一个与我分开的板条箱中。

这是非常真实的。

真的没有比手动将矩阵转换为浮点数组更好的选择了吗?

好吧,您不必手动做很多事情。

首先,注意Matrix4<S> 实现Into<[[S; 4]; 4]>是有用的(我不能直接链接到那个 impl,所以你必须使用ctrl+ f)。这意味着您可以轻松地将 aMatrix4转换为 glium 接受的数组。不幸的是,into()只有在编译器确切知道要转换为什么类型时才有效。所以这是一个非工作和工作版本:

// Not working, the macro accepts many types, so the compiler can't be sure 
let uniforms = uniform! {
    matrix: cgmath::Matrix4::from_scale(0.1).into()
};

// Works, because we excplicitly mention the type
let matrix: [[f64; 4]; 4] = cgmath::Matrix::from_scale(0.1).into();
let uniforms = uniform! {
    matrix: matrix,  
};

但是这个解决方案可能仍然太多,无法编写。当我使用cgmathandglium时,我创建了一个辅助特征来进一步减少代码大小。这可能不是最好的解决方案,但它有效并且没有明显的缺点(AFAIK)。

pub trait ToArr {
    type Output;
    fn to_arr(&self) -> Self::Output;
}

impl<T: BaseNum> ToArr for Matrix4<T> {
    type Output = [[T; 4]; 4];
    fn to_arr(&self) -> Self::Output {
        (*self).into()
    }
}

我希望这段代码能自我解释。有了这个特性,你现在只需要调用use附近的特性draw(),然后:

let uniforms = uniform! {
    matrix: cgmath::Matrix4::from_scale(0.1).to_arr(),
    //                                      ^^^^^^^^^
};
于 2016-10-13T18:07:43.280 回答