Reputation:
I am trying to create a rubiks cube using openGL. Within the code for each individual piece, I want to draw a cube around x, y, z using a matrix. I am wondering how do I draw my cube once I have processed it using glMultMatrix
? Thanks!
class Piece:
def __init__(self, x, y, z, position):
self.x = x
self.y = y
self.z = z
self.matrix = position
def draw(self, axis, slice, dir):
glPushMatrix()
glMultMatrixf(self.matrix)
glBegin(GL_QUADS)
#
# What would go here to draw a cube based off of self.matrix?
#
glEnd()
glPopMatrix()
Upvotes: 1
Views: 878
Reputation: 51845
You just render axis aligned cube centered by (0,0,0)
so set of 4*6=24
glVertex
calls with the combinations of +/-1.0
or any different size. You can extract the vertexes from this example (in newer api)
so the code would be (C++):
const GLfloat vao_pos[]=
{
// x y z //ix
-1.0,+1.0,-1.0, //0
+1.0,+1.0,-1.0, //1
+1.0,-1.0,-1.0, //2
-1.0,-1.0,-1.0, //3
-1.0,-1.0,+1.0, //4
+1.0,-1.0,+1.0, //5
+1.0,+1.0,+1.0, //6
-1.0,+1.0,+1.0, //7
};
const GLuint vao_ix[]=
{
0,1,2,3,
4,5,6,7,
3,2,5,4,
2,1,6,5,
1,0,7,6,
0,3,4,7,
};
glBegin(GL_QUADS);
for (int i=0;i<24;i++) glVertex3dv(vao_pos+3*vao_ix[i]);
glEnd();
or this:
const GLfloat vao_pos[]=
{
// x y z //ix
-1.0,+1.0,-1.0, //0
+1.0,+1.0,-1.0, //1
+1.0,-1.0,-1.0, //2
-1.0,-1.0,-1.0, //3
-1.0,-1.0,+1.0, //4
+1.0,-1.0,+1.0, //5
+1.0,+1.0,+1.0, //6
-1.0,+1.0,+1.0, //7
-1.0,-1.0,-1.0, //3
+1.0,-1.0,-1.0, //2
+1.0,-1.0,+1.0, //5
-1.0,-1.0,+1.0, //4
+1.0,-1.0,-1.0, //2
+1.0,+1.0,-1.0, //1
+1.0,+1.0,+1.0, //6
+1.0,-1.0,+1.0, //5
+1.0,+1.0,-1.0, //1
-1.0,+1.0,-1.0, //0
-1.0,+1.0,+1.0, //7
+1.0,+1.0,+1.0, //6
-1.0,+1.0,-1.0, //0
-1.0,-1.0,-1.0, //3
-1.0,-1.0,+1.0, //4
-1.0,+1.0,+1.0, //7
};
glBegin(GL_QUADS);
for (int i=0;i<24*3;i+=3) glVertex3dv(vao_pos+i);
glEnd();
so just port it to python (I do not code in python) its really just an array and a loop ... you can also hardcode the 24 glVertex
calls without loop ....
Upvotes: 1
Reputation: 1171
A rubik's cube can be organized by an 3 dimensional array of 3x3x3 cubes. It seems to be easy to rotate a slice of the cube, but note if on slice is rotated the positions of the cube change and have to be reorganized. Not only the position changes, also the orientation of the (rotated) single cubes changes.
Check out this answer by rabbid, https://stackoverflow.com/a/54953213/7977581
Its very descriptive. Also he explains it in Python.
Upvotes: 0