Skip to content

Tutorial 2 Dynamic Creation and Deletion

Jacob Austin edited this page May 16, 2020 · 2 revisions

Goals

In this tutorial, we will create and delete cubes dynamically throughout the run, adding new masses and springs to the simulation while it is running.

Setup

See the first tutorial for the full project setup. As before, include the Titan simulation header to access the library methods.

#include <Titan/sim.h>
#include <math.h>

using namespace titan;

Setting up the simulation

We will start the simulation with a single lattice bouncing on a flat plane. This is essentially the outcome of the previous tutorial. In the main function, we create a Simulation object, and add the plane and lattice.

Simulation sim; // create the basic simulation object.
sim.createLattice(Vec(0, 0, 20), Vec(5, 5, 5), 5, 5, 5);
sim.createPlane(Vec(0, 0, 1), 0);

Then we add start the run, and add new cube every second.

    sim.start();

    while (sim.time() < 10.0) {
        sim.pause(sim.time() + 1.0); // pause at the current time plus 1 second

        sim.createLattice(Vec(cos(sim.time()), sin(sim.time()), 10), Vec(5, 5, 5), 5, 5, 5); // create a lattice at some random position

        if (sim.time() > 5.0) {
            sim.deleteContainer(sim.getContainerByIndex(0)); // delete the first created container each iteration, after 5 seconds.
        }
        
        sim.resume(); 
    }

    sim.stop(); // stop the simulation after breaking out of the loop
}

This program is easy to write, but runs a rather complicated simulation. After setting it up, every second, it creates a new lattice object. Also, after 5 seconds have passed, it will delete the earliest lattice object still present in the simulation. The simulation lasts for 10 seconds.

The finished program:

The full program now looks like this:

#include <Titan/sim.h>
#include <math.h>

using namespace titan;

int main() {
    Simulation sim; // create the basic simulation object.
    sim.setViewport(Vec(20, 20, 10), Vec(0, 0, 5), Vec(0, 0, 1)); // set the viewport to see the cubes

    sim.createLattice(Vec(0, 0, 20), Vec(5, 5, 5), 5, 5, 5);
    sim.createPlane(Vec(0, 0, 1), 0);

    sim.start();

    while (sim.time() < 10.0) {
        sim.pause(sim.time() + 1.0);

        sim.createLattice(Vec(cos(sim.time()), sin(sim.time()), 10), Vec(5, 5, 5), 5, 5, 5);

        if (sim.time() > 5.0) {
            sim.deleteContainer(sim.getContainerByIndex(0)); // delete the first created container each iteration, after 5 seconds.
        }

        sim.resume();
    }

    sim.stop();
}

Try compiling and running this.

Result