Slide 1

Slide 1 text

3D Modeling in OpenSCAD Moncton Developer User Group 16 February 2016 Doreen A. Clemons

Slide 2

Slide 2 text

Overview: What's Being Covered 1. Pros and Cons 2. The OpenSCAD UI 3. Code Structure 4. Creating Basic 3D Objects (“Singletons”) 5. Transforming and Manipulating Objects 6. Basic Debugging 7. Printing on MakerBot

Slide 3

Slide 3 text

So who am I, right?  Chief cook and bottle-washer at Bonaventure Software  (Yet) Another programming side-step: Originally needed custom parts for Arduino-projects  Appalling drafting skills...in CAD or in meat-space  OpenSCAD, by contrast, builds shapes via math and code

Slide 4

Slide 4 text

OpenSCAD: Pros vs. Cons Photo Sources: http://www.cirrusinsight.com/wp-content/uploads/2014/08/Wayne_Gretzky_Net_Worth.jpeg and http://www.bankers-anonymous.com/wp-content/uploads/2014/02/Wolf-of-wall-street.jpg

Slide 5

Slide 5 text

OpenSCAD: The Pros  Absolutely no drawing ability required  Free-as-in-beer open source (vs. Sketchup)  Uncomplicated UI (vs. Blender)  Supported on Linux, Mac, and Windows (vs. Sketchup)  Can be rendered and exported from the command- line  OpenSCAD provides an unparalleled opportunity to appreciate just how much Geometry / Trigonometry / Vector Algebra you've forgotten

Slide 6

Slide 6 text

OpenSCAD: The Cons  API is rapidly evolving – not always backwards- compatible  Linux versions (in the official repositories) can lag considerably behind Windows/Mac  Arcs are not supported except in 3rd-party libraries  sizeof()-type functions not supported except in 3rd-party libraries  Primitive debugging capabilities  (My opinion) Some annoying API inconsistencies

Slide 7

Slide 7 text

OpenSCAD: The Real Estate Tour Photo Source: http://4.bp.blogspot.com/-MYtNcESuAFo/UJmtP5iu12I/AAAAAAAAFR4/ogNbPyVVdg0/s1600/Real+Estate+1.jpeg

Slide 8

Slide 8 text

OpenSCAD UI: Views Code Status Viewport

Slide 9

Slide 9 text

OpenSCAD UI: Using 3rd-party Editor “Hide Editor” option in “View” menu

Slide 10

Slide 10 text

OpenSCAD UI: X-Y-Z Orientation X-Y-Z Orientation indicator

Slide 11

Slide 11 text

OpenSCAD UI: Manipulating Viewport  Left-click plus mouse-drag rotates on X, Y, and Z axes  Right-click plus mouse-drag moves the objects plus axes within viewport  Mouse-roll upward zooms in  Mouse-roll downward zooms out  Note: Later versions of OpenSCAD may have shortcut buttons for top view, side view, re-centering, etc.  “Preview” (F5) vs. “Render” (F6) modes

Slide 12

Slide 12 text

OpenSCAD: Code Structure

Slide 13

Slide 13 text

Code Structure: The Non-drawing Parts  C-ish look and feel  Variables (including the biggest “gotcha”)  Looping  Conditional logic  Operators  Built-in functions  Modules and Functions  API “chaining”

Slide 14

Slide 14 text

C-ish Look and Feel, but...  Looks just enough like classic (K&R) C to trip you up.  Not object-oriented  “Functional” language in that functions can take other functions/modules as parameters  No exception-handling  echo() is your System.out.println()  Variable scope is what you'd expect...mostly  Gotcha: Undefined variables will equate to zero and generate a warning, but not a compiler error

Slide 15

Slide 15 text

Variables in OpenSCAD  Variables are dynamically typed  Variable types are implicit, not declared  Six variable types:  Signed floating-point number: Approx -1.0e+308 – 1.0e+308  Boolean: Some counter-intuitive evaluations  String: Some vector-like characteristics  Vector/Matrix: Square-bracket syntax  Range: Used mainly in for-loops; two or three “parameters”  Undefined and NaN (udef and nan, respectively)  Gotcha: With few exceptions, variable values are set at compile-time, not run-time

Slide 16

Slide 16 text

Gotcha: Variable values set at compile-time

Slide 17

Slide 17 text

Expecting blocks of two different lengths...

