在 OpenGL ES 中構建 3D 物件時,所有複雜模型最終都會拆解為三角形。以常見的幾何體為例:
要讓 3D 物件繞自身軸心旋轉,關鍵在於將物件的幾何中心固定在世界座標系的原點 (0,0,0)。此外,OpenGL ES 預設採用逆時針(CCW)繞序作為正面,建立頂點陣列時必須遵循此規則,否則會因背面剔除導致面片不顯示。
void glDrawArrays(GLenum mode, GLint first, GLsizei count);
參數說明:
GL_POINTS、GL_LINES、GL_LINE_LOOP、GL_LINE_STRIP、GL_TRIANGLES、GL_TRIANGLE_STRIP、GL_TRIANGLE_FAN。使用 GL_TRIANGLE_STRIP 可大幅減少頂點數據量:
// 繪製三角錐:4 個面,每面 3 頂點
for (int i = 0; i < 4; i++) {
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, i * 3, 3);
}
// 繪製立方體:6 個面,每面用 4 頂點構成 Triangle Strip
for (int i = 0; i < 6; i++) {
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, i * 4, 4);
}
此處使用定點數(Fixed Point),以 0x10000 代表 1.0f:
int one = 0x10000; // 1.0f 的定點數表示
// 四稜錐頂點陣列 (12 頂點 × 3 座標 = 36 個整數)
private IntBuffer pyramidBuffer = IntBuffer.wrap(new int[]{
// 面 1
0, one, 0, // 頂點
-one, -one, 0, // 左下
one, -one, one, // 右下
// 面 2
0, one, 0,
one, -one, one,
one, -one, -one,
// 面 3
0, one, 0,
one, -one, -one,
-one, -one, -one,
// 面 4
0, one, 0,
-one, -one, -one,
-one, -one, one
});
// 立方體頂點陣列 (24 頂點 × 3 座標 = 72 個整數)
// 依序為:上、下、前、後、左、右六個面的 Triangle Strip 頂點
private IntBuffer cubeBuffer = IntBuffer.wrap(new int[]{
// 上面
one, one, -one, -one, one, -one, one, one, one, -one, one, one,
// 下面
one, -one, one, -one, -one, one, one, -one, -one, -one, -one, -one,
// 前面
one, one, one, -one, one, one, one, -one, one, -one, -one, one,
// 後面
one, -one, -one, -one, -one, -one, one, one, -one, -one, one, -one,
// 左面
-one, one, one, -one, one, -one, -one, -one, one, -one, -one, -one,
// 右面
one, one, -one, one, one, one, one, -one, -one, one, -one, one
});
提示:實際開發中建議改用浮點數(FloatBuffer)並搭配 VBO(Vertex Buffer Object)以提升效能,定點數僅為早期無 FPU 設備的相容方案。