我正在尝试将4x4矩阵传递给glUniformMatrix4fv
,但找不到最后一位。我通过直接输入16个值来创建4x4。 glUniformMatrix4fv
,但UnsafePointer<GLfloat>!
作为最后一个参数除外
var proj = GLKMatrix4(m: (
-1.1269710063934326,
0.0,
-1.380141455272968e-16,
0.0,
0.0,
0.800000011920929,
0.0,
0.0,
0.0,
-0.0,
0.0,
-4.950000286102295,
-1.2246468525851679e-16,
0.0,
1.0,
5.050000190734863)
)
var loc = GLint(_locations.uniforms.projection)
var f = GLboolean(GL_FALSE)
第一次尝试:
glUniformMatrix4fv(loc, 1, f, proj.m)
加薪
Cannot convert value of type '(Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)' to expected argument type 'UnsafePointer<GLfloat>!'
第二次尝试:
glUniformMatrix4fv(loc, 1, f, &proj.m)
加薪
Cannot convert value of type '(Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)' to expected argument type 'GLfloat' (aka 'Float')
第三次尝试
glUniformMatrix4fv(loc, 1, f, &proj)
加薪
Cannot convert value of type 'GLKMatrix4' (aka '_GLKMatrix4') to expected argument type 'GLfloat' (aka 'Float')
最后
glUniformMatrix4fv(loc, 1, f, proj)
加薪
Cannot convert value of type 'GLKMatrix4' (aka '_GLKMatrix4') to expected argument type 'UnsafePointer<GLfloat>!'
任何想法?
最佳答案
“问题”是像
float m[16];
struct _GLKMatrix4
中的代码作为元组映射到Swift:public var m: (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)
但是
glUniformMatrix4fv()
函数需要UnsafePointer<GLfloat>
(C中的float *
)作为最后一个参数。在C语言中,数组在传递时会“衰减”到第一个元素的指针
功能,但在Swift中没有。但是Swift保留了内存布局
导入的C结构,因此您可以将指针传递给元组,
转换为
GLfloat
的指针:// Swift 2:
withUnsafePointer(&proj.m) {
glUniformMatrix4fv(loc, 1, f, UnsafePointer($0))
}
// Swift 3/4:
let components = MemoryLayout.size(ofValue: proj.m)/MemoryLayout.size(ofValue: proj.m.0)
withUnsafePointer(to: &proj.m) {
$0.withMemoryRebound(to: GLfloat.self, capacity: components) {
glUniformMatrix4fv(loc, 1, f, $0)
}
}