# Objects

## Primitives

### Primitive Solids

OpenSCAD provides four 3D primitive solids: cube(), sphere(), cylinder(), and polyhedron(). Note that surface() and import() may also be considered as primitive solids.

### Primitive Shapes

OpenSCAD provides four 2D primitive shapes: square(), circle(), polygon(), and text().

## Transformations

Syntactically, there's no difference between transformations and primitives, both accepts zero or more quantities and zero or more children objects as input and produce a 2D or 3D object as output. However, primitives require no input object (any children are ignored) and generally create an object from quantitative input. Transformations, in general, require input objects as children. If transformations are given no children, most of them behave benignly, producing neither any output, error, nor warning. It is useful to note the syntactical equivalence between primitives and transformation when coding a user defined module, since a user is free to create modules that behave as both primitives and transformations.

The full list of built-in transformations are given below according to this categorization:

 Transformation on one object color, rotate, translate, mirror, multmatrix, scale, resize, offset, render Transformation on two or more objects union, difference, intersection, hull Transformation on two objects minkowski Transformation between 2D and 3D projection(), linear_extrude(), rotate_extrude()

### projection(): 3D to 2D projection

Projection() creates either a cross-section or a projection of a 3D object onto the X-Y plane. Cross-section works like a saw that cut the object along the X-Y plane and leaving behind only the 2D shape that is on the plane. Projection works like a sun that is infinitely far away and casting its parallel rays on the object. The projection is the shadow of that object on the X-Y plane. Note that parts of the object both below and above the X-Y plane contribute to the shadow. The original 3D object is discarded after a projection(). If a cross-section or projection is needed in addition to the original object, that object has to be recreated separately. This is most conveniently achieved by packing all the code to create the 3D object into a module. Skip the cut parameter or set it cut=false to create a projection. Set the boolean parameter cut=true to create a cross-section.

In order to create projection along an arbitrary direction or a cross-section thru an arbitrary plane, use a combination of rotate() and translate() prior to projection().

Projections and cross-sections are very useful for extrusion and exportation to DXF formation.

projection(cut = true) example002(); make a cross-section.
projection(cut = false) example002(); makes a projection.
To make a projection in the Y-axis direction, first rotate it around the X-axis 90 degrees, projection() rotate([90,0,0]) example002();:

 example002(); projection(cut = true) example002(); projection(cut = false) example002(); projection() rotate([90,0,0]) example002();

Some additional examples are found in:

## Flow Control

### if() ... else ...

 Conditional Object if (expr_Q) object_T; Conditional Object if (expr_Q) object_T; else object_F;

The conditional object performs a test (evaluates the query expr_Q), and renders either object_T or object_F depending on the truth value of the test result. If object_F was to be nothing, then the else object_F; portion is optional.

More commonly, the compound statement form of if() is used, as exemplified by:

if (a1 > a2) {
// stack cube(a2) on top of cube(a1)
cube(a1);
translate([0,0,a1]) cube(a2);
} else {
// stack cube(a1) on top of cube(a2)
cube(a2);
translate([0,0,a2]) cube(a1);
}

If the result of the conditional evaluation is not an object, but a quantity, use the ? : conditional operator.

While it is allowed to assign variables in the compound form, the scope of those variables is limited to the curly brackets.

a = 5;
translate([0,0,0]) sphere(a);
if (a > 0) {
echo("Let's change!  a = ", a);
translate([20,0,0]) sphere(a);
a = 10;
}
echo("We don't forget!  a = ", a);

The outcome is a small and a large sphere, and in the console:

ECHO: "Let's change!  a = ", 10
ECHO: "We don't forget!  a = ", 5

Note that "a is 10" within the scope of the curly bracket, the corresponding statement a = 10; need not precede the echo() and sphere() statements for its effect to apply. After the if() statement, the assignment to a is lost, so we "recall" a is still 5. See Scope of variables for more details.

Nested if

Since a complete if() statement is an object, it can be nested in another if() statement. A common form is multiply nested "else if" statements:

if (a > 100) {
echo("HUGE!");
sphere(a);
// etc...
} else if (a > 10) {
echo("big.");
translate([0,0,10]) sphere(a);
// etc...
} else if (a > 1) {
echo("not so big...");
color("red") sphere(a);
} else {
echo("Sorry, I lost it.");
}