Slide 18

Slide 18 text

lol, nope

Slide 19

Slide 19 text

So what happened? Variable's value is always its last assigned value.

Slide 20

Slide 20 text

Looping  No while-loops  for-loops have a slightly different iteration syntax: for(i = [0:9]) {...} or for(i = [0:2:10]) {...} or for(i = [1.0, 1.1, 1.2, 1.3, 1.4]) or for(i = 2_dimensional_array_name)  Loops can be nested

Slide 21

Slide 21 text

Conditional logic  if – else blocks look like C: if ([condition is true]) // do something else // do something else  if – else blocks can be nested  Inline-if syntax can only return values, not execute other code: [Test_condition] ? [True_value] : [False_value] (x == y) ? fltMax : fltMin;  Gotcha: if­else cannot be used to set variable values – code will not compile

Slide 22

Slide 22 text

Operators  Most of the usual suspects from C are available:  Arithmetic: +, ­, *, /, %  Comparison: <, >, <=, >=, ==, !=  Logic: &&, ||, !  Minus-sign also negates or multiplies by -1  When used with a vector and number, * and / multiply/divide all vector elements w/that number  When used with two vectors (of the identical size), + and – add/subtract the vector elements  The usual rules about vector and matrix dot- products apply

Slide 23

Slide 23 text

OpenSCAD's Built-in functions  Trigonometric functions: sin(), cos(), tan(), asin(), acos(), atan(), atan2()  Trig. functions take degrees, not radians, as arguments  π (PI) is a reserved word  Math functions: abs(), ceil(), floor(), min(), max(), exp(), pow(), sqrt(), sign(), ln(), log(), round(), rand()  Vector functions: concat(), cross(), len(), lookup(), norm()

Slide 24

Slide 24 text

Code Execution  A .scad file is both compiled and executed by opening it in the OpenSCAD program  There is no application entry-point (e.g. no main() function)  Break reusable code out into modules and functions  Variables and functionality used by more than one model can be d or d  d code makes variables/modules/functions available, but does not execute inline code  d code executes any inline code as well as makes variables/modules/functions available

Slide 25

Slide 25 text

Modules and Functions  Modules can draw objects, but cannot return a value.  Functions return a single value, cannot draw anything, and must be written inline: function computeSecant(fltDegrees)= (1 / cos(fltDegrees));  Both modules and functions can take parameters  Modules can call other modules as well as functions; functions can only call other functions

Slide 26

Slide 26 text

Chaining API Calls  Particularly when using the “drawing” parts of the OpenSCAD API, functions can be “chained”  Basically, the API function is taking another API function as a parameter  Your own module can be used as the last parameter  For readability, use indentation and/or curly-braces  When chaining single-line function-calls, a semi- colon ends a chain  Closing curly-braces determine the end of a multi- line chain

Slide 27

Slide 27 text

Example of API Chaining  Chaining single-line API calls:  Chaining multi-line API calls:

Slide 28

Slide 28 text

OpenSCAD: 3D “Singletons” Photo Source: http://i.ebayimg.com/00/z/M6sAAOxyzi9Se2vD/$T2eC16JHJGMFFpfi!d7!BSe2vGu-Tw~~_32.JPG

Slide 29

Slide 29 text

Three Ways to Make Singletons 1. Drawing 3D “primitives”  cube()  sphere()  cylinder()  polyhedron() -- “custom primitive” of vertices and planes 2. Projecting 2D shapes into 3D space  linear_extrude()  rotate_extrude()  text() 3. Programatically

Slide 30

Slide 30 text

3D “Primitives”: Cube  “Cube” is a misnomer: Can also be a rectangular block  Two parameters:  size: A float or vector that determines the XYZ dimensions  center: A Boolean indicating whether or not to center on the XYZ origin-point (false places cube “bottom” on Q1 of the XY plane.)  $fn, $fa, and $fs are pointless with blocks; don't bother with them

Slide 31

Slide 31 text

3D “Primitives”: Sphere  Does what it says on the label  Parameters:  r, for “radius”  d, for “diameter,” is not backwards-compatible  $fn, $fa, $fs (most likely $fn) to control granularity  “Gotcha”: You do not have the option of turning off centering at the origin – you have to explicitly move it

Slide 32

Slide 32 text

