stl.py

Thu, 06 Apr 2017 19:00:07 +0200

author
mdd
date
Thu, 06 Apr 2017 19:00:07 +0200
changeset 22
08f0118587d7
parent 19
32de35694e56
permissions
-rw-r--r--

ht is not PVC....

"""
STL related helpers
"""

import os, subprocess
import config, data

OPENSCAD_MODULES = """
module tank(x, r, h) {
  color("SteelBlue") render() { //rotate([90,0,0]) {
    translate([x, r, r]) {
        sphere(r = r); // bottom
        cylinder(h = h-2*r, r = r);
    }
    translate([x, r, h-r]) {
        sphere(r = r); // top
        cylinder(h = r*1.4, r = r*0.25);
    }
  }
}

module spacer(x, r, rcyl, h) {
  color("DarkGrey") render() { //rotate([90,0,0]) {
    translate([x, r, rcyl]) {
        difference() {
            cylinder(h = h-2*rcyl, r = r);
            cylinder(h = h-2*rcyl, r = r*0.8);
        }
    }
  }
}
$fn = 25; // high detail per default
"""

def run_openscad(output):
    """
    Run openSCAD process, then convert the ascii stl to binary by using vtk
    """
    import vtk
    if os.path.isfile(output):
        print "skipping existing file %s" % output
        return
    print "rendering %s" % output
    subprocess.check_call([
        'openscad',
        '-o',
        output,
        config.TMP_SCAD
        ])
    # convert to binary
    reader = vtk.vtkSTLReader()
    reader.SetFileName(output)
    reader.Update()
    write = vtk.vtkSTLWriter()
    write.SetFileTypeToBinary()
    write.SetInput(reader.GetOutput())
    write.SetFileName(output)
    write.Write()

def precompile_all_stl():
    """
    Write .scad temp file and
    Invoke run_openscad for each object
    that needs to be created in stl directory
    """
    base = os.path.abspath('stl')
    hmin = 9999
    rmax = 0
    for cyl in data.CYLINDER.keys():
        with open(config.TMP_SCAD, "w") as fn:
            fn.write(OPENSCAD_MODULES)
            fn.write("tank(0, %f, %f);" % (
                data.CYLINDER[cyl][0] / 2 * config.SCALE3D,
                data.CYLINDER[cyl][1] * config.SCALE3D))
        run_openscad(os.path.join(base, \
            'cylinder_' + cyl + '.stl'))
        if data.CYLINDER[cyl][1] < hmin:
            hmin = data.CYLINDER[cyl][1]
        if data.CYLINDER[cyl][0] > rmax:
            rmax = data.CYLINDER[cyl][0]

    for pipe in data.PIPES:
        with open(config.TMP_SCAD, "w") as fn:
            fn.write(OPENSCAD_MODULES)
            fn.write("spacer(0, %f, %f, %f);" % (
                pipe[1] / 2 * config.SCALE3D,
                rmax / 2 * config.SCALE3D,
                hmin * config.SCALE3D))
        run_openscad(os.path.join(base, \
            'spacer_' + pipe[0] + '.stl'))

mercurial