Socket
Socket
Sign inDemoInstall

jscad-utils

Package Overview
Dependencies
2
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    jscad-utils

Utilities for use in a jscad script.


Version published
Weekly downloads
3
Maintainers
1
Install size
12.2 MB
Created
Weekly downloads
 

Readme

Source

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.

ParamTypeDescription
[red or css name]String | NumberCss color name or the red color channel value (0.0 - 1.0)
[green or alpha]Numbergreen color channel value (0.0 - 1.0) or the alpha channel when used with a css color string
[blue]Numberblue color channel value (0.0 - 1.0)
[alpha]Numberalpha 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]

ParamTypeDescription
toCSGobject - The object to snap to.
axisstringWhich axis to snap on ['x', 'y', 'z']. You can combine axes, ex: 'xy'
orientationstringWhich 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.

ParamTypeDescription
axisStringAxis to move the object along.
toNumberThe 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

ParamTypeDescription
toCSGThe object to align to.
axisstringA 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

ParamTypeDescription
xnumber | arraysize of x or array of axes
ynumber | booleansize of y axis or a boolean too keep the aspect ratio if x is an array
znumbersize of z axis
abooleanKeep 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]

ParamTypeDescription
radiusnumberRadius of fillet. Positive and negative radius will create a fillet or a roundover.
orientationstringAxis and end (positive or negative) to place the chamfer. Currently on the z axis is supported.
optionsobjectadditional 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]

ParamTypeDescription
radiusnumberRadius of the chamfer
orientationstringAxis 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.

ParamTypeDescription
axisstringAxis to cut the object
offsetnumberOffset to cut the object. Defaults to the middle of the object
anglenumberangle to rotate the cut plane to
rotateaxisnumberaxis to rotate the cut plane around.
rotateoffsetnumberoffset 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.

ParamTypeDescription
objectCSGObject to stretch
axisStringAxis to streatch along
distanceNumberDistance to stretch
offsetNumberOffset 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.

ParamTypeDescription
objectCSG | functionA CSG object to union with, or a function that reutrns a CSG object.
conditionbooleanboolean 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.

ParamTypeDescription
objectCSG | functionA CSG object to union with, or a function that reutrns a CSG object.
conditionbooleanboolean 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.

ParamTypeDescription
solidobjectan 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.

ParamTypeDescription
objectobjectthe context to run the function with.
ffunction | objectif 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.

ParamTypeDescription
targetobjectThe target object to return.
defaultsobjectDefalut 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

ParamTypeDescription
msgStringMessage to print
oCSGA 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

ParamTypeDescription
xNumberValue in inches

util.cm(x) ⇒ Number

Convert metric cm to imperial inch.

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

ParamTypeDescription
xNumberValue 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.

ParamTypeDescription
objectCSGThe object to calculate the segments on.
segmentsnumberThe number of segments to create.
axisstringAxis 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.

ParamTypeDescription
oobjectObject to map
ffunctionfunction 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

ParamTypeDescription
oCSGA 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

ParamTypeDescription
sizenumberObject size
valuenumberAmount 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]

ParamTypeDefaultDescription
objectCSG[description]
xnumber[description]
ynumber[description]
znumber[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]

ParamTypeDescription
objectCSG[description]
xnumber | array[description]
ynumber[description]
znumber[description]
keep_aspect_ratioboolean[description]

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

Moves an object flush with another object

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

ParamTypeDescription
moveobjCSGObject to move
withobjCSGObject to make flush with
axisStringWhich axis: 'x', 'y', 'z'
msideNumber0 or 1
wsideNumber0 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.

ParamTypeDescription
namesstringComma separated list of part names.
objectsarray | objectArray 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.

ParamTypeDescription
sizeSizeSize array of the object
boundsBoundsBounds of the object
axisStringAxis to find the point on
offsetNumberOffset from either end
nonzeroBooleanWhen 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.

ParamTypeDescription
objectCSGobject to bisect
axisstringaxis to cut along
offsetnumberoffset to cut at
anglenumberangle 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.

ParamTypeDescription
objectCSGObject to stretch
axisStringAxis to stretch along
distanceNumberDistance to stretch
offsetNumberOffset 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

ParamTypeDescription
topCAGTop polygon
bottomCAGBottom polygon
heightnumberheigth of solid

util.init(CSG) ⇐ CSG

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

Kind: static method of util
Extends: CSG

ParamTypeDescription
CSGCSGThe 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

ParamTypeDescription
CSGCSGThe 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.

ParamTypeDescription
boxCSGThe object to bisect.
thicknessNumberThickness of the objects walls.
gapNumberGap between the join cheeks.
heightNumberOffset from the bottom to bisect the object at. Negative numbers offset from the top.
faceNumberSize 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..

ParamTypeDescription
boxCSGA hollow object.
thicknessNumberThe thickness of the object walls
gapNumberThe gap between the top/bottom and the walls.
optionsObjectOptions to have a removableTop or removableBottom. Both default to true.
options.removableTopBooleanThe top will be removable.
options.removableBottomBooleanThe 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..

ParamTypeDescription
objectCSGA CSG object
thicknessNumberThe thickness of the walls.
interiorcbfunctionA 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.

ParamTypeDescription
oCSGThe object to create a bounding box for.

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

Keywords

FAQs

Last updated on 06 Jan 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc