ExerciseFocus
0. GravityApplying C fundamentals to a larger, simulation-style exercise.
1. PoolApplying C fundamentals to a larger, game-like simulation exercise.
2. CPUSimulate a CPU using structs, arrays, and pointers

Getting Started

This Volume is optional and ungraded. All test cases are public.
Get the Volume code through Entainer and the cs1010 command,
then work in 0-gravity, 1-pool, or 2-cpu.
Implement your functions in student.c.
We handle the graphics, input, output, and setup in main.c.

0. Gravity

Focus

Applying C fundamentals to a larger, simulation-style exercise.

Introduction

Have you ever wondered how scientists write simulations that they base some of their predictions on? Well, wonder no more! Because we’re going to write one ourselves! Don’t worry, we’ve done most of the work and all you’ll have to do is implement the formula that we’ve mentioned. We’ll explain Newton’s formula in the next section for some context but you won’t have to understand it. All you’ll have to do is translate what we need, into math.

A simulation of the solar system

In case you really are curious, we have additional sections that explain how the overarching program works (the parts that we’ve implemented for you), as well as how the program flow goes. But if you just want to see planets (and Pluto) whizzing about the Sun, go ahead and read the next section where we first explain the derivation of the formula, and subsequently what you should see in the code.

Exercise Details

Vector Form of Newton’s Law of Universal Gravitation

So everyone’s probably at least somewhat familiar with the following formula for gravity between two bodies and :

where is the universal constant, is the mass of the first body, is the mass of the second body, and is the distance between the two bodies.

But what’s missing here is the direction of the force acting on the bodies. For example, if we have two bodies placed at and respectively, then the force that represents the gravitational force acting on body 1 should:

  • Be oriented from towards

  • Be as long as

To get the orientation of the vector, simply consider the vector: For example, consider the vector .

The issue here is that the vector does not necessarily have the length we want. In our example, the vector has a length of , whereas if the first item had a mass of , and the second item had a mass of , we want it to have a length of .

So how do we do this? We scale the vector we have by

So in general, if is the length of the vector , then to scale it, we want:

And if we wanted the acceleration of body , then since we know that the force acting on body is given as , then the acceleration acting on body is given as:

But what about if we had multiple bodies in the solar system instead of just 2? How does it work then?

Let be the body with:

  • Mass

  • Position

Then we know the force acting on body due to body is given as: where is the distance between body and body .

Then, if we had , bodies , the resultant force acting on body due to all bodies is given as:

Now, it turns out that for our simulation, we don’t really want the force, we want the acceleration only. For that reason, since we know (or Newton knows) that the force acting on an object where is the acceleration on that object, this means that the acceleration is just given as .

Your Task

Implement the gravity formula for each body in the simulation. To put simply, this means that to compute the acceleration of the body, we just need to actually compute the following:

Notice the term is now removed from the formula.

In 0-gravity/student.c, implement:

void compute_accelerations(Body const bodies[NUM_BODIES],
                           Point accelerations[NUM_BODIES]);
void compute_next_positions(Body bodies[NUM_BODIES], double dt);

compute_accelerations fills every output element without changing bodies.
compute_next_positions uses those accelerations in the Verlet step below.
Compute all next positions from the same old state before updating any body.
Keep mass, drawing radius, and colours unchanged.
You may assume finite coordinates, distinct body positions, nonnegative masses,
and a finite, nonnegative dt.
You may add your own vector helpers in student.c.
support.c handles the elapsed-time display and changes to the time step.

Running and Testing

  • To compile: run make in 0-gravity
  • To run the graphical simulation: run ./gravity
  • To test your functions without a display: run make test

For example, two bodies on the same horizontal line attract each other along that line.
With all masses zero, acceleration is zero, and the Verlet update continues each body’s existing motion.
The public tests include unequal masses, translated coordinates, and simultaneous position updates.

Writing a Discrete Simulation

Let’s talk about writing a discrete simulation. While physicists and philosophers might still be arguing about whether the universe is discrete or not, fret not! As of the time of writing this page, computers operate discretely, so that’s how we need to simulate anything at all.

In this particular simulation, what we care about is showing each planet (and Pluto) at their positions at all time steps. To do so, we need their mass and positions to calculate what exactly is the direction and magnitude of the force acting on them.

Think of it this way: We will take into account the state of the solar system at time steps to compute the state of the solar system at time step . We are going to assume a discrete time step duration of . You can think of it as basically saying we are trying to infer what the state of the solar system is at time , based on what we know about it from time and .

Okay, so that’s the high level idea, but what should we do concretely?

Verlet Integration

We’re going to do something called Verlet integration! (We don’t know whether you feel like this is a cool thing or not because we’re just a web page, but we hope the nerd in you is excited.)

Let’s talk about how to update the state of any specific body . Firstly, let’s mention the state we keep track of for Verlet Integration. For each body, we store its:

  • Position , as a 2D coordinate

  • Previous position , as a 2D coordinate

To update the state of a body is to update the two values that it has. But how do we do that? Using the following steps:

  • Compute the current resultant gravitational acceleration (Not force!) acting on the body using every other bodies current position

  • Compute the next position using the following formula:

  • Save current position as old position

  • Save next position as current position

The Specifications

Okay, let’s get into the code. In student.h you’ll see the following code:

typedef struct Point {
    double x, y;
} Point;
 
typedef struct {
    double mass;
    Point curr_pos;
    Point prev_pos;
    double draw_r;
    double color[3];
} Body;
 
typedef struct {
    unsigned int years;
    unsigned int days;
} Duration;

To explain the structs we have here:

  • Point represents a point (or a vector, it’s the same)

  • Body represents a body in the solar system we need to simulate. For the purposes of implementing our formulae, mass, curr_pos, and prev_pos are the relevant pieces of data. The other members/fields of the Body struct are relevant for drawing it on the screen, so they can be left alone

  • Duration is how we represent the count of how many years and days have elapsed since we started the simulation

Helper Functions

You may or may not choose to use the helper functions in the subsequent parts.

(Optional) How The Simulation Works, In Case You’re Curious

So here’s the big picture of the program flow (beyond what we’re getting you to write).

The rough idea is something like this:

  • Start with some initial state

  • Find the next state that we should have

  • Update the state

  • Show/Draw the state on the screen

  • Rinse and repeat from step 2

And that’s pretty much it! All we did was write the frontend and hook up all the buttons and inputs to what they needed to do, and wrote the loop that calls the code that updates the state.

(Optional) Time Elapsed Display

One thing you might have noticed in support.c is the function Duration seconds_to_duration(double seconds_elapsed) which takes the amount of simulated seconds elapsed and converts it to years and days to show on the screen.

For convenience we’ve made some assumptions about how many seconds there are in a day and how many seconds there are in a year. If you’d like, you can try updating it based on more accurate formulae and see how that might change in the display!


1. Pool

Focus

Applying C fundamentals to a larger, game-like simulation exercise.

Introduction

In this exercise, we’ll get you to write the physics for a simple pool game. Along the way, you’ll be implementing some formulae, and making a few if-else statements.

Pool game preview
Don’t worry about how the whole program works, we’ve done most of the heavy lifting for you, all you have to do is implement the collision physics. We’ll walk you through it. In the Exercise Details section, we’ll give details on what type of collisions there are, and how the physics works. We’ll then explain the relevant portions of the code you should make use of, and also implement.

Running and Testing

  • To compile: run make in 1-pool
  • To run the graphical game: run ./pool
  • To test your functions without a display: run make test

Your Task

In 1-pool/student.c, implement ball_move, ball_ball_collision,
ball_wall_collision, and in_ball_pocket, declared in student.h below.
Each function returns the updated ball; it does not change its arguments.
Keep the ball’s type unchanged.
A pocketed ball remains unchanged, except that in_ball_pocket may mark a ball pocketed.
You may assume finite coordinates and velocities.
The collision rules and examples below define the simplified physics we use.

How the Game Works

The objective of the game is to knock all the 10 red balls, into any of the 6 pockets. You can only do so using the cue ball (the white ball). If you knock the cue ball into the pocket, just click on anywhere else on the table and it will place the cue ball back on where you clicked.

To move the cue ball, long click on the cue ball then drag the mouse as if you’re slingshotting it. Then release the mouse button and the cue ball will move in the opposite direction of where you dragged, and the speed is determined by how far you’ve dragged. The further you’ve dragged, the faster and further the cue ball will travel.

Dragging the cue ball

Exercise Details

