Lambda Stack - Demo 16

Objective

Remove repetition in the coordinate transformations, as previous demos had very similar transformations, especially from camera space to NDC space. Each edge of the graph of objects should only be specified once per frame.

Demo 12

Full Cayley graph.

Noticing in the previous demos that the lower parts of the transformations have a common pattern, we can create a stack of functions for later application. Before drawing geometry, we add any functions to the top of the stack, apply all of our functions in the stack to our modelspace data to get NDC data, and before we return to the parent node, we pop the functions we added off of the stack, to ensure that we return the stack to the state that the parent node gave us.

To explain in more detail —

What’s the difference between drawing paddle 1 and the square?

Here is paddle 1 code

src/modelviewprojection/demo14.py
209    GL.glColor3f(*iter(paddle1.color))
210    GL.glBegin(GL.GL_QUADS)
211    for p1_v_ms in paddle1.vertices:
212        ms_to_ndc: mu.InvertibleFunction[mu3d.Vector3D] = mu.compose(
213            [
214                # camera space to NDC
215                mu.uniform_scale(1.0 / 10.0),
216                # world space to camera space
217                mu.inverse(mu.translate(camera.position_ws)),
218                # model space to world space
219                mu.compose(
220                    [
221                        mu.translate(paddle1.position),
222                        mu3d.rotate_z(paddle1.rotation),
223                    ]
224                ),
225            ]
226        )
227
228        paddle1_vector_ndc: mu3d.Vector3D = ms_to_ndc(p1_v_ms)
229        GL.glVertex3f(
230            paddle1_vector_ndc.x, paddle1_vector_ndc.y, paddle1_vector_ndc.z
231        )
232    GL.glEnd()

Here is the square’s code:

src/modelviewprojection/demo14.py
236    # draw square
237    GL.glColor3f(0.0, 0.0, 1.0)
238    GL.glBegin(GL.GL_QUADS)
239    for ms in square:
240        ms_to_ndc: mu.InvertibleFunction[mu3d.Vector3D] = mu.compose(
241            [
242                # camera space to NDC
243                mu.uniform_scale(1.0 / 10.0),
244                # world space to camera space
245                mu.inverse(mu.translate(camera.position_ws)),
246                # model space to world space
247                mu.compose(
248                    [
249                        mu.translate(paddle1.position),
250                        mu3d.rotate_z(paddle1.rotation),
251                    ]
252                ),
253                # square space to paddle 1 space
254                mu.compose(
255                    [
256                        mu.translate(mu3d.Vector3D(x=0.0, y=0.0, z=-1.0)),
257                        mu3d.rotate_z(rotation_around_paddle1),
258                        mu.translate(mu3d.Vector3D(x=2.0, y=0.0, z=0.0)),
259                        mu3d.rotate_z(square_rotation),
260                    ]
261                ),
262            ]
263        )
264        square_vector_ndc: mu3d.Vector3D = ms_to_ndc(ms)
265        GL.glVertex3f(
266            square_vector_ndc.x, square_vector_ndc.y, square_vector_ndc.z
267        )
268    GL.glEnd()

The only difference is the square’s modelspace to paddle1 space. Everything else is exactly the same. In a graphics program, because the scene is a hierarchy of relative objects, it is unwise to put this much repetition in the transformation sequence. Especially if we might change how the camera operates, or from perspective to ortho. It would required a lot of code changes. And I don’t like reading from the bottom of the code up. Code doesn’t execute that way. I want to read from top to bottom.

When reading the transformation sequences in the previous demos from top down the transformation at the top is applied first, the transformation at the bottom is applied last, with the intermediate results method-chained together. (look up above for a reminder)

With a function stack, the function at the top of the stack (f5) is applied first, the result of this is then given as input to f4 (second on the stack), all the way down to f1, which was the first fn to be placed on the stack, and as such, the last to be applied. (Last In First Applied - LIFA)

             |-------------------|
(MODELSPACE) |                   |
  (x,y,z)->  |       f5          |--
             |-------------------| |
                                   |
          -------------------------
          |
          |  |-------------------|
          |  |                   |
           ->|       f4          |--
             |-------------------| |
                                   |
          -------------------------
          |
          |  |-------------------|
          |  |                   |
           ->|       f3          |--
             |-------------------| |
                                   |
          -------------------------
          |
          |  |-------------------|
          |  |                   |
           ->|       f2          |--
             |-------------------| |
                                   |
          -------------------------
          |
          |  |-------------------|
          |  |                   |
           ->|       f1          |-->  (x,y,z) NDC
             |-------------------|

