Menger Sponge in openJSCAD


#1

Hello All, I have been facing an issue please help me on that.

I’m trying to make a ‘Menger sponge’ in OpenJSCAD

it doesn’t work for more than 1 generation and I have no idea why, you can try and paste the below code in there and fiddle with it yourself if you’d like.

+1 if you can find my mistake without going to OpenJSCAD

function main() {
    var rad = 100;
    var MC = new MCube(rad, [0,0,0]);
    var sponge = [];
    sponge = menger(MC, 2);
    return sponge;
}
function menger(cube, dept){
    if(dept > 0){
        dept--;
        var cubes = [];
        var sponge = [];
        var r = cube.size;
        var q = r/3;
        xPos = cube.pos[0];
        yPos = cube.pos[1];
        zPos = cube.pos[2];
        for(var z = 0;z<3;z++){
            for(var y = 0;y<3;y++){
                for(var x = 0;x<3;x++){
                    cubes.push(new MCube(q,[xPos + (x * q),yPos + (y * q),zPos + (z * q)] ));  
                }
            }
        }
        for(var i = 0;i < cubes.length;i++){
            if(i != 4 && i != 10 && i != 12 && i != 13 && i != 14 && i != 16 && i != 22){
                sponge.push(cubes[i]);
            }
        }
        for(var i = 0;i < sponge.length;i++){
            sponge[i] = menger(sponge[i], dept);
        }
        return unite(sponge);
    }else{
        return cube;
    }
}
function unite(cubes){
    var sponge = cubes.pop().obj;
        for(var i = 0; i < cubes.length;i++){
            sponge = union(sponge, cubes[i].obj );
        }
    return sponge;
}
function MCube(size,pos){
    this.obj = cube({size:size,center:false}).translate(pos);
    this.size = size;
    this.pos = pos;
    this.translate = function(pos){
        this.obj.translate(pos);
    };
}

Hope, I will get answer for this

Thanks
SarahJohn