Only one triangle is drawn, not the second one

48 views Asked by At

I have this code to draw two triangles. But it only draws the first triangle, not the second one. I cannot figure out the bug.

module draw_triangles(indices, vertices, triangle_color=[1, 1, 1, 0.4]) {
  assert(len(indices) % 3 == 0, "indices must have a length that is a multiple of 3");

  for (i = [0:len(indices)-1:3]) {
    triangle(
      vertices[indices[i]],
      vertices[indices[i+1]],
      vertices[indices[i+2]],
      triangle_color
    );
  }
}

module triangle(p1, p2, p3, triangle_color) {
  color(triangle_color) polyhedron(points=[p1, p2, p3], faces=[[0, 1, 2]]);
}

edges = [
    [80/2, 0, 0],
    [80, 80/2, 0],
    [80/2, 80, 0],
    [0, 80/2, 0],
    [80/2, 0, 80],
    [80, 80/2, 80],
    [80/2, 80, 80],
    [0, 80/2, 80],
    [0, 0, 80/2],
    [80, 0, 80/2],
    [80, 80, 80/2],
    [0, 80, 80/2],
];

triangle_table = [1, 8, 3, 9, 8, 1];
draw_triangles(indices = triangle_table, vertices = edges, triangle_color=[0, 1, 1, .4]);

Screenshot

2

There are 2 answers

1
Cadeyrn On BEST ANSWER

You made a mistake when you wrote your for loop : it's [start:step:end] not [start:end:step] so you must replace your for (i = [0:len(indices)-1:3]) by for (i = [0:3:len(indices)-1])

0
Megidd On

Avoid loop step

I already solved my problem by not using the loop step at all.

The bug was robustly fixed by using a nested array like this:

triangle_table = [
    [ 1, 8, 3 ],
    [ 9, 8, 1 ],
];

draw_triangles(triangle_table);

The loop is implemented like this:

module draw_triangles(triangle_table)
{
    for (i = [0:len(triangle_table) - 1])
    {
        indices = triangle_table[i];

        p0 = edges[indices[0]];
        p1 = edges[indices[1]];
        p2 = edges[indices[2]];

        color([ 1, 1, 1, 0.4 ]) polyhedron(points = [ p0, p1, p2 ], faces = [[ 0, 1, 2 ]]);

        echo("Draw triangle ", i, "indices: ", indices);
    }
}

The bug was fixed by replacing:

  for (i = [0:len(indices)-1:3]) {

with:

  for (i = [0:len(indices)-3:3]) {

Screenshot