So, in order to ensure that the functions in a stack will execute in the same order as all of the previous demos, they need to be pushed onto the stack in reverse order.

This means that from modelspace to world space, we can now read the transformations FROM TOP TO BOTTOM!!!! SUCCESS!

Then, to draw the square relative to paddle one, those six transformations will already be on the stack, therefore only push the differences, and then apply the stack to the paddle’s modelspace data.

How to Execute

Load src/modelviewprojection/demo16.py in Spyder and hit the play button.

Move the Paddles using the Keyboard

Keyboard Input

Action

w

Move Left Paddle Up

s

Move Left Paddle Down

k

Move Right Paddle Down

i

Move Right Paddle Up

d

Increase Left Paddle’s Rotation

a

Decrease Left Paddle’s Rotation

l

Increase Right Paddle’s Rotation

j

Decrease Right Paddle’s Rotation

UP

Move the camera up, moving the objects down

DOWN

Move the camera down, moving the objects up

LEFT

Move the camera left, moving the objects right

RIGHT

Move the camera right, moving the objects left

q

Rotate the square around its center

e

Rotate the square around paddle 1’s center

Description

Function stack. Internally it has a list, where index 0 is the bottom of the stack. In python we can store any object as a variable, and we will be storing functions which transform a vector to another vector, through the “modelspace_to_ndc” method.

src/modelviewprojection/mathutils3d
277@dataclasses.dataclass
278class FunctionStack:
279    stack: typing.List[mathutils.InvertibleFunction[Vector3D]] = (
280        dataclasses.field(default_factory=lambda: [])
281    )
282
283    def push(self, o: object):
284        self.stack.append(o)
285
286    def pop(self):
287        return self.stack.pop()
288
289    def clear(self):
290        self.stack.clear()
291
292    def modelspace_to_ndc_fn(self) -> mathutils.InvertibleFunction[Vector3D]:
293        return mathutils.compose(self.stack)
294
295
296fn_stack = FunctionStack()

Define four functions, which we will compose on the stack.

Push identity onto the stack, which will will never pop off of the stack.

tests/test_mathutils3d.py
179def test_fn_stack():
180    def identity(x):
181        return x
182
183    mu3d.fn_stack.push(identity)
184    assert 1 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)
185
186    def add_one(x):
187        return x + 1
188
189    mu3d.fn_stack.push(add_one)
190    assert 2 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)  # x + 1 = 2
191
192    def multiply_by_2(x):
193        return x * 2
194
195    mu3d.fn_stack.push(multiply_by_2)  # (x * 2) + 1 = 3
196    assert 3 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)
197
198    def add_5(x):
199        return x + 5
200
201    mu3d.fn_stack.push(add_5)  # ((x + 5) * 2) + 1 = 13
202    assert 13 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)
203
204    mu3d.fn_stack.pop()
205    assert 3 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)  # (x * 2) + 1 = 3
206
207    mu3d.fn_stack.pop()
208    assert 2 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)  # x + 1 = 2
209
210    mu3d.fn_stack.pop()
211    assert 1 == mu3d.fn_stack.modelspace_to_ndc_fn()(1)  # x = 1

Event Loop

src/modelviewprojection/demo16.py
189while not glfw.window_should_close(window):
...

In previous demos, camera_space_to_ndc_space_fn was always the last function called in the method chained pipeline. Put it on the bottom of the stack, by pushing it first, so that “modelspace_to_ndc” calls this function last. Each subsequent push will add a new function to the top of the stack.

\[\vec{f}_{c}^{ndc}\]
Demo 12
src/modelviewprojection/demo16.py
209    # camera space to NDC
210    mu3d.fn_stack.push(mu.uniform_scale(1.0 / 10.0))

Unlike in previous demos in which we read the transformations from modelspace to world space backwards; this time because the transformations are on a stack, the fns on the model stack can be read forwards, where each operation translates/rotates/scales the current space

The camera’s position and orientation are defined relative to world space like so, read top to bottom:

\[\vec{f}_{c}^{w}\]
Demo 12

But, since we need to transform world-space to camera space, they must be inverted by reversing the order, and negating the arguments

Therefore the transformations to put the world space into camera space are.

\[\vec{f}_{w}^{c}\]
Demo 12
src/modelviewprojection/demo16.py
214    # world space to camera space
215    mu3d.fn_stack.push(mu.inverse(mu.translate(camera.position_ws)))

draw paddle 1

Unlike in previous demos in which we read the transformations from modelspace to world space backwards; because the transformations are on a stack, the fns on the model stack can be read forwards, where each operation translates/rotates/scales the current space