## Imported Objects

A number of file formats, including DXF, STL, JPG and TXT can be interpreted by OpenSCAD as objects.

OpenSCAD can also export objects into a number of file formats, however, those are performed by a menu command in the integrated development environment, therefore there are no export() counterparts to the import() and surface() commands.

## Null Object

Echo() is an exception when classifying OpenSCAD statements. Its functionality has nothing to do with rendering objects, but syntactically it is neither a variable assignment nor an expression (which evaluates to a quantity). Therefore, it is classified as an object, like primitives and transformations, but which produces a null object.

### echo()

Echo() prints out its input parameters as comma-delimited text in the Console (the compilation window). No formatting option is provided. Strings are surrounded by double quotation marks, vectors by square brackets. Multi-dimension vectors are fully represented with the appropriate number of nesting square brackets. It is in general possible to copy/paste the output of echo() to use as literals in an OpenSCAD program. Numeric values are rounded to 5 significant digits.

The primary intention of echo() is not to format and print beautiful text message to the end-user, but to expose the contents of variables to the programmer for debugging purpose. It is possible to improve the appearance of the output message with some variant forms of echo() and using the str() function.

The OpenSCAD console supports a subset of HTML markup language. See here for details.

Echo() accepts parameters in the format echo(var = expr, ...) and produces as output ECHO: var = quant, ... in which quant is the result of evaluating expr. This form is both decent looking and conveniently can be copied/pasted as valid OpenSCAD code.

Usage examples:

my_h=50;
my_r=100;
echo("This is a cylinder with h=", my_h, " and r=", my_r);
echo(my_h=my_h,my_r=my_r); // shortcut
cylinder(h=my_h, r=my_r);
//
echo("<b>Hello</b> <i>Qt!</i>");


Shows in the Console as

ECHO: "This is a cylinder with h=", 50, " and r=", 100
ECHO: my_h = 50, my_r = 100
ECHO: "Hello Qt!"


# Operators

## Arithmetic Operators

The scalar arithmetical operators take numbers as operands and produce a new number.

 + add - subtract - negate (unary) * multiply / divide % modulo

## Conditional Operator ? :

 Conditional Operator expr_Q ? expr_T : expr_F

An operator which returns either of two expressions depending on the truth value of a query expression. For example:

var = expr_Q ? expr_T : expr_F;

The expression expr_Q is evaluated and if it's true, expr_T will be evaluated and assigned to var; otherwise expr_F will be evaluated and assigned to var. If expr_Q evaluated to a non-Boolean result, it will be converted to Boolean, see here.

The conditional operator is essential when creating a recursive function call, since it is used to terminate the recursion, see here.

The conditional operator can be used like a nested if also, as in the following example:

 NSides = (FF=="triangular") ? 3 : (FF=="hexagonal") ? 6 (FF=="octogonal") ? 8 : (FF=="circular") ? 180 : 0;

# Functions

## Math Functions

### Trigonometric Functions

The trigonometric functions use the C Language mathematics library functions. Remember all numbers in OpenSCAD are IEEE double floating points. A good reference for the specifics of the C math library are (math.h) and (acos) at the Open Group website. For a quick reference to the relevant mathematics, see Trigonometric functions.

Note that the trigonometric functions do not work on vectors. Invalid inputs produce nan (e.g. acos(2)) or undef (e.g. sin("2")).

Function Description Notes
sin(x) trigonometric sine of x -inf < x < inf is in degrees, return value in [-1,+1]
cos(x) trigonometric cosine of x -inf < x < inf is in degrees, return value in [-1,+1]
tan(x) trigonometric tangent of x -inf < x < inf is in degrees, return value in (-inf, inf)
asin(x) inverse sine of x -1 <= x <= 1, return value in [-90,+90] (degrees)
acos(x) inverse cosine of x -1 <= x <= 1, return value in [0,+180] (degrees)
atan(x) inverse tangent of x -inf <= x <= inf, return value in [-90,+90] (degrees)
atan2(y, x) inverse tangent of y/x -inf <= x,y <= inf, return value in [-180,+180] (degrees) see also: atan2

More precisely the return value is the angle between the line joining origin to the point (x,y) and the X-axis

### Real Functions

Real functions require numeric inputs and produce numbers, except for rands() which returns a vector of numbers.