To simulate the physics for each ball, there are a few cases that we need to deal with:

  • Straight-line movement (when the balls aren’t colliding with anything)

  • Ball to wall collision

  • Ball and ball collision

  • Ball falling into pocket

State Representation in C, and Program Flow

To understand how to even write the physics for the simulation, we must first talk about what the state is, and how our state is represented in C code. Each ball has a position, and a velocity, a type (to indicate if it’s a cue ball or otherwise), and whether it’s pocketed or not.

typedef enum BallType { CUE, RED } BallType;
 
typedef struct {
    Point pos;
    Velocity vel;
    bool in_pocket;
    BallType type;
} Ball;

where Point and Velocity are defined as the following:

typedef struct Point {
    double x, y;
} Point;
typedef Point Velocity;

Initially, every ball has a velocity of 0, and is not in any pocket. (And their position is initialised accordingly.) The cue ball’s type is CUE whereas the other balls are considered RED. Lastly, every ball has radius defined by BALL_RADIUS in student.h.

The program flow is pretty much just confined to a simple loop that looks something like this:

  • Display the current state of all the current balls

  • For each ball, compute its next state. (Based on the physics explained in the subsections)

  • Save the next state that we computed as the current state

  • Rinse and repeat from step 1 again

Every step of the simulation is also referred to as a tick. To simulate the next time step, we need to pretend that some small but non-zero time duration has elapsed. This is defined in student.h as TIME_STEP.

Each tick we will call each of the following functions:

Ball ball_move(Ball ball);
Ball ball_ball_collision(Ball main, Ball other);
Ball ball_wall_collision(Ball main);
Ball in_ball_pocket(Ball ball, Point pock1, Point pock2, Point pock3,
                    Point pock4, Point pock5, Point pock6);

Your Task

Implement each function so that it handles different cases of the simulated physics.

Straight line movement

So what happens if a ball is moving? I.e. what happens if the velocity of a ball is non-zero? How should we update the position? Let’s say that a ball has position , has velocity , what happens after duration ? (Assuming that all the units line up, we’re not physicists.)

Movement Formula

The next position is given as . So in particular, and .

The issue with this is that if we let this simulation run, the balls will never slow down and stop moving. Which doesn’t sound very realistic.

So what we will also do is update the velocity and reduce it every tick. So we have a magic constant as our multiplier, named FRICTION. So every tick, is updated to . (Defined in student.h.)

So to implement Ball ball_move(Ball ball), here’s the exact program behaviour we want:

  • If ball is in the pocket, just simply return the value itself. Otherwise,

  • Firstly, update ball.pos (based on Movement formula, using ball.pos, ball.vel and TIME_STEP)

  • Secondly, update ball.vel by multiplying its and values by

  • Set each velocity component whose absolute value is below MINIMUM_THRESHOLD to zero

  • Lastly, return resulting ball

Ball vs Wall Collision

How does the program decide when a ball has collided with a wall? We make use of the position (stored in pos) and the radius (defined by BALL_RADIUS) to figure that out.

Ball distance from wall
For example, to see if a ball is colliding with the wall on the right, we need to see if pos.x + ball_radius has exceeded TABLE_WIDTH. If it has, that is considered as a collision.

Now, the desired behaviour we want out of the collision is that it should “bounce” off the wall. Here’s an example if we were bouncing against a wall on the right. Then the final resulting ball that we need to return is such that:

  • Let’s say the ball was going to move dx units to the right. Then instead make the resulting ball BALL_RADIUS + dx units away from the wall (at TABLE_WIDTH)

  • Let’s say the ball was going to move dy units either upwards or downwards. Then keep this and the resulting ball should move dy units either upwards or downwards

  • Reverse the component of the velocity of the ball, but keep the component of the velocity of the ball

To compute it, we’ll first simulate the ball moving at its current velocity (call that next_ball), then say we know it is colliding with the right wall (i.e. the -coordinate of next_ball is more than TABLE_WIDTH - BALL_RADIUS).

An example of C code that handles this case is given below:

Ball tick_ball = to_return; // Simulate one tick
double dx = to_return.vel.x * TIME_STEP;
double dy = to_return.vel.y * TIME_STEP;
tick_ball.pos.x = to_return.pos.x + dx;
tick_ball.pos.y = to_return.pos.y + dy;
// if colliding with right wall
if (tick_ball.pos.x > TABLE_WIDTH - BALL_RADIUS) {
    to_return.pos.x = (TABLE_WIDTH - BALL_RADIUS) - dx;
    to_return.pos.y = tick_ball.pos.y;
    to_return.vel.x = -to_return.vel.x;
}
return to_return;

Example implementation of bouncing against the right wall.

At a corner, handle both colliding walls independently, keeping both corrected coordinates and reversing both velocity components.

There are 4 cases to handle in total: Bouncing against the top/bottom or left/right walls. This logic is left for you to implement in the body of function Ball ball_wall_collision(Ball main) in student.c, where the function should return the resulting ball if there is a bounce. If there is no bounce, just return the ball by itself (don’t move it or change anything about it).

Ball vs Ball Collision

How does the program decide when a ball has collided with a ball? This is slightly different from how we would handle collision with a wall. To decide if two balls have collided, we need to check if the distance they have from each other is at most the diameter (or 2 times the radius) of the balls.

Once we’ve decided they are indeed colliding, we need to alter the velocity. The function we’ve provided has the following signature: Ball ball_ball_collision(Ball main, Ball other). The way that it works is that it takes in two balls as input, and returns the resulting state of the main ball.

Let’s talk about how to compute the resulting ball. There are some complicated ways to do this, some involve trigonometric functions, but we’ll give a formula that dodges certain issues (like particles clumping together). We won’t talk too much about why the math works, but rather just what the formula is that you need to implement. Also some vague idea as to why it works, but really all you have to do is implement in C what we’re specifying in math.

Firstly, if either ball is already in a pocket, then just return main as-is. Otherwise, if a ball is in a pocket, it might knock away other balls that are headed to the same pocket.

Otherwise, we need to compute a few vectors. Conceptually here’s the math:

  • Let be the position vector for main, and be the position vector for other

  • Let be the velocity vector for main, and be the velocity vector for other

So based on this, let . Think of this as the displacement vector that moves from other to main. Also let . Think of this as the relative velocity vector from main to other.

Secondly, if the distance between main and other is greater than BALL_RADIUS, they are not close enough so just return main. (The distance can be computed as .)

If the two centres coincide, return main unchanged because there is no collision direction.
Otherwise, we know they are colliding, and if they are, we need to compute the new resulting velocity of main. To do so:

  • Let

  • If , don’t do anything and return main

  • Otherwise, compute

  • Set as the new velocity of main, and return main

Pocket Physics: It’s Not Rocket Physics!

Lastly, let’s talk about pocket physics, this one should be relatively simple. There are 6 pockets, and as long as the distance from its centre to any pocket is strictly less than POCKET_RADIUS, return the same ball but with in_pocket set to true.


2. CPU

Focus

Arrays, strings, structs, and pointers in a CPU-style simulation task.

Introduction

In this task you’re gonna implement a basic virtual CPU. It won’t be entirely realistic, but it’ll convey most of the basic idea across.

For this optional project, we’re going to try something a little different (because eventually you’ll have to do more of this on your own): We’re going to get you to implement most of the program yourself. Also, we may not be as direct/clear as we might otherwise be.

This means that you might take some time to finish this project for CS1010. We encourage you to work through it; the concepts will be useful in your later courses.

Your Task

In 2-cpu/student.c, implement parse_instruction, read_instructions, and
simulate. You may add solution helpers there. student.h defines the shared
types; main.c handles setup, output, cleanup, and get_input_line.

You’ll be given as input a sequence of “assembly instructions” (we’ll specify the format). You’ll have to simulate how these instructions execute on a “CPU” that has 8 registers, along with memory that can hold 16 ints. At the end, we will print out the state of the registers and memory.

Note

We’ll give only valid CPU instructions (all registers and numbers will follow what the CPU has), and valid offsets for branches (each taken branch targets an instruction in the program). Integer arithmetic results fit in int; division never overflows. You may assume allocations succeed and a program eventually terminates or divides by zero. Input ends at EOF or an empty line, and the last line need not end with a newline. An empty program terminates successfully.

Background on How CPUs, Registers, and Memory Work

We’ll try to give you some background here on what it means to “simulate a CPU”.

CPU architecture diagram

Basic Computer Architecture

