OpenGL の基礎のいくつかを学ぶために、このレポの Objective-C コードを Swift に翻訳しています。私はそれにまったく新しいです。フローティング長方形を使用して作業中の NSOpenGLView をコンパイルして生成する作業中のプロジェクトがありますが、色が間違っています。glVertexAttribPointer
問題を頂点とカラー データを指す関数の使用に絞り込みました。
頂点と色のデータを保存する方法は次のとおりです。
struct Vertex {
var position: (x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat)
var color: (r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat)
}
struct Vertices {
var v1: Vertex
var v2: Vertex
var v3: Vertex
var v4: Vertex
}
var vertexData = Vertices(
v1: Vertex( position: (x: -0.5, y: -0.5, z: 0.0, w: 1.0),
color: (r: 1.0, g: 0.0, b: 0.0, a: 1.0)),
v2: Vertex( position: (x: -0.5, y: 0.5, z: 0.0, w: 1.0),
color: (r: 0.0, g: 1.0, b: 0.0, a: 1.0)),
v3: Vertex( position: (x: 0.5, y: 0.5, z: 0.0, w: 1.0),
color: (r: 0.0, g: 0.0, b: 1.0, a: 1.0)),
v4: Vertex( position: (x: 0.5, y: -0.5, z: 0.0, w: 1.0),
color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0)) )
glVertexAttribPointer
翻訳しようとしている関数の Objective-C バージョンは次のようになります。
glVertexAttribPointer((GLuint)positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)offsetof(Vertex, position));
glVertexAttribPointer((GLuint)colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)offsetof(Vertex, colour ));
Objective-C バージョンでは、offsetof
マクロを使用して、これらの関数のポインター パラメーターを設定します。Swift はマクロを許可していないので、その代わりに何を使用するかを考えています。私はnil
次のように を渡そうとしました:
glVertexAttribPointer(GLuint(positionAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), nil)
glVertexAttribPointer(GLuint(colorAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), nil)
しかし、そうすると、カラー データ配列は位置データで満たされます。オフセットは考慮されないため、位置と色の両方の属性に位置データが使用されます。
次のように、使用を提案するこのスタックオーバーフローの回答を見つけwithUnsafePointer
て試してみました。
withUnsafePointer(&vertexData.v1.position) { ptr in
glVertexAttribPointer(GLuint(positionAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), ptr)
}
withUnsafePointer(&vertexData.v1.color) { ptr in
glVertexAttribPointer(GLuint(colorAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), ptr)
}
しかし、それはディスプレイ全体をクラッシュさせ、強制シャットダウンと再起動を必要とします.
次に何を試せばよいかわかりません。私が取り組んでいる完全なコードは、こちらから入手できます。
編集:
また、次のように、最初のデータ ポイントへのポインターを取得して 4GLfloat
秒進めてみました。
let ptr = UnsafePointer<GLfloat>([vertexData.v1.position.x])
glVertexAttribPointer(GLuint(positionAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), ptr)
glVertexAttribPointer(GLuint(colorAttribute), 4, UInt32(GL_FLOAT), UInt8(GL_FALSE), GLsizei(sizeof(Vertex)), ptr.advancedBy(4))
ディスプレイはクラッシュしませんが、画面には何も描画されません。