3D “Primitives”: Fragment Variables  Use to control resolution of 3D primitives with curved surfaces (i.e., sphere and cylinder)  For spheres and cylinders, applies to “top” view  Three variables:  $fn specifies the number of fragments  $fa specifies the fragment angle in degrees  $fs specifies the fragment size in millimetres  Tradeoff: Finer resolution = more processing and longer printing-time

Slide 33

Slide 33 text

3D “Primitives”: Cylinder  You can also use it to make a cone (pointy or truncated)  Parameters:  r : float that indicates single radius (cylinder); r1 + r2 = bottom and top radii for a cone  d : float that specifies cylinder diameter; d1 + d2 = bottom and top diameters of a cone  h : float that indicates height  center : true centers on XYZ origin; false centers on XY origin  $fn, $fa, $fs : Specifies granularity of sides

Slide 34

Slide 34 text

3D “Primitives”: Polyhedrons  Points (vertices) and faces (planes)  Parameters:  points : a vector of XYZ points (themselves vectors of floats)  faces / triangles : a vector of vectors; the vectors are the indices of the points that make the corners of each face/triangle  Always define faces clockwise, from the perspective of the outside of the object  triangles is for pre-2014 OpenSCAD versions; all faces must be comprised of triangles!

Slide 35

Slide 35 text

Polyhedron: Points & Triangles P0 [0.0, 0.0, 0.0] P1 [15.0, (sin(60.0) * 30.0), 0.0] P2 [30.0, 0.0, 0.0] Apex (top point): P3 [15.0, ((sin(60.0) / 2) * 30.0), (sin(60) * 3.0)]] T1 [P0, P3, P2] Underside: T0 [P0, P1, P2] T2 [P1, P3, P0] T3 [P2, P3, P1]

Slide 36

Slide 36 text

Polyhedron: Code

Slide 37

Slide 37 text

2D -> 3D Extrusion  Build a 2D object and project it into 3D space  linear_extrude() projects “up” from XY plane's “ground”  rotate_extrude() spins shape like on a pottery wheel  Can use built-in 2D objects (square, circle, ellipse), “custom” polygons, or imported .dxf files  Hack: Can use circle to make a regular polygon before extruding – just specify # of faces

Slide 38

Slide 38 text

2D -> 3D Extrusion: linear_extrude()  Example of function “chaining”: linear_extrude() specifies the 3D attributes of all that follows in its “chain”  Parameters:  height : float specifying height  center : Boolean specifying whether or not to center on the Z axis  convexity : float specifying max. # of points a line passing through shape would intersect  slices : specifies granularity on the Z-axis  twist : float specifying degrees of twist during build-up  scale : float specifies change in size for both X & Y; vector specifies change for each dimension

Slide 39

Slide 39 text

linear_extrude() 2D Code

Slide 40

Slide 40 text

polygon() before linear_extrude() Note: 2D “height” is for illustration purposes only.

Slide 41

Slide 41 text

Simple linear_extrude() Code

Slide 42

Slide 42 text

Simple linear_extrude()

Slide 43

Slide 43 text

linear_extrude() with twist Code

Slide 44

Slide 44 text

linear_extrude() with twist

Slide 45

Slide 45 text

linear_extrude() with scale Code

Slide 46

Slide 46 text

linear_extrude() with scale

Slide 47

Slide 47 text

linear_extrude() with scale, top view Gotcha: Polygon footprint will “hug” the X-Y origin; for a symmetrical extrusion, center 2D object on X-Y origin (0, 0)

Slide 48

Slide 48 text

2D -> 3D Extrusion: rotate_extrude()  Draws a 2D object on X-Y plane, which is automatically rotated 90 degrees around the X-axis before 360 degree rotation around the Z-axis  Parameters:  convexity : the max. # of times a line will intersect w/edges of 2D object it passes through  $fn, $fa, $fs : As with 3D primitives, specifies granularity  Gotcha #1: polygon() must be entirely in Q1  Gotcha #2: Documentation may not be correct

Slide 49

Slide 49 text

rotate_extrude() using polygon()

Slide 50

Slide 50 text

polygon() before rotate_extrude()

Slide 51

Slide 51 text

rotate_extrude() Code

Slide 52

Slide 52 text

2D -> 3D Extrusion: Text  Only supported in the last stable release (2015.03)  Basic parameters:  The text itself, enclosed in quotation-marks  size : approx. font size, like in word processing  font : the font name, e.g. Liberation Serif  style : Bold and/or Italic  Non-system fonts must be installed with use, e.g. use  Unicode characters can be specified with backslash notation: \x03, \u0123, or \U012345