A computer has three main parts that work together (see the figure above, as an expansion of the ideas we’ve been describing in CS1010):

  • CPU (Central Processing Unit): This is the “brain” of the computer. It uses its Arithmetic/Logic Unit (ALU) to execute instructions, where the instructions themselves are stored in Memory
  • Memory (RAM): This is a storage area outside the CPU (storing 16 ints in this exercise) (This would be described in bytes, typically, but we’re simplifying registers and memory to hold ints.). It holds all the data and instructions for your program. The CPU can execute instructions (code) that are inside the memory, but the actual data required for the instructions have to be inside registers
  • Registers: These are small, fast storage spaces inside the CPU. They hold the values that the CPU is working with right now. For this exercise, imagine there are 8 registers, and their names are 0, 1, 2, 3, 4, 5, 6, 7 respectively. Each can store one int. Importantly, a CPU can only do operations on values in registers, not directly on values in memory!

In this exercise, you will read instructions from a text file and simulate how our basic computer will “run” them step by step. Each instruction tells the CPU what to do with the registers and memory.

What Is an Instruction?

An instruction is a command that tells the CPU what operation to perform. Each instruction consists of an operation code (opcode) and operands. The opcode specifies the operation (like ADD, SUB, LOAD, etc.), and the operands specify the registers, memory addresses, or “immediate” (constant values) involved in the operation.

Here are the instructions you’ll need to implement (REG refers to a register, REG1 and REG2 for e.g., are just to differentiate the operands (not referring specifically to Register 1 and 2), ADDR refers to an address in RAM):

  • ADD REG1 REG2 REG3: Adds the values in REG1 and REG2, and stores the result in REG3
  • SUB REG1 REG2 REG3: Subtracts the value in REG2 from REG1, and stores the result in REG3
  • MUL REG1 REG2 REG3: Multiplies the values in REG1 and REG2, and stores the result in REG3
  • DIV REG1 REG2 REG3: Divides the value in REG1 by the value in REG2, and stores the result in REG3. Note that this is an integer division. If a divide-by-zero occurs, this is a hardware fault, and no further instructions should be executed
  • LOAD REG1 ADDR: Loads the value from memory address ADDR into REG1
  • STORE REG1 ADDR: Stores the value from REG1 into memory address ADDR
  • LOADIMM REG1 VAL: Loads the constant (“immediate”) value VAL into REG1
  • STOREIMM ADDR VAL: Stores the constant (“immediate”) value VAL into memory address ADDR
  • BNQ REG1 REG2 OFFSET: If the values in REG1 and REG2 differ, jump by OFFSET instructions; otherwise continue to the next instruction
  • BEQ REG1 REG2 OFFSET: If the values in REG1 and REG2 are equal, go to and start executing the instruction that is OFFSET instructions away (positive OFFSET means jump forward, negative means jump backward)

Each instruction will be represented as a line in the input text file, and by default your program will read and execute them one after the other, simulating how a CPU processes instructions.

Example of Instruction Execution

Let’s say we have the following instructions in our input file:

LOADIMM 0 10
LOADIMM 1 20
ADD 0 1 2
STORE 2 10
BEQ 0 1 2
LOADIMM 3 99
STORE 3 12

Here’s how the CPU (and therefore you) would execute these instructions step by step:

  • LOADIMM 0 10: Load the immediate value 10 into register 0. (REG0 = 10). What you need to do: update register 0 with the value 10
  • LOADIMM 1 20: Load the immediate value 20 into register 1. (REG1 = 20). What you need to do: update register 1 with the value 20
  • ADD 0 1 2: Add the values in REG0 and REG1, and store the result in REG2. (REG2 = REG0 + REG1 = 10 + 20 = 30). What you need to do: update register 2 with the sum of registers 0 and 1
  • STORE 2 10: Store the value from REG2 into memory address 10. (Memory[10] = REG2 = 30). What you need to do: update memory address 10 with the value from register 2
  • BEQ 0 1 2: Check if the values in REG0 and REG1 are equal. Since , we do not jump. What you need to do: check if registers 0 and 1 are equal; if they are, since the OFFSET is 2, skip the very next instruction, and execute the one after it. In this case, since , you’ll continue executing the very next instruction
  • LOADIMM 3 99: Load the immediate value 99 into register 3. (REG3 = 99). What you need to do: update register 3 with the value 99
  • STORE 3 12: Store the value from REG3 into memory address 12. (Memory[12] = REG3 = 99). What you need to do: update memory address 12 with the value from register 3

