No Plugins; Monolithic

    jscad-utils

    3.2.0 • Public • Published

    view on npm npm module downloads

    jscad-utils

    This is a collection of utilities for openjscad projects. These modify the CSG object adding utilities for alignment, scaling and colors. There are also some basic parts that use outside dimensions rather than radii.

    For an example, see the yeoman jscad generator which will create a project that uses this library.

    Installation

    You will need Node.js version 6.4 installed. Other versions will probobly work, but that's what it's tested with. Install jscad-utils using NPM:

    npm install --save jscad-utils

    Basic usage

    To use the utilities, you need to include the jscad-utils.jscad file and a copy of lodash.

    include('node_modules/jscad-utils/jscad-utils.jscad');
     
    main() {
      util.init(CSG);
     
    }

    Publishing

    Use np to publish to NPM.

    Examples

    Examples are placed in the dist directory with the jscad-utils.jscad file injected into them. This allows the files to be included directly into openjscad.org.

    Here are some of the examples:

    • snap an example showing how to use the snap function.
    • bisect an example cutting an object in two with the bisect function.
    • fillet an example adding a roundover and fillet with the fillet function.
    • chamfer an example cutting a chamfer into an object with the chamfer function.

    API Reference

    Added CSG methods

    JWC jscad utilities

    CSG.color([red or css name], [green or alpha], [blue], [alpha]) ⇒ CSG

    Set the color of a CSG object using a css color name. Also accepts the normal setColor() values.

    Kind: static method of CSG
    Extends: CSG
    Chainable
    Returns: CSG - Returns a CSG object set to the desired color.

    Param Type Description
    [red or css name] String | Number Css color name or the red color channel value (0.0 - 1.0)
    [green or alpha] Number green color channel value (0.0 - 1.0) or the alpha channel when used with a css color string
    [blue] Number blue color channel value (0.0 - 1.0)
    [alpha] Number alpha channel value (0.0 - 1.0)

    Example

    // creates a red cube
    var redcube = CSG.cube({radius: [1, 1, 1]}).color('red');
     
    // creates a blue cube with the alpha channel at 50%
    var bluecube =  CSG.cube({radius: [1, 1, 1]}).color('blue', 0.5);
     
    // creates a green cube with the alpha channel at 25%
    // this is the same as the standard setColor
    var greencube =  CSG.cube({radius: [1, 1, 1]}).color(0, 1, 0, 0.25);

    CSG.snap(to, axis, orientation) ⇒ CSG

    Snap the object to another object. You can snap to the inside or outside of an object. Snapping to the z axis outside- will place the object on top of the to object. sphere.snap(cube, 'z', 'outside-') is saying that you want the bottom of the sphere (-) to be placed on the outside of the z axis of the cube.

    Click here for an example in openjscad.

    snap example

    Kind: static method of CSG
    Extends: CSG
    Chainable
    Returns: CSG - [description]

    Param Type Description
    to CSG object - The object to snap to.
    axis string Which axis to snap on ['x', 'y', 'z']. You can combine axes, ex: 'xy'
    orientation string Which side to snap to and in what direction (+ or -). ['outside+', 'outside-', 'inside+', 'inside-', 'center+', 'center-']

    Example

    include('dist/utils.jscad');
     
    // rename mainx to main
    function mainx() {
       util.init(CSG);
     
       var cube = CSG.cube({
           radius: 10
       }).setColor(1, 0, 0);
     
       var sphere = CSG.sphere({
           radius: 5
       }).setColor(0, 0, 1);
     
       return cube.union(sphere.snap(cube, 'z', 'outside-'));
    }

    CSG.midlineTo(axis, to) ⇒ CGE

    Moves an objects midpoint on an axis a certain distance. This is very useful when creating parts from mechanical drawings. For example, the RaspberryPi Hat Board Specification has several pieces with the midpoint measured. pi hat drawing To avoid converting the midpoint to the relative position, you can use midpointTo.

    Click here for an example in openjscad.

    midlineTo example

    Kind: static method of CSG
    Extends: CSG
    Chainable
    Returns: CGE - A translated CGE object.

    Param Type Description
    axis String Axis to move the object along.
    to Number The distance to move the midpoint of the object.

    Example

    include('dist/utils.jscad');
     
    // rename mainx to main
    function mainx() {
       util.init(CSG);
     
       // create a RPi hat board
       var board = Parts.Board(65, 56.5, 3).color('green');
     
       // a 40 pin gpio
       var gpio = Parts.Cube([52.2, 5, 8.5])
           .snap(board, 'z', 'outside+')
           .midlineTo('x', 29 + 3.5)
           .midlineTo('y', 49 + 3.5)
           .color('black')
     
       var camera_flex_slot = Parts.Board(2, 17, 1)
           .midlineTo('x', 45)
           .midlineTo('y', 11.5)
           .color('red');
     
       // This is more group, due to the outside 1mm          * roundover.
       // Create a board to work from first.  The spec
       // has the edge offset, not the midline listed as          * 19.5mm.
       // Bisect the cutout into two parts.
       var display_flex_cutout = Parts.Board(5, 17, 1)
           .translate([0, 19.5, 0])
           .bisect('x');
     
       // Bisect the outside (negative) part.
       var edges = display_flex_cutout.parts.negative.bisect('y');
     
       // Create a cube, and align it with the rounded edges
       // of the edge, subtract the edge from it and move it
       // to the other side of the coutout.
       var round1 = Parts.Cube([2, 2, 2])
           .snap(edges.parts.positive, 'xyz', 'inside-')
           .subtract(edges.parts.positive)
           .translate([0, 17, 0]);
     
       // Repeat for the opposite corner
       var round2 = Parts.Cube([2, 2, 2])
           .snap(edges.parts.negative, 'yz', 'inside+')
           .snap(edges.parts.negative, 'x', 'inside-')
           .subtract(edges.parts.negative)
           .translate([0, -17, 0]);
     
       // Create a cube cutout so the outside is square instead of rounded.
       // The `round1` and `round2` parts will be used to subtract off the rounded outside corner.
       var cutout = Parts.Cube(display_flex_cutout.parts.negative.size()).align(display_flex_cutout.parts.negative, 'xyz');
     
       return board
           .union(gpio)
           .subtract(camera_flex_slot)
           .subtract(union([display_flex_cutout.parts.positive,
               cutout
           ]))
           .subtract(round1)
           .subtract(round2);
    }

    CSG.align(to, axis) ↩︎

    Align with another object on the selected axis.

    Kind: static method of CSG
    Extends: CSG
    Chainable

    Param Type Description
    to CSG The object to align to.
    axis string A string indicating which axis to align, 'x', 'y', 'z', or any combination including 'xyz'.

    CSG.fit(x, y, z, a) ⇒ CSG

    Fit an object inside a bounding box. Often used to fit text on the face of an object. A zero for a size value will leave that axis untouched.

    Click here for an example in openjscad.

    fit example

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG - The new object fitted inside a bounding box

    Param Type Description
    x number | array size of x or array of axes
    y number | boolean size of y axis or a boolean too keep the aspect ratio if x is an array
    z number size of z axis
    a boolean Keep objects aspect ratio

    Example

    include('dist/utils.jscad');
     
    // rename mainx to main
    function mainx() {
       util.init(CSG);
     
       var cube = CSG.cube({
           radius: 10
       }).color('orange');
     
       // create a label, place it on top of the cube
       // and center it on the top face
       var label = util.label('hello')
           .snap(cube, 'z', 'outside-')
           .align(cube, 'xy');
     
       var s = cube.size();
       // fit the label to the cube (minus 2mm) while
       // keeping the aspect ratio of the text
       // and return the union
       return cube.union(label.fit([s.x - 2, s.y - 2, 0], true).color('blue'));
    }

    CSG.size() ⇒ CSG.Vector3D

    Returns the size of the object in a Vector3D object.

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG.Vector3D - A CSG.Vector3D with the size of the object.
    Example

    var cube = CSG.cube({
        radius: 10
    }).setColor(1, 0, 0);
     
    var size = cube.size()
     
    // size = {"x":20,"y":20,"z":20}

    CSG.centroid() ⇒ CSG.Vector3D

    Returns the centroid of the current objects bounding box.

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG.Vector3D - A CSG.Vector3D with the center of the object bounds.

    CSG.fillet(radius, orientation, options) ⇒ CSG

    Add a fillet or roundover to an object.

    Click here for an example in openjscad.

    fillet example

    Kind: static method of CSG
    Extends: CSG
    Chainable
    Returns: CSG - [description]

    Param Type Description
    radius number Radius of fillet. Positive and negative radius will create a fillet or a roundover.
    orientation string Axis and end (positive or negative) to place the chamfer. Currently on the z axis is supported.
    options object additional options.

    Example

    include('dist/utils.jscad');
     
    // rename mainx to main
    function mainx() {
    util.init(CSG);
     
    var cube = Parts.Cube([10, 10, 10]);
     
    return cube
      .fillet(2, 'z+') // roundover on top (positive fillet)
      .fillet(-2, 'z-') // fillet on  the bottom (negative fillet)
      .color('orange');
    }

    CSG.chamfer(radius, orientation) ⇒ CSG

    Add a chamfer to an object. This modifies the object by removing part of the object and reducing its size over the radius of the chamfer.

    Click here for an example in openjscad.

    chamfer example

    Kind: static method of CSG
    Extends: CSG
    Chainable
    Returns: CSG - [description]

    Param Type Description
    radius number Radius of the chamfer
    orientation string Axis and end (positive or negative) to place the chamfer. Currently on the z axis is supported.

    Example

    include('dist/utils.jscad');
     
    // rename mainx to main
    function mainx() {
    util.init(CSG);
     
    var cube = CSG.cube({
        radius: 10
    });
     
    return cube.chamfer(2, 'z+').color('orange');
    }

    CSG.bisect(axis, offset, angle, rotateaxis, rotateoffset) ⇒ object

    Cuts an object into two parts. You can modify the offset, otherwise two equal parts are created. The group part returned has a positive and negative half, cut along the desired axis.

    Click here for an example in openjscad.

    bisect example

    Kind: static method of CSG
    Extends: CSG
    Returns: object - A group group object with a parts dictionary and a combine() method.

    Param Type Description
    axis string Axis to cut the object
    offset number Offset to cut the object. Defaults to the middle of the object
    angle number angle to rotate the cut plane to
    rotateaxis number axis to rotate the cut plane around.
    rotateoffset number offset in the rotateaxis for the rotation point of the cut plane.

    CSG.stretch(object, axis, distance, offset) ⇒ CSG

    Wraps the stretchAtPlane call using the same logic as bisect. This cuts the object at the plane, and stretches the cross-section there by distance amount. The plane is located at the center of the axis unless an offset is given, then it is the offset from either end of the axis.

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG - The stretched object.

    Param Type Description
    object CSG Object to stretch
    axis String Axis to streatch along
    distance Number Distance to stretch
    offset Number Offset along the axis to cut the object

    CSG.unionIf(object, condition) ⇒ CSG

    Union only if the condition is true, otherwise the original object is returned. You can pass in a function that returns a CSG object that only gets evaluated if the condition is true.

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG - The resulting object.

    Param Type Description
    object CSG | function A CSG object to union with, or a function that reutrns a CSG object.
    condition boolean boolean value to determin if the object should perform the union.

    CSG.subtractIf(object, condition) ⇒ CSG

    Subtract only if the condition is true, otherwise the original object is returned. You can pass in a function that returns a CSG object that only gets evaluated if the condition is true.

    Kind: static method of CSG
    Extends: CSG
    Returns: CSG - The resulting object.

    Param Type Description
    object CSG | function A CSG object to union with, or a function that reutrns a CSG object.
    condition boolean boolean value to determin if the object should perform the subtraction.

    util

    jscad-utils

    util.identity(solid) ⇒ object

    A function that reutrns the first argument. Useful when passing in a callback to modify something, and you want a default functiont hat does nothing.

    Kind: static method of util
    Returns: object - the first parameter passed into the function.

    Param Type Description
    solid object an object that will be returned

    util.result(object, f) ⇒ object

    If f is a funciton, it is executed with object as the parameter. This is used in CSG.unionIf and CSG.subtractIf, allowing you to pass a function instead of an object. Since the function isn't exeuted until called, the object to union or subtract can be assembled only if the conditional is true.

    Kind: static method of util
    Returns: object - the result of the function or the object.

    Param Type Description
    object object the context to run the function with.
    f function | object if a funciton it is executed, othewise the object is returned.

    util.defaults(target, defaults) ⇒ object

    Returns target object with default values assigned. If values already exist, they are not set.

    Kind: static method of util
    Returns: object - Target object with default values assigned.

    Param Type Description
    target object The target object to return.
    defaults object Defalut values to add to the object if they don't already exist.

    util.print(msg, o)

    Print a message and CSG object bounds and size to the conosle.

    Kind: static method of util

    Param Type Description
    msg String Message to print
    o CSG A CSG object to print the bounds and size of.

    util.inch(x) ⇒ Number

    Convert an imperial inch to metric mm.

    Kind: static method of util
    Returns: Number - Result in mm

    Param Type Description
    x Number Value in inches

    util.cm(x) ⇒ Number

    Convert metric cm to imperial inch.

    Kind: static method of util
    Returns: Number - Result in inches

    Param Type Description
    x Number Value in cm

    util.segment(object, segments, axis) ⇒ Array

    Returns an array of positions along an object on a given axis.

    Kind: static method of util
    Returns: Array - An array of segment positions.

    Param Type Description
    object CSG The object to calculate the segments on.
    segments number The number of segments to create.
    axis string Axis to create the sgements on.

    util.map(o, f) ⇒ array

    Object map function, returns an array of the object mapped into an array.

    Kind: static method of util
    Returns: array - an array of the mapped object.

    Param Type Description
    o object Object to map
    f function function to apply on each key

    util.size(o) ⇒ CSG.Vector3D

    Returns a Vector3D with the size of the object.

    Kind: static method of util
    Returns: CSG.Vector3D - Vector3d with the size of the object

    Param Type Description
    o CSG A CSG like object or an array of CSG.Vector3D objects (the result of getBounds()).

    util.scale(size, value) ⇒ number

    Returns a scale factor (0.0-1.0) for an object that will resize it by a value in size units instead of percentages.

    Kind: static method of util
    Returns: number - Scale factor

    Param Type Description
    size number Object size
    value number Amount to add (negative values subtract) from the size of the object.

    util.enlarge(object, x, y, z, [options]) ⇒ CSG

    Enlarge an object by scale units, while keeping the same centroid. For example util.enlarge(o, 1, 1, 1) enlarges object o by 1mm in each access, while the centroid stays the same.

    Kind: static method of util
    Returns: CSG - [description]

    Param Type Default Description
    object CSG [description]
    x number [description]
    y number [description]
    z number [description]
    [options] Object { centroid: true } [description]

    util.fit(object, x, y, z, keep_aspect_ratio) ⇒ CSG

    Fit an object inside a bounding box. Often used with text labels.

    Kind: static method of util
    Returns: CSG - [description]

    Param Type Description
    object CSG [description]
    x number | array [description]
    y number [description]
    z number [description]
    keep_aspect_ratio boolean [description]

    util.flush(moveobj, withobj, axis, mside, wside) ⇒ CSG

    Moves an object flush with another object

    Kind: static method of util
    Returns: CSG - [description]

    Param Type Description
    moveobj CSG Object to move
    withobj CSG Object to make flush with
    axis String Which axis: 'x', 'y', 'z'
    mside Number 0 or 1
    wside Number 0 or 1

    util.group(names, objects) ⇒ object

    Creates a group object given a comma separated list of names, and an array or object. If an object is given, then the names list is used as the default parts used when the combine() function is called.

    You can call the combine() function with a list of parts you want combined into one.

    The map() funciton allows you to modify each part contained in the group object.

    Kind: static method of util
    Returns: object - An object that has a parts dictionary, a combine() and map() function.

    Param Type Description
    names string Comma separated list of part names.
    objects array | object Array or object of parts. If Array, the names list is used as names for each part.

    util.getDelta(size, bounds, axis, offset, nonzero) ⇒ Point

    Given an size, bounds and an axis, a Point along the axis will be returned. If no offset is given, then the midway point on the axis is returned. When the offset is positive, a point offset from the mininum axis is returned. When the offset is negative, the offset is subtracted from the axis maximum.

    Kind: static method of util
    Returns: Point - The point along the axis.

    Param Type Description
    size Size Size array of the object
    bounds Bounds Bounds of the object
    axis String Axis to find the point on
    offset Number Offset from either end
    nonzero Boolean When true, no offset values under 1e-4 are allowed.

    util.bisect(object, axis, offset, angle) ⇒ object

    Cut an object into two pieces, along a given axis. The offset allows you to move the cut plane along the cut axis. For example, a 10mm cube with an offset of 2, will create a 2mm side and an 8mm side.

    Negative offsets operate off of the larger side of the axes. In the previous example, an offset of -2 creates a 8mm side and a 2mm side.

    You can angle the cut plane and poistion the rotation point.

    bisect example

    Kind: static method of util
    Returns: object - Returns a group object with a parts object.

    Param Type Description
    object CSG object to bisect
    axis string axis to cut along
    offset number offset to cut at
    angle number angle to rotate the cut plane to

    util.stretch(object, axis, distance, offset) ⇒ CSG

    Wraps the stretchAtPlane call using the same logic as bisect.

    Kind: static method of util
    Returns: CSG - The stretched object.

    Param Type Description
    object CSG Object to stretch
    axis String Axis to stretch along
    distance Number Distance to stretch
    offset Number Offset along the axis to cut the object

    util.poly2solid(top, bottom, height) ⇒ CSG

    Takes two CSG polygons and createds a solid of height. Similar to CSG.extrude, excdept you can resize either polygon.

    Kind: static method of util
    Returns: CSG - generated solid

    Param Type Description
    top CAG Top polygon
    bottom CAG Bottom polygon
    height number heigth of solid

    util.init(CSG) ⇐ CSG

    Initialize jscad-utils and add utilities to the CSG object.

    Kind: static method of util
    Extends: CSG

    Param Type Description
    CSG CSG The global CSG object

    Colors

    Color utilities for jscad. Makes setting colors easier using css color names. Using .init() adds a .color() function to the CSG object.

    You must use Colors.init(CSG) in the main() function. The CSG class is not available before this.

    Example

    include('jscad-utils-color.jscad');
     
    function mainx(params) {
      Colors.init(CSG);
     
      // draws a purple cube
      return CSG.cube({radius: [10, 10, 10]}).color('purple');
    }

    jscad-utils-color.init(CSG) ⇐ CSG

    Initialize the Color utility. This adds a .color() prototype to the CSG object.

    Kind: static method of jscad-utils-color
    Extends: CSG

    Param Type Description
    CSG CSG The global CSG object

    Parts

    A collection of parts for use in jscad. Requires jscad-utils. parts example

    Example

    include('jscad-utils-color.jscad');
     
    function mainx(params) {
      util.init(CSG);
     
      // draws a blue hexagon
      return Parts.Hexagon(10, 5).color('blue');
    }

    Boxes

    jscad box and join utilities. This should be considered experimental, but there are some usefull utilities here.

    parts example

    Example

    include('dist/jscad-utils.jscad');
     
    function mainx(params) {
        util.init(CSG);
     
        var cyl = Parts.Cylinder(20, 20)
        var cbox = Boxes.Hollow(cyl, 3, function (box) {
          return box
              .fillet(2, 'z+')
              .fillet(2, 'z-');
        });
        var box = Boxes.Rabett(cbox, 3, 0.5, 11, 2)
        return box.parts.top.translate([0, 0, 10]).union(box.parts.bottom);
    }

    Boxes.Rabett(box, thickness, gap, height, face) ⇒ group

    This will bisect an object using a rabett join. Returns a group object with positive and negative parts.

    Kind: static method of Boxes
    Returns: group - A group object with positive, negative parts.

    Param Type Description
    box CSG The object to bisect.
    thickness Number Thickness of the objects walls.
    gap Number Gap between the join cheeks.
    height Number Offset from the bottom to bisect the object at. Negative numbers offset from the top.
    face Number Size of the join face.

    Boxes.RabettTopBottom(box, thickness, gap, options) ⇒ group

    Used on a hollow object, this will rabett out the top and/or bottom of the object.

    A hollow hexagon with removable top and bottom

    Kind: static method of Boxes
    Returns: group - An A hollow version of the original object..

    Param Type Description
    box CSG A hollow object.
    thickness Number The thickness of the object walls
    gap Number The gap between the top/bottom and the walls.
    options Object Options to have a removableTop or removableBottom. Both default to true.
    options.removableTop Boolean The top will be removable.
    options.removableBottom Boolean The bottom will be removable.

    Example

    include('dist/jscad-utils.jscad');
     
    function mainx(params) {
        util.init(CSG);
        var part = Parts.Hexagon(20, 10).color('orange');
        var cbox = Boxes.Hollow(part, 3);
     
        var box = Boxes.RabettTopBottom(cbox, 3, 0.25);
     
     
        return union([
            box.parts.top.translate([0, 0, 20]),
            box.parts.middle.translate([0, 0, 10]),
            box.parts.bottom
        ]);
    }

    Boxes.Hollow(object, thickness, interiorcb) ⇒ CSG

    Takes a solid object and returns a hollow version with a selected wall thickness. This is done by reducing the object by half the thickness and subtracting the reduced version from the original object.

    A hollowed out cylinder

    Kind: static method of Boxes
    Returns: CSG - An A hollow version of the original object..

    Param Type Description
    object CSG A CSG object
    thickness Number The thickness of the walls.
    interiorcb function A callback that allows processing the object before returning. * @param {Function} exteriorcb A callback that allows processing the object before returning.

    Boxes.BBox(o) ⇒ CSG

    Create a box that surounds the object.

    Kind: static method of Boxes
    Returns: CSG - The bounding box aligned with the object.

    Param Type Description
    o CSG The object to create a bounding box for.

    © 2016 John Cole johnwebbcole@gmail.com. Documented by jsdoc-to-markdown.

    Keywords

    Install

    npm i jscad-utils

    DownloadsWeekly Downloads

    2

    Version

    3.2.0

    License

    ISC

    Last publish

    Collaborators

    • johnwebbcole