Function Description Notes
abs(x) absolute value of x -inf < x < inf, return value in [0,+inf)
sign(x) sign of x, see also Sign function -inf < x < inf, return value is 1, 0, or -1, if x is greater than, equal to, or less than 0
ceil(x) ceiling (integer) of real number x, see also: Ceil Function -inf < x < inf, return value is the smallest integer not less than x

also known as rounding off a number towards +inf

floor(x) floor (integer) of real number x, see also: Floor Function -inf < x < inf, return value is the largest integer not greater than x

also known as rounding off a number towards -inf

round(x) rounding function of real number x -inf < x < inf, return value is the integer nearest to x
pow(x,y) x raised to the power of y, i.e. ${\displaystyle x^{y}}$ -inf < x,y < inf
sqrt(x) square root of x, i.e. ${\displaystyle {\sqrt {x}}}$ 0 <= x < inf, return value is the integer nearest to x, if x is negative, returns nan
exp(x) exponential function of x, i.e. ${\displaystyle e^{x}}$, see also: Exponent -inf < x < inf
ln(x) natural logarithm of x, i.e. ${\displaystyle \ln x=\log _{e}x}$, see also: Natural logarithm 0 <= x < inf, if x is negative, returns nan
log(x) logarithm (base 10) of x, i.e. ${\displaystyle \log x=\log _{10}x}$, see also: Logarithm 0 <= x < inf, if x is negative, returns nan
rands(a,b,n) pseudo random number generator, see the main article return a vector with n random numbers in the range [a, b]

Some examples:

echo(ceil(4.4),ceil(-4.4));      // ECHO: 5, -4
echo(floor(4.4),floor(-4.4));    // ECHO: 4, -5
echo(exp(1),exp(ln(3)*4));       // ECHO: 2.71828, 81
sign(-5.0); // ECHO -1
sign(0);// ECHO 0
sign(8.0);// ECHO 1
round(5.4); //-> 5
round(5.5); //-> 6
round(5.6); //-> 6
round(-5.4); //-> -5
round(-5.5); //-> -6
round(-5.6); //-> -6


### Pseudo Random number generator

Generates a vector of pseudo random numbers. A seed value can be supplied optionally. From the moment a seed value is given, the sequence of pseudo random numbers being generated is deterministic. This provide a convenient way to debug the program using a constant seed value between repeated execution of the program.

Rands() always return a vector, which is not the most convenient data type when only a single random number is needed. In order to generate a single random value as a number, use x = rands(a,b,1)[0];.

Parameters

min_value
Minimum value of random number range
max_value
Maximum value of random number range
value_count
Number of random numbers to return as a vector
seed_value (optional)
Seed value for random number generator for repeatable results. On versions before late 2015, seed_value gets rounded to the nearest integer

Usage Examples:

// get a single number
vec_rand = rands(0,10,1);
single_rand = rands(0,10,1)[0];
echo(vec_rand);    // ECHO: [4.44795]
echo(single_rand); // ECHO: 7.86455

// get a vector of 4 random numbers with seed value 42
random_vect=rands(5,15,4,42);
echo(random_vect); // ECHO: [8.7454, 12.9654, 14.5071, 6.83435]


cross, norm

max, min

len, concat

lookup

search()

str(), chr()

search()

dxf_cross()

dxf_dim()

# Functions and Module Definitions

## Function Definition

function name(param_list) = expr;

Note that inside a function definition, variables defined in the main scope is accessible. See variables and scopes.

### Recursive function calls

Recursive function calls are supported. Using the Conditional Operator it's possible to ensure the recursion is terminated. Note: There is a built-in recursion limit to prevent an application crash. If the limit is hit, the function returns undef.

example
 // recursion - find the sum of the values in a vector (array) by calling itself
// from the start (or s'th element) to the i'th element - remember elements are zero based

function sumv(v,i,s=0) = (i==s ? v[i] : v[i] + sumv(v,i-1,s));

vec=[ 10, 20, 30, 40 ];
echo("sum vec=", sumv(vec,2,1)); // calculates 20+30=50


include <>

use <>

# Special Variables

$t$fn etc

$vpn etc$parent_modules

# Modifiers

A modifier, when preceding an object, will modify the behavior of the interpreter during preview and rendering for that object or all other objects in the program. They are essential aids to the user when designing even a minimally complicated object.