Slide 53

Slide 53 text

Extruding text() from 2D -> 3D

Slide 54

Slide 54 text

text() from top to bottom

Slide 55

Slide 55 text

2D -> 3D Extrusion: Aligning Text  Text layout and options are fairly primitive  Text vector specified by the direction parameter:  ltr : left-to-right  rtl : right-to-left  ttb : top-to-bottom  btt : bottom-to-top  Default is left-to-right if direction not specified  rtl prints each letter backwards as well as reversing their order, but btt does not print letters upside-down

Slide 56

Slide 56 text

2D -> 3D Extrusion: Aligning Text, cont.  Horizontal & vertical alignment text() parameters control positioning w/in bounding box  Possible halign values: left, center, and right  Possible valign values: top, bottom, center, and baseline  Default values are left and baseline, respectively, when not specified  In practice, you will probably use translate() more often that halign/valign to position text

Slide 57

Slide 57 text

Programming 3D Objects  Basic idea: Combine logic and built-in functions  Typically, using for-loops to build shape in “slices”  “Slices” take the place of the $fn, $fa, $fs variables  The # of slices is a tradeoff between granularity of the finished product and the processing / printing required

Slide 58

Slide 58 text

Example: sin() + cos() inside for-loop

Slide 59

Slide 59 text

Code: sin() + cos() inside for-loop

Slide 60

Slide 60 text

OpenSCAD: Let's Build Stuff! Source: http://41.media.tumblr.com/eb177cf4a2c9b9047698e6b7e12c5882/tumblr_nxxk3zWA161uz9n5lo1_1280.jpg

Slide 61

Slide 61 text

A 3D Project's “Toolkit”  Transform objects by stretching/compressing with scale() and resize()  Change object location with translate() and rotate()  Glue/Meld singletons together with union()  Subtract singletons with difference() and intersection()  Superpowers: hull() and minkowski()functions

Slide 62

Slide 62 text

Transforming Objects with scale() & resize()  Both functions transform object dimensions in XYZ space  Both functions take an [X, Y, Z] vector as a parameter  With scale(v=[x, y, z]), x, y, and z are multiples of the original dimensions  With resize(newsize=[x, y, z]), x, y, and z are literal measurements unrelated to original dimensions

Slide 63

Slide 63 text

Conical cylinder() before transformation

Slide 64

Slide 64 text

Cone after scale() transformation

Slide 65

Slide 65 text

Cone after resize() transformation

Slide 66

Slide 66 text

scale() and resize(), cont.  For many purposes, scale() and resize() are equivalent  If you use zero as one of resize()'s newsize parameters, the object will not be resized in that dimension  Alternatively, set one newsize parameter, set the others to 0, and use the optional auto parameter to proportionally scale the other dimensions  Pro tip: resize() is handy for combining text w/other 3D objects

Slide 67

Slide 67 text

Moving Objects on the 3D “Canvas”  By default, all objects are drawn relative to (0, 0, 0), with zero degrees of rotation around all axes  translate() and rotate() apply to the code- chain / code-block that follow, then OpenSCAD resets back to (0, 0, 0) with zero rotation  rotate() takes degrees, not radians, as parameters  translate() and rotate() can be mixed, nested and repeated as often as necessary  Gotcha: translate() + rotate() != rotate() + translate()

Slide 68

Slide 68 text

Rectangular Block Before Transformation

Slide 69

Slide 69 text

Block After translate()

Slide 70

Slide 70 text

Block Rotated 45 Degrees on Y- and Z-axes

Slide 71

Slide 71 text

rotate() + translate() vs. translate() + rotate()

Slide 72

Slide 72 text

Building Complex Shapes from Singletons  No parameters needed for union(), intersection(), and difference()  The usual rules of code-chaining apply: Use semi- colons and curly-braces accordingly  All three functions can be nested w/in blocks in infinite variety  Shortcuts for creating “shells” for compound objects: hull() and minkowski()  2D objects can use all of the above functions before being extruded to 3D

Slide 73

Slide 73 text

union() of cube() and cylinder()s

Slide 74

Slide 74 text

union() of cube() and cylinder()s

Slide 75

Slide 75 text

intersection() of cube() and cylinder()s