\[\vec{f}_{p1}^{w}\]
Demo 12
src/modelviewprojection/demo16.py
219    # paddle 1 model space to world space
220    mu3d.fn_stack.push(
221        mu.compose(
222            [mu.translate(paddle1.position), mu3d.rotate_z(paddle1.rotation)]
223        )
224    )

for each of the modelspace coordinates, apply all of the procedures on the stack from top to bottom this results in coordinate data in NDC space, which we can pass to glVertex3f

src/modelviewprojection/demo16.py
228    GL.glColor3f(*iter(paddle1.color))
229    GL.glBegin(GL.GL_QUADS)
230    for p1_v_ms in paddle1.vertices:
231        paddle1_vector_ndc = mu3d.fn_stack.modelspace_to_ndc_fn()(p1_v_ms)
232        GL.glVertex3f(
233            paddle1_vector_ndc.x,
234            paddle1_vector_ndc.y,
235            paddle1_vector_ndc.z,
236        )
237    GL.glEnd()

draw the square

since the modelstack is already in paddle1’s space, and since the blue square is defined relative to paddle1, just add the transformations relative to it before the blue square is drawn. Draw the square, and then remove these 4 transformations from the stack (done below)

\[\vec{f}_{s}^{p1}\]
Demo 12
src/modelviewprojection/demo16.py
241    mu3d.fn_stack.push(
242        mu.compose(
243            [
244                mu.translate(mu3d.Vector3D(x=0.0, y=0.0, z=-1.0)),
245                mu3d.rotate_z(rotation_around_paddle1),
246                mu.translate(mu3d.Vector3D(x=2.0, y=0.0, z=0.0)),
247                mu3d.rotate_z(square_rotation),
248            ]
249        )
250    )
src/modelviewprojection/demo16.py
253    GL.glColor3f(0.0, 0.0, 1.0)
254    GL.glBegin(GL.GL_QUADS)
255    for ms in square:
256        square_vector_ndc = mu3d.fn_stack.modelspace_to_ndc_fn()(ms)
257        GL.glVertex3f(
258            square_vector_ndc.x,
259            square_vector_ndc.y,
260            square_vector_ndc.z,
261        )
262    GL.glEnd()

Now we need to remove fns from the stack so that the lambda stack will convert from world space to NDC. This will allow us to just add the transformations from world space to paddle2 space on the stack.

src/modelviewprojection/demo16.py
266    mu3d.fn_stack.pop()  # pop off square space to paddle 1 space
267    # current space is paddle 1 space
268    mu3d.fn_stack.pop()  # # pop off paddle 1 model space to world space
269    # current space is world space

since paddle2’s modelspace is independent of paddle 1’s space, only leave the view and projection fns (1) - (4)

draw paddle 2

\[\vec{f}_{p2}^{w}\]
Demo 12
src/modelviewprojection/demo16.py
273    mu3d.fn_stack.push(
274        mu.compose(
275            [mu.translate(paddle2.position), mu3d.rotate_z(paddle2.rotation)]
276        )
277    )
src/modelviewprojection/demo16.py
281    # draw paddle 2
282    GL.glColor3f(*iter(paddle2.color))
283    GL.glBegin(GL.GL_QUADS)
284    for p2_v_ms in paddle2.vertices:
285        paddle2_vector_ndc = mu3d.fn_stack.modelspace_to_ndc_fn()(p2_v_ms)
286        GL.glVertex3f(
287            paddle2_vector_ndc.x,
288            paddle2_vector_ndc.y,
289            paddle2_vector_ndc.z,
290        )
291    GL.glEnd()

remove all fns from the function stack, as the next frame will set them clear makes the list empty, as the list (stack) will be repopulated the next iteration of the event loop.

src/modelviewprojection/demo16.py
295    # done rendering everything for this frame, just go ahead and clear all functions
296    # off of the stack, back to NDC as current space
297    mu3d.fn_stack.clear()
298

Swap buffers and execute another iteration of the event loop

src/modelviewprojection/demo16.py
302    glfw.swap_buffers(window)

Notice in the above code, adding functions to the stack is creating a shared context for transformations, and before we call “glVertex3f”, we always call “modelspace_to_ndc” on the modelspace vector. In Demo 19, we will be using OpenGL 2.1 matrix stacks. Although we don’t have the code for the OpenGL driver, given that you’ll see that we pass modelspace data directly to “glVertex3f”, it should be clear that the OpenGL implementation must fetch the modelspace to NDC transformations from the ModelView and Projection matrix stacks.