Note that after each instruction is done executing, you should automatically execute the next one in the list. The only exceptions are: a divide-by-zero hardware fault, and BEQ or BNQ, where you may have to execute an instruction not immediately after the current one. Once you’ve reached the end of the instruction list, you’re done!

Code

So we’ll sketch out the rough flow of the program, but as you work on this project you should try planning through this and discussing with your TA if need be.

There are a few aspects you’ll need to think about.

  • The phases between the program
  • How to represent the entire virtual machine

Phases

Generally, the program runs in 2 phases. In the first phase, the program has to read the assembly instructions into some kind of readable format. Then from there, it has to run through the sequence of parsed instructions, tracking how the machine’s state changes as it runs through the instructions.

Representing the Data We Care About

We’ve broken down the representation into 3 rough categories:

  • The instructions (which is just an array of Instruction)
  • The CPU (which is just an array of 8 integers, each being a single register)
  • The RAM (which is just an array of 16 integers, each being a single “address”)

Now the most interesting thing here is how to represent an instruction. In particular, we need to read a string (which is a char *) into a struct (which is an Instruction).

An instruction has a type and 2 or 3 arguments, so we’re going to choose to represent that with a struct like so:

typedef struct Instruction {
  InstructionType instruction_type;
  int arg1;
  int arg2;
  int arg3;
} Instruction;

Okay.. so the arguments are stored as integers… that makes sense. But what about the type? We’re going to use something you haven’t seen (which isn’t so fancy deep down), which is an enum type (No, you don’t have to know this for the finals).

So if we pop open the code that defines InstructionType:

typedef enum InstructionType {
  BRANCH_EQ = 0,
  BRANCH_NEQ,
  ADD,
  SUB,
  MUL,
  DIV,
  LOAD,
  STORE,
  LOADIMM,
  STOREIMM,
  ILL,
} InstructionType;

You’ll see that any variable of type InstructionType, can take on one of 10 instruction values. For example:

int x = 5;
InstructionType a = BRANCH_EQ;
InstructionType b = LOADIMM;
 
if(a == LOAD){
  printf("a is a LOAD instruction type!\n");
} else {
  printf("a is not a LOAD instruction type!\n");
}

The above is code that has made 3 variables. The first one you should be familiar with, x is a variable with an integer type. Similarly, both variables a, b have the type InstructionType. Like how we can assign 5 to an integer type, we can assign values like BRANCH_EQ or LOADIMM to InstructionType.

So we can check what kind of value it is, using ==.

Big Picture

So here’s the big picture, we want to: (1) Read lines of input, and create a Program from it. (2) Run through the program i.e. the array of Instructions and update/maintain the machine state as we do so. The way you should do it is based on what was laid out in the previous section.

You have the help of functions like char *get_input_line() which will return a heap-allocated string representing 1 line of input. At end of input, it returns NULL. An empty line produces an empty string; stop reading instructions there too. Free each line after parsing it, and return a heap-allocated instruction array (or NULL for an empty program).

So overall, implement the following:

  • Instruction parse_instruction(char const *str) should be given a string, and it parses it into an instruction
  • Program read_instructions(void) should read as many lines as possible from input, and it should output a Program (which is an array of Instructions)
  • bool simulate(Program program, RAM *ram, CPU *cpu) is the meat of the simulation (i.e. after we’ve read all instructions from input). Now, we are given a program and we need to run it. This means updating the state of the program as we process the instructions line by line. The last thing is, the boolean that we have to return. This is specified immediately below

The last thing we need to simulate is a “hardware fault”. So in our program there is only one possible way to have a hardware fault: Dividing by 0. If we do, the simulation should stop immediately and return false, leaving cpu->instruction_pointer on the failing instruction. Otherwise, as long as we make it to the end of the program, it should return true.

At the end of the program, we will “dump” the contents of the CPU by printing out the values of all the registers and memory for you. :)

Running and Testing

  • To compile: run make in 2-cpu
  • To run: run ./virtual
  • To test: run make test
  • Notes: We recommend that you add additional test cases to make sure everything works