openscad

Openscad - conditional load of configuration


I have a common design part in OpenSCAD defined by ca. 15 parameters. Is there a way how to put them to configuration files (or something similar) and choose between them conditionally?

I am looking for something like

type = "wide";

if (type == "narrow")
  include <narrow.scad>;
else if (type == "wide">
  include <wide.scad>;
else
  include <round.scad>;

With file wide.scad containing data like

width = 200;
height = 50;
radius = 7;

etc.

I would like to provide the type parameter from commandline, which is possible via -D, but I cannot find a way how to bind the definition to parameter value.


Solution

  • I don't know of a way to put configurations into separate files, but I have solved a similar problems by putting configurations in a table of key-value pairs like this:

    // Rows must be in "asciibetical" order by name.
    configs = [
      // name     width  height  radius
      ["narrow", [   50,     50,      7]],
      ["round",  [  100,    100,    100]]
      ["wide",   [  200,     50,      7]],
    ];
    

    A couple helper functions can find the configuration you want from a table of key-value pairs.

    function find_row(key, table, low, high) =
      low > high ? undef :
      let(i = round_up(mid(low, high)))
        table[i][0] == key ? table[i][1] :
        table[i][0] <  key ? find_row(key, table, i+1, high) :
                             find_row(key, table, low, i-1);
    
    function find_config(key) =
        find_row(key, configs, 0, len(configs) - 1);
    

    To get a configuration:

    config = find_config("wide");
    assert(!is_undef(config));
    

    Of course, you have to know which parameter is at which index in the configuration. Usually, I immediately unpack them into variables to given them meaningful names.

    width  = config[0];
    height = config[1];
    radius = config[2];
    

    This works well enough once you've nailed down the parameters that will be part of a configuration. If the code you're writing it still evolving, it can become tedious to make sure you're using consistent indexes.