Slide 76

Slide 76 text

intersection() of cube() and cylinder()s

Slide 77

Slide 77 text

difference() of cube() and cylinder()s

Slide 78

Slide 78 text

difference() of cube() and cylinder()s

Slide 79

Slide 79 text

Gotcha: difference() and “Breaking the Plane”

Slide 80

Slide 80 text

Gotcha: difference() and “Breaking the Plane”

Slide 81

Slide 81 text

hull() of cube() and cylinder()s

Slide 82

Slide 82 text

hull() of cube() and cylinder()s Note: Hull will always be convex, never concave.

Slide 83

Slide 83 text

minkowski() Transformation

Slide 84

Slide 84 text

minkowski() Transformation

Slide 85

Slide 85 text

minkowski() “Under the Hood”

Slide 86

Slide 86 text

OpenSCAD: Debugging Photo Source: http://vignette1.wikia.nocookie.net/men-in-black/images/5/59/Mib1ufoshotdown.jpg/revision/latest? cb=20131231042919

Slide 87

Slide 87 text

Error-handling in OpenSCAD  Again, no try-catch exception handling :~(  Compilation failures will prevent all rendering  Runtime errors (e.g. undefined variables, NaN, etc.) will generate warnings, but will render improperly  Errors and warnings are shown in the console area of the GUI  Gotcha: Included/Used files will throw off the line numbers of the error message

Slide 88

Slide 88 text

Debugging “Toolkit”  The echo() function prints message to the console  Commas concatenate strings and numbers in echo()  An exclamation-point (!) before a block of code draws only that block of code  A hashtag (#) before a block of code draws its objects in semi-transparent colour to highlight them  An asterisk (*) before a block of code ignores it and draws everything else  Caveat: Asterix may have side effects, particularly with the difference() function

Slide 89

Slide 89 text

difference() Before Debugging Symbols

Slide 90

Slide 90 text

difference() with # and *

Slide 91

Slide 91 text

difference() with # and *

Slide 92

Slide 92 text

Caveat: Can only use ! once This will not work as intended.

Slide 93

Slide 93 text

Only First !-ed Code-block Will Render

Slide 94

Slide 94 text

Workaround: union() the Cylinders

Slide 95

Slide 95 text

Workaround: union() the Cylinders

Slide 96

Slide 96 text

Printing on a MakerBot Photo Source: http://store.makerbot.com/mb-images/store/rep-mini/hero-shark.png

Slide 97

Slide 97 text

3D Models in Plasticspace  Export .scad to .stl or .obj files for printing  Units: 1.0 in OpenSCAD == 1mm on MakerBot  Printer puts down a “raft” before printing object; must be manually separated after printing  Orient object to print “into thin air” as little as possible – can be done w/Makerbot software – Supporting “legs” will need to be broken/sanded off – Consider coding objects so they can be glued together  Adjust infill (w/Makerbot software) to control amount of plastic used inside shape

Slide 98

Slide 98 text

PLEASE Print Responsibly! Photo Credits (clockwise): http://blog.wwf.ca/files/2012/06/turtle.jpg, http://media-2.web.britannica.com/eb-media/79/102979- 004-7CA2A83F.jpg, http://i0.wp.com/okmagazine.com/wp-content/uploads/2015/03/kim-kardashian-plastic-surgeries-05.jpg? fit=600%2C9999, http://assets1.learni.st/learning_preview/1505628/image/w583h583_721070-devestating-to-oceans-and-marine- life.jpg

Slide 99

Slide 99 text

Experimenting on Your Own Photo Source: http://images4.fanpop.com/image/quiz/571000/571868_1302369936696_315_395.jpg

Slide 100

Slide 100 text

OpenSCAD: Resources  OpenSCAD website: http://www.openscad.org/  OpenSCAD user manual & language reference: https://en.wikibooks.org/wiki/OpenSCAD_Use r_Manual  Various sample projects (MakerBot website): http://www.thingiverse.com  New to C? The C Programming Language, Kernigan & Richie  Shameless plug for the MPL Makerspace/FabLab: http://monctonpubliclibrary.ca/makerspace/

Slide 101

Slide 101 text

Et cetera  URL of slides (as .PDF file): http://www.bonaventuresoftware.ca/mug/Open SCAD/slides.pdf  Email: [email protected]  Twitter: @bonaventuresoft