Class: Polyhedron

PD. Polyhedron

A class for defining polyhedral shapes simply and efficiently.

This class extends the PD.Shape class by adding support for creating a range of known polyhedra types and implementing methods and techniques for the core Conway polyhedron notation modifiers.

The base requirement for the majority of these modifiers is a manifold shape with connected vertices and edges, which all of the polyhedra creation methods comply with. Some modifiers have more detailed requirements. For example, the inflate modifier assumes that the shape is roughly spherical, whilst some others assume a unit sphere with a radius of close to 1, which means that you really have to experiment with their arguments to get anything viable from larger or differently formed shapes. However, this is such a simple and flexible class that it can be used for many different things, so these restrictions don't always need to be met if you are not intending to apply those particular modifiers.

What is a Polyhedron

Polyhedra are three dimensional shapes that are formed by the connection of a finite number of closed planar polygons that each share connected edges and completely bound an internal volume. A particular polyhedra shape is referred to as a polyhedron.

Regular polyhedrons are formed from multiple instances of the same regular polygon, in which all sides/edges are straight, equiangular (all internal angles are equal in measure) and equilateral (all sides/edges have the same length).

Irregular polyhedrons can be formed from irregular polygons where each straight edge may be different in length and may even form a concave boundary. Whilst this class focusses mainly on non-self-intersecting polyhedrons, they too may be valid polyhedra.

Generators and Modifiers

This class started out as a means of creating and experimenting with commonly used polyhedron shapes. As a result, it provides static generator methods for Platonic, Archimedean, Catalan and Johnson solids, as well as prisms, anti-prisms, pyramids, cupola, rotunda, domes and spheres.

Something very important to note is that these static generators create shapes in which the radius of the farthest vertex from their geometric centre is equal to or close to 1. This makes them compatible with all of the polyhedron modifier recipes described in Polyhédronisme, but means that you will likely have to use the PD.Polyhedron#scale method once you have completed all modifications, or add the S modifier to your notation, If you don't apply a scale, they will be about 2mm in diameter and unlikely to be visible alongside other geometry within your model.

This scaling does not apply to polyhedra generated using PD.Shape factory methods as their input parameters often require world coordinates or dimensions. However, this makes these shapes less suitable for the application of polyhedron modifiers. Some modifiers will work without issue, but others will likely generate unusable results or require you to experiment heavily with their parameters to get anything useful from them.

As a result, you are encouraged to only scale the polyhedron after you have applied all modifiers. When you use the S modifier, it just sets a scale factor that is applied to the final result at the very end of the modifier sequence for exactly this reason.

Structure and Modifiers

A polyhedron is constructed from a set of spatial vertices that are shared by a series of connected edges which are, in turn, shared by a series of connected faces. To completely bound an internal volume, every vertex is shared by at least three edges and every edge is shared by exactly two faces. Each face is defined by a single outer boundary loop of vertices. A face in a polyhedron cannot contain internal hole boundaries, but must instead be broken down into a series of separate faces that bound the hole.

With the above caveats, there are a series of mathematical operations that can be reliably performed on valid polyhedra to generate incredibly complex and beautiful shapes that are also valid polyhedra. These work by dividing, truncating, expanding, inflating and/or rotating faces and edges. You can apply these operations to any valid polyhedron using the PD.Polyhedron#applyModifiers method or the PD.PolyhedronFactory class.

Array-Based Vertices

See the PD.Shape class documentation for more detailed information, but a key aspect of this polyhedron class is that all vertices are and must be stored as [x,y,z] vector arrays rather than point objects. This allows the polyhedron modifiers described in Polyhédronisme to be directly applied and supports the detailed array-based vector math they use.

To assist with the array-based vector math involved in the creation, modification and transformation of these kinds of forms, the framework provides the PD.VectorArray, PD.PlaneArray, PD.QuaternionArray and PD.MatrixArray classes. The framework also links in array-based vector geometry libraries for generating 2D and 3D convex hulls, surface triangulation and noise generation.


new Polyhedron( [vertices] [, faces] [, name])

Creates a new polyhedron.

Parameters:
Name Type Argument Description
vertices string | Array.<Array.<number>> <optional>

A type/notation string or a flat array of [x,y,z] vertex coordinates.

faces Array.<Array.<number>> <optional>

An array of face boundary arrays, each containing three or more vertex indices.

name string <optional>

A human-readable name for the shape.

Author:
  • drajmarsh

Extends

Members


:Array.<number>|Array.<Array.<number>>

colors

An array of [r,g,b] face colors.

This array is only valid if it is exactly the same length as the PD.Polyhedron#faces array. Each entry in this array is the color associated with the corresponding face in the faces array.

Type
  • Array.<number> | Array.<Array.<number>>
Inherited From:
Overrides:

:Array.<Array.<number>>

faces

An array of face boundary arrays, each containing three or more vertex indices.

Each face is an array of ordinal indices of the vertexes in the PD.Shape#vertices array that form its boundary.

Type
  • Array.<Array.<number>>
Inherited From:
Overrides:

:boolean

isPolyhedron <readonly>

A flag identifying this object as a polyhedron.

Type
  • boolean

:boolean

isShape <readonly>

A flag identifying this object as a shape.

Type
  • boolean
Inherited From:
Overrides:

:string

name

A human-readable name for the shape.

Type
  • string
Inherited From:
Overrides:

:Array.<Array.<number>>

vertices

A flat array of vertex coordinates stored as [x,y,z] vector arrays.

Each vertex is an array of three (3) numbers representing the X, Y and Z coordinates of a spatial point, referred to as an [x,y,z] vector array. These vertices are assembled into edges and boundaries by the PD.Shape#faces array.

Type
  • Array.<Array.<number>>
Inherited From:
Overrides:

:Array.<Array.<string>>

POLYHEDRA_NAMES <static>

Stores the names and type abbreviations for each type of known polyhedra and Johnson solids.

These include the five Platonic solids (0 to 4), the twelve Archimedean solids (5 to 17), Prisms (18 to 25), Antiprisms (26 to 33) and Johnson solids (34 to 126).

Each item in the list is a [name,type] array, where the name entry is a string containing the full name of the polyhedra and the type is a short string containing the code for that polyhedra that can be used with the PD.Polyhedron.fromType static method.

Type
  • Array.<Array.<string>>

:object

POLYHEDRA_TYPES <static>

Shortcuts for known polyhedra types.

Type
  • object

:boolean

cancelProgress <static>

A flag to cancel any current computation.

Type
  • boolean

:string

colorMethod <static>

Stores the current face color method.

Options are: 'area', 'edges', 'signature', 'none'.

Type
  • string

:number

colorSensitivity <static>

Stores the color sensitivity to variation in congruence signature or planar area.

Type
  • number

:Array.<number>

finalScale <static>

Stores a global [sx,sy,sz] scale vector set by the scale() modifier and applied only once all other modifiers have been processed.

Type
  • Array.<number>

:boolean

maintainUnitRadius <static>

Whether or not polyhedron processing should rescale to a unit radius after modifiers have been applied.

Some polyhedron modifiers work on the assumption that the shape is close to a unit sphere, and apply their factors based on that. You will quickly work out which ones they are as you apply them.

Set this to true if you want to apply those modifiers that work with a world-scale shape and not have it scaled in the process.

Type
  • boolean

:number

modifierKey <static>

Stores the current unique modifier key used to identify modifier objects in lists.

Type
  • number

:Array.<string>

modifierLog <static>

Stores a log of app;lied modifier descriptions.

Type
  • Array.<string>

:function

updateProgress <static>

An assignable callback method for updating progress.

Type
  • function

Methods


addVertex(vertex)

Retrieves the next reusable vertex in the surface, or creates and adds a new one.

The argument to this method can be either a simple [x,y,z] vector array or an {x,y,z} object such as a THREE.Vector3, PD.Point or similar object class. This method fetches from or creates vertices in vertexList by incrementing an internal counter that is reset to zero when the reuseStart() method is called.

Parameters:
Name Type Description
vertex Array.<number>

The [x,y,z] vector array to add to the vertex list.

Inherited From:
Overrides:
Returns:

Returns the index of the added vertex in the vertices list.

Type
number

align( [alignX] [, alignY] [, alignZ] [, point])

Moves this shape to align it in each axis with the given point.

The axial alignment values are given as fractions of the shape's extents in that axis. A value of zero in any axis means that the shape will align centrally at the point. A value of 1 means that shape will align its minimum edge at the point, and a value of -1 means that it will align its maximum edge. You can use any fractional values (eg: 0.5) or even multiples (eg: 2.5) in any axis.

Parameters:
Name Type Argument Description
alignX number <optional>

The X axis alignment factor (-1 to 1), defaults to 0.

alignY number <optional>

The Y axis alignment factor (-1 to 1), defaults to alignX.

alignZ number <optional>

The Z axis alignment factor (-1 to 1), defaults to alignX.

point Array.<number> <optional>

An [x,y,z] vector array for the point to align with, defaults to origin [0,0,0].

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const box = PD.Shape.cuboid(3000, 2000, 1000);
CAD.add(box.align(1, 1, 1));

ambo( [offset])

The Conway ambo operation is essentially the truncation of a shape by marking the midpoints of all its edges and cutting its vertices at those points.

The best way to think of the ambo operator is as a topological 'tween' between a polyhedron and its dual polyhedron. Thus the ambo of a dual polyhedron is the same as the ambo of the original.

Parameters:
Name Type Argument Description
offset number <optional>

The distance of the pyramid apex away from the face center in model units, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
/// Cupola-based space frame.
const poly = PD.Shape.cupola(9).scale(6000);
poly.ambo().ambo().triakis(9, 2000).join();
poly.translate([ 0, 0, -1800 ]).scale([ 1, 1, 2 ]).cutAt(0, 1);
const frame = PD.Shape.frame(poly, 250, 150);
CAD.add(frame);

applyAxis(axis)

Aligns this shape with the local coordinate axis.

Parameters:
Name Type Description
axis PD.AxisArray

The local coordinate axis to apply.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const segments = 12;

/// Create base shape to work on.
const cyl = PD.Shape.cylinder(segments, 1000, 500);

/// Create local coordinates.
const axis = new PD.AxisArray();
axis.moveOrigin(0, 2000, 0);
axis.rotateZ(Math.PI / 4);
cyl.applyAxis(axis);

/// Create different positive/negative scales.
const scale_positive = [3.50, 1.5, 1.0];
const scale_negative = [1.25, 1.5, 1.0];

/// Extract the bottom ring of vertices.
const base = cyl.vertices.slice(0, segments);

/// Apply both scales about the origin.
axis.scalePoints(base, scale_positive, scale_negative);
CAD.add(cyl);

applyMatrix(matrix)

Applies a transformation matrix to this shape.

Parameters:
Name Type Description
matrix Array.<number>

The 16-item (4x4) column-major matrix to apply.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

applyModifiers(modifiers)

Applies an array of modifier operations to this polyhedron.

The method performs all the required calculations synchronously, which can block the main thread of your application for several seconds for long modifier chains. To perform the calculations asynchronously with progress updates, use the PD.PolyhedronFactory.fromModifiers method instead.

Each modifier in the list is an object with an op property that is a string defining the operation to be performed and an args property which is an array of any numeric arguments the operation requires.

See the PD.Polyhedron.parseNotation method for details of the supported modifier operations and their arguments.

Parameters:
Name Type Description
modifiers Array.<object>

A list of modifier operations.

Returns:

Returns this polyhedra to support method chaining.

Type
PD.Polyhedron

applyNotation(notation)

Applies modifiers from a Conway notation string such as 'qoh(0.15,0.05)eeuz'.

See the PD.Polyhedron.parseNotation method for details of the supported modifier operations and their arguments.

Parameters:
Name Type Description
notation string

A string containing 'a(n,n)bcd9' modifier operations.

Returns:

Returns this polyhedra to support method chaining.

Type
PD.Polyhedron

applyQuaternion(quaternion)

Applies a rotational quaternion to this shape.

Parameters:
Name Type Description
quaternion Array.<number>

The [x,y,z,w] quaternion to apply.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

bevel( [sides])

The Conway bevel operation truncates the shape at its edges and vertices, creating a new facet in place of each edge and of each vertex.

If the sides argument is less than 3, all faces in the shape will be bevelled. If 3 or more, only those faces with a matching number of sides will be bevelled.

Parameters:
Name Type Argument Description
sides number <optional>

The number of sides as face must have to be affected, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const poly = new PD.Polyhedron('D12:S4000');
CAD.add(poly.clone().bevel().setRadius(3440));
CAD.add(poly);

centers()

Computes a list of face center points.

The center of each face is returned as an [x,y,z] vector array defining its spatial position in each major axis.

The order and index of center points in the returned list match the order and index of corresponding faces in the faces list.

Inherited From:
Overrides:
Returns:

Returns an array of face centers.

Type
Array.<Array.<number>>
Example
const shape = PD.Shape.domeGeodesic(4, 2000)

/// Find bottom face.
let bottom_face_index = -1;
let bottom_face_min_z = Infinity;
const face_centers = shape.centers();
for (let ii = 0; ii < face_centers.length; ++ii) {
    if (bottom_face_min_z > face_centers[ii][2]) {
        bottom_face_min_z = face_centers[ii][2];
        bottom_face_index = ii;
    }
}

/// Show bottom face as face.
if (bottom_face_index >= 0) {
    const points = shape.faces[bottom_face_index].map(index => shape.vertices[index]);
    CAD.addPolygon(points);
}

clone()

Creates a deep copy of this shape.

Inherited From:
Overrides:
Returns:

Returns a new shape.

Type
PD.Shape
Example
const shape = PD.Shape.prism(9, 1500, 1000).ortho();
CAD.add(shape.clone().inflate(200));
CAD.add(shape);

closestAndFarthestFromPlane(plane)

Computes the vertex positions that are closest to and farthest away from the given plane.

Parameters:
Name Type Description
plane number | Array.<number>

A [a,b,c,d] plane array or vertical height value in the Z axis to slice the shape at.

Inherited From:
Overrides:
Returns:

Returns a [closest,farthest] array of [x,y,z] vector arrays.

Type
Array.<Array.<number>>
Example
const slices = 4;
const plane = [  1,  0.25,  0,  10000 ];
const shape = PD.Shape.cuboid(4000, 2000, 1000);
const [ closest, farthest ] = shape.closestAndFarthestFromPlane(plane);
const start = -PD.VectorArray.dot(closest, plane);
const end = -PD.VectorArray.dot(farthest, plane);
const inc = (end - start) / (slices + 1);

for (let ii = 1; ii <= slices; ++ii) {
    plane[3] = start + (ii * inc);
    shape.cutAt(plane, 0);
}

CAD.addSolid(shape);
const frame = PD.Shape.frame(shape, 50, 50);
CAD.add(frame);

computeCentroid()

Computes the geometric center point of the shape by averaging all of its vertices.

Inherited From:
Overrides:
Returns:

Returns the centroid as an [x,y,z] vector arrays.

Type
Array.<number>

connections()

Computes and assembles the connection relationships between faces, edges and vertices.

This method returns an object with two arrays as properties:

  • vertices: An array of vertices with the indexes of each of the other vertices they connect to via an edge. This array is in the form [ v1, v2, v3, ... ] and uses the same ordinal indexes as the PD.Shape#vertices array.

  • edges An array of edges with two vertex indices followed by the indexes of the two faces they share. This array is in the form [ v1, v2, f1, f2 ].

The vertex indexes in the edges array are ordered such that the lowest ordinal index always comes first (array[0]) followed by the highest ordinal (array[1]). The face indexes are ordered such that, in the first face (array[2]), the direction of travel along the edge is from first vertex to second. In the second face (array[3]), the direction of travel is from the second vertex (array[1]) back to the first (array[0]).

Inherited From:
Overrides:
Returns:

Returns an array of vertex and edge connections.

Type
Array.<Array.<Array.<number>>>

copy(shape)

Performs a shallow copy of the data in the given shape.

Parameters:
Name Type Description
shape PD.Shape

The shape to copy from.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

copyToBRep(brep [, scale])

Copies polyhedron to the given surface.

Parameters:
Name Type Argument Description
brep PD.BRep

The BRep to add the polyhedron faces to.

scale number <optional>

An optional scale factor for the polyhedron, defaults to 1000mm (1m).

Overrides:
Returns:

Returns true if geometry was added to the surface. ??? @override -> jsdoc2md - RangeError: Maximum call stack size exceeded.

Type
boolean

cutAt(plane [, keep] [, cutFaces])

Cuts the faces of this shape by the given plane and either keeps all of them or just those in the front or behind.

Defining a Plane

This method uses an infinite plane to cut the shape, defined by an [a,b,c,d] plane array based on the Ax + Bx + Cz + D = 0 equation for a 3D plane. This means providing an array with four numbers that define the A, B, C and D components of the equation.

Alternatively, if you just want to cut a shape with a horizontal plane, you can pass a single number rather than a plane array. This number is used as the height on the Z axis of a cutting plane that faces towards the +Z axis.

The first three values in the plane array define its normal direction, which also defines the front and rear sides of the plane. Anything on the same side as the normal is pointing is in front, and anything on the other side is behind.

To make this method easier to use, the directional component of any given plane array does not need to be normalised as this will be done automatically. Thus, you could provide a plane array such as [ 1, 1, 1, -500 ] and it will be automatically normalized to [ 0.5773503, 0.5773503, 0.5773503, -500 ].

NOTE: When providing just a single number instead of a plane, it is important to remember that the number represents the plane height rather than the D component. Thus, a numeric value of 250 is equivalent to specifying [0,0,1,-250] as the plane array.

Which Side

You can choose to retain faces on both sides of the cut, or just those in front of or behind the cutting plane. To do this, set the value of keep to a positive number (usually 1) for faces in front of the plane, a negative number (usually -1) for faces behind the plane, or exactly zero (0) to keep both sides.

Accessing Cut Faces

If the value of keep is not zero, faces will be added to 'fill in' any openings created in the shape by the cut. If you set the value of cutFaces to an existing array, the new faces will be added to this array instead of directly to the shape. These faces will still reference vertices within the shape (which are shared by the existing faces that were actually cut), but this allows you an opportunity to discard or post-process them before adding them to the shape.

One action that is regularly performed on shapes is to do a cut and then extrude the 'fill in' faces in the opposite direction to create a base. As a result, this method provides a shortcut for for you to do this as part of the cutting process by passing a numeric value for cutFaces instead of an array. This numeric value must be positive, as shown in the second example below.

Parameters:
Name Type Argument Description
plane Array.<number> | number

An [a,b,c,d] plane array to cut the shape at or a height value in the +Z axis.

keep number <optional>

Which side(s) of the plane to retain (0:Both, 1:Front, -1:Rear), defaults to 0 (both).

cutFaces Array | number <optional>

An optional array in which to store any newly added cut faces. If given as a positive number instead of an array, it gives a distance by which to create a base by extruding cut surfaces in the opposite direction of the cutting plane.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Examples
const cut_faces = [];
const cut_plane = [ 0, 0, 1, 0 ];
const dome_with_holes = new PD.Polyhedron('D12:jh(0.15,0.025)ajejS9000');
dome_with_holes.cutAt(cut_plane, 1);
CAD.add(dome_with_holes);
/// Extrude cut faces to form support columns.
const cut_faces = [];
const cut_plane = [ 0, 0, 1, 0 ];
const poly = new PD.Polyhedron('D8:jeh(0.15,0.025)ajS9000');
const dome_with_holes = PD.Shape.cutAt(poly, cut_plane, 1, cut_faces).translate([ 0, 0, 3000 ]);
for (const face of cut_faces) {
    dome_with_holes.faceExtrude(face, -3000, cut_plane, 3);
}
CAD.add(dome_with_holes);

dual()

The Conway dual operation creates a new shape in which the centroid of each face in the original shape becomes a new vertex in the dual, and each vertex in the original becomes the centroid of a new face.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const poly = new PD.Polyhedron('D12:S4000');
CAD.add(poly.dual());

edges()

Computes a non-redundant list of the shape's edges.

The edges of a shape are simply arrays containing two integer values, being the ordinal indices of the start and end vertices of the edge within the PD.Shape#vertices array.

Inherited From:
Overrides:
Returns:

Returns an array of unique edges.

Type
Array.<Array.<number>>
Example
const poly = new PD.Polyhedron('D8:tk').scale(2000);

/// Display polyhedron as wires.
for (const edge of poly.edges()) {
    const points = edge.map(index => poly.vertices[index]);
    CAD.addWire(points, false);
}

/// Cut section and display as a face.
const section = PD.Shape.generateSection(poly, [ -1, -1, 4, -200 ]);
if (section?.faces) {
    CAD.addShell(section);
}

ensureOutwardOrientation()

Iterates the shape to ensure that all faces are oriented outwards relative to the geometric centre of the shape.

A face normal is considered to be pointing inwards if the dot product of its vector towards the centroid is positive, in which case the face is reversed.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

ensureOutwardOrientation_MoreRobust()

Iterates the shape to ensure that all faces are oriented outwards by referencing a known good face.

This method uses a reference face as a reference and compares all other to it. The reference face is determined as the one with a centre point at the most extreme edge in one of the major cartesian axis. To be facing 'outwards', the normal of the most extreme face in must point in the same direction as that axis. Once this condition is met, all other faces can be oriented relative to that one.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

expand()

The Conway expand operation is basically a double ambo operation, which is the truncation of a shape by marking the midpoints of all its edges and cutting its vertices at those points.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
/// Cupola-based space frame.
const poly = PD.Shape.anticupola(9).scale(9000);
poly.triakis(9, 2000).expand().join();
poly.translate([ 0, 0, -6700 ]).scale([ 1, 1, 3 ]).cutAt(0, 1);
const frame = PD.Shape.frame(poly, 250, 150);
CAD.add(frame);

extents( [min] [, max])

Computes the minimum and maximum extents of the shape.

Parameters:
Name Type Argument Description
min Array.<number> <optional>

An optional [x,y,z] vector array to receive the minimum extents.

max Array.<number> <optional>

An optional [x,y,z] vector array to receive the maximum extents.

Inherited From:
Overrides:
Returns:

Return a [min,max] array of two [x,y,z] vector arrays.

Type
Array.<Array.<number>>
Example
/// Create cylinder with 12 sides and 20 segments.
const shape = PD.Shape.cylinder(12, 2000, 5000, 20);

/// Compute range values in Z axis.
const [ min, max ] = shape.extents();
const bot_z = min[2] + ((max[2] - min[2]) * 0.25);
const top_z = min[2] + ((max[2] - min[2]) * 0.90);

/// Apply a scaling factor over the range.
shape.scaleByAxis(2, bot_z, top_z, 2.0, PD.Easing.inOutQuart);
CAD.add(shape);

extrudeBase(height [, segments])

Searches for the bottom-most face whose normal points in the -Z direction and extrudes it downwards by the given distance (height) and in the given number of segments.

Parameters:
Name Type Argument Description
height number

The height of the base to add to the shape, in model units.

segments number <optional>

The number of segments to extrude the base in, defaults to 1.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

faceCenter(face [, target])

Compute the geometric center of the given face.

The center of the face is returned as an [x,y,z] vector array defining its spatial position in each major axis.

Parameters:
Name Type Argument Description
face number | Array.<number>

The face to process, as an index within the faces array, or the actual array of vertex indices.

target Array.<number> <optional>

An optional [x,y,z] vector array to receive the calculated center, defaults to a new vector array.

Inherited From:
Overrides:
Returns:

Return an [x,y,z] vector array defining the face center.

Type
Array.<number>
Example
const shape = PD.Shape.domeGeodesic(4, 2000)

/// Display shape as wires.
for (const edge of shape.edges()) {
    const points = edge.map(index => shape.vertices[index]);
    CAD.addWire(points, false);
}

/// Find bottom face.
const center = [ 0, 0, 0 ];
let bottom_face_index = -1;
let bottom_face_value = Infinity;
for (let ii = 0; ii < shape.faces.length; ++ii) {
    shape.faceCenter(ii, center);
    if (bottom_face_value > center[2]) {
        bottom_face_value = center[2];
        bottom_face_index = ii;
    }
}

/// Show bottom face as face.
if (bottom_face_index >= 0) {
    const points = shape.faces[bottom_face_index].map(index => shape.vertices[index]);
    CAD.addPolygon(points);
}

faceExtrude(face, distance [, direction] [, segments])

Extrudes the given face in the given direction and distance.

This method displaces the given face and adds extruded side faces. If the optional segments argument has an integer value of greater than one (1), the extrusion will be done in a series of that many segments.

Parameters:
Name Type Argument Description
face number | Array.<number>

The face to process, as an index within the faces array, or the actual array of vertex indices.

distance number

The total distance to extrude, in model units.

direction Array.<number> <optional>

The direction to extrude in as an [x,y,z] vector array. defaults to the face's surface normal.

segments number <optional>

The number of segments to extrude the face in, defaults to 1.

Inherited From:
Overrides:
Returns:

Return an array of all the new faces just added.

Type
Array.<Array.<number>>
Example
const cut_faces = [];
const cut_plane = [ 0, 0, 1, 0 ];
const poly = new PD.Polyhedron('D8:jeh(0.15,0.025)ajS9000');
const dome_with_holes = PD.Shape.cutAt(poly, cut_plane, 1, cut_faces).translate([ 0, 0, 3000 ]);
for (const face of cut_faces) {
    dome_with_holes.faceExtrude(face, -3000, cut_plane, 3);
}
CAD.add(dome_with_holes);

faceInset(face [, inset] [, offset] [, normal])

Computes a set of vertices inset from the edges of the given face.

Parameters:
Name Type Argument Description
face number | Array.<number>

The face to process, as an index within the faces array, or the actual array of vertex indices.

inset number <optional>

An inset distance from each edge in model units, defaults to 0 (no inset).

offset number <optional>

An optional distance from face surface, defaults to 0 (no offset).

normal Array.<number> <optional>

An optional [x,y,z] vector array to receive the calculated face normal so you don't need to compute it again.

Inherited From:
Overrides:
Returns:

Return an array of new inset/offset vertices.

Type
Array.<Array.<number>>

faceNormal(face [, target])

Compute the surface normal of the given face.

The normal vector of the face is returned as an [x,y,z] vector array of unit length (normalized) defining its spatial direction in each major axis.

Parameters:
Name Type Argument Description
face number | Array.<number>

The face to process, as an index within the faces array, or the actual array of vertex indices.

target Array.<number> <optional>

An optional [x,y,z] vector array to receive the calculated normal, defaults to a new vector array.

Inherited From:
Overrides:
Returns:

Returns the modified target if it is given or a new [x,y,z] vector array defining the face normal.

Type
Array.<number>
Example
const distance = 250;
const face_normal = [];
for (let ii = 0; ii < shape.faces.length; ++ii) {
    for (const index of shape.faces[ii]) {
        hull_vertices.push(
            PD.VectorArray.translateInVectorDirection([], shape.vertices[index], face_normals[ii], distance)
        );
    }
}

faceVertices(face)

Retrieves the face as an array of actual vertices, being the [x,y,z] vector arrays representing each point on the face boundary.

NOTE: This method returns the actual vertex arrays from the shape vertex list, so any changes you make to the vertex arrays will propagate across all faces that share the same vertices.

Parameters:
Name Type Description
face number | Array.<number>

The face to process, as an index within the faces array, or the actual array of vertex indices.

Inherited From:
Overrides:
Returns:

Return an array of [x,y,z] vector array points the define the face boundary.

Type
Array.<Array.<number>>
Example
const shape = PD.Shape.domeGeodesic(4, 2000)

/// Find bottom face and show as filled polygon.
const bot_face = shape.findExtremeFace([ 0, 0, -1 ]);
if (bot_face.index >= 0) {
    const points = shape.faceVertices(bot_face.index);
    CAD.addPolygon(points);
}

/// Show rest of shape as wires.
for (const edge of shape.edges()) {
    const points = edge.map(index => shape.vertices[index]);
    CAD.addWire(points, false);
}

findExtremeFace( [normal])

Finds the face with a centre point at the extreme edge of the shape in one of the major cartesian axis.

This method is used to find a reference face to use for orienting all others. To be facing 'outwards', the normal of the most extreme face in one of the major axis must point in the same direction as that axis.

Parameters:
Name Type Argument Description
normal Array.<number> <optional>

An optional [x,y,z] vector array giving the direction to search in, defaults to any.

Inherited From:
Overrides:
Returns:

Returns an object with face, extreme.index and extreme.axis properties, being the actual face, its index in the faces array and the axis (0, 1 or 2).

Type
object
Examples
const { face, index, axis } = shape.findExtremeFace();

/// Ensure extreme face normal points in same direction as extreme axis.
PD.VectorArray.calcNormalFromIndexedPathNewellMethod(normal, face, this.vertices);
if (normal[axis] < 0) {
     face.reverse();
}
const shape = PD.Shape.domeGeodesic(4, 2000)

/// Find bottom face and show as filled polygon.
const bot_face = shape.findExtremeFace([ 0, 0, -1 ]);
if (bot_face.index >= 0) {
    const points = shape.faceVertices(bot_face.index);
    CAD.addPolygon(points);
}

/// Display shape as wires.
for (const edge of shape.edges()) {
    const points = edge.map(index => shape.vertices[index]);
    CAD.addWire(points, false);
}

frame( [inset] [, thickness] [, glazing])

The frame operation essentially hollows out the shape and generates a structural frame with bars running along each of its edges.

Parameters:
Name Type Argument Description
inset number <optional>

The inset width of framing bars, defaults to 25mm.

thickness number <optional>

The framing bar thickness as a positive value, defaults to 50mm.

glazing boolean <optional>

Whether or not to generate glazing panes between frames.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
/// Cupola-based space frame.
const shape = PD.Shape.anticupola(9).scale(9000);
shape.scale([1, 1, 3]).triakis(9, 2000).expand().join();
shape.translate([0, 0, -7500]).cutAt(0, 1);
shape.frame(250, 150);
CAD.add(shape);

fromDSV(text [, separator] [, zeroBased])

Attempts to parse polyhedron data from delimiter-separated values.

NOTE: This method can also be used to parse simple Wavefront OBJ files if they contain a single object/group.

Parameters:
Name Type Argument Default Description
text string

A delimiter-separated values data string.

separator string <optional>
,

The delimiter to separate values with, defaults to a comma.

zeroBased string <optional>
true

Whether or not vertex indices in faces start at zero rather than one, defaults to true.

Returns:

Returns true if DSV data was parsed and the polyhedron geometry was updated.

Type
boolean

fromJSON(data)

Safely copy properties from a source object.

See the PD.Base#fromJSON method for more details.

NOTE: If vertexes are given as [x,y,z] vector arrays, and faces as arrays of ordinal indexes, then both the faces and vertices data arrays are used directly rather than copied to the shape. This makes creating shapes from JSON very fast and efficient, which is important as this class is used quite a lot for data exchange. If you want to deep copy the data arrays, see the example code below:

Parameters:
Name Type Description
data object

The source object containing data to copy.

Inherited From:
Overrides:
Returns:

Returns this instance to support method chaining.

Type
PD.Shape
Example
const shallow_copy = new PD.Shape().fromJSON(data);
const deep_copy = new PD.Shape().fromJSON(data).clone();

fromMcCooeyFormat(text)

Attempts to parse polyhedron data from McCooey (https://dmccooey.com/polyhedra/).

Parameters:
Name Type Description
text string

A McCooey formatted data string.

Returns:

Returns true if McCooey formatted data was parsed and the polyhedron geometry was updated.

Type
boolean

fromOBJ(text)

Attempts to parse polyhedron data from simple OBJ data.

As the rules for modifying manifold polyhedron geometry are reasonably tight, you should only load relatively simple closed shell geometry if you want standard modifiers to work.

Parameters:
Name Type Description
text string

A Wavefront OBJ data string.

Returns:

Returns true if OBJ data was parsed and the polyhedron geometry was updated.

Type
boolean

fromPLY(text)

Attempts to parse polyhedron data from Polygon File Format data.

As the rules for modifying manifold polyhedron geometry are reasonably tight, you should only load relatively simple closed shell geometry if you want standard modifiers to work.

Parameters:
Name Type Description
text string

A Polygon File Format data string.

Returns:

Returns true if PLY data was parsed and the polyhedron geometry was updated.

Type
boolean

fromSTL(text)

Attempts to parse polyhedron data from STL format data.

As the rules for modifying manifold polyhedron geometry are reasonably tight, you should only load relatively simple closed shell geometry if you want standard modifiers to work.

Parameters:
Name Type Description
text string

A STL format data string.

Returns:

Returns true if STL data was parsed and the polyhedron geometry was updated.

Type
boolean

fromVRML(text)

Attempts to parse polyhedron data from VRML/WRL data.

As the rules for modifying manifold polyhedron geometry are reasonably tight, you should only load relatively simple closed shell geometry if you want standard modifiers to work.

Parameters:
Name Type Description
text string

A VRML/WRL data string.

Returns:

Returns true if VRML data was parsed and the polyhedron geometry was updated.

Type
boolean

fromX3D(text)

Attempts to parse polyhedron data from XML X3D data.

As the rules for modifying manifold polyhedron geometry are reasonably tight, you should only load relatively simple closed shell geometry if you want standard modifiers to work.

Parameters:
Name Type Description
text string

An XML X3D data string.

Returns:

Returns true if X3D data was parsed and the polyhedron geometry was updated.

Type
boolean

gyro( [offset] [, fraction])

The Conway gyro operation creates a new shape in which a new face is created at each vertex of its dual, which is then twisted slightly and two new triangular faces added to replace each edges and fill the gaps.

NOTE: When using an offset value not equal to zero, this operation will often create non-planar faces. If that is detected, then the resulting faces will be automatically triangulated.

Parameters:
Name Type Argument Description
offset number <optional>

The distance of the center apex away from the face center in model units, defaults to 0.

fraction number <optional>

The face rotation fraction (0.001 to 0.999), defaults to 1/3.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const shape = PD.Shape.cuboid();
shape.gyro().triangulate().scale(5000);
CAD.add(shape);

hasContent()

Determines whether or not the shape has any content.

This method does a very simple check to see if there are any vertices and any faces. It doesn't do any validity or sanity checking, just looks for content.

Inherited From:
Overrides:
Returns:

Returns true if shape has one or more valid edge/facet.

Type
boolean

importGeometry(text [, detectOnly])

Checks the given text for a recognisable and importable geometry data format and, if found imports it.

Parameters:
Name Type Argument Default Description
text string

The textual content of a geometry file.

detectOnly boolean <optional>
false

When true, only the format is returned without loading the geometry, defaults to false

Returns:

Returns a format string such as json, mcc, obj, etc.

Type
string

inflate(distance [, checkPlanes])

Expand all vertices in the direction of their surface normals by the given distance.

Expansion is different from offsetting in that the given distance refers to the movement of each vertex rather than to each face. Vertices move in the direction of their average surface normals, which is effectively the normalised sum of each face normal that the vertex is shared by. Movement is outwards if the distance is positive or inwards if it is negative.

The result is a set of vertices that are exactly the given distance away from their original positions. Depending on the number of faces shared by each vertex, and their relative orientations, this may result in faces changing orientation slightly and not being parallel to their original position. In some rare cases it may even result in faces that are no longer planar.

If you want to specify the exact perturbation distance of faces rather than vertices use the PD.Shape#offset method instead.

Parameters:
Name Type Argument Description
distance number

The expansion distance, defaults to 0.

checkPlanes number <optional>

Extra checks (0:None, 1:OnePlane, 2:AllPlanes), defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const shape = PD.Shape.prism(9, 1500, 1000).ortho();
CAD.add(shape.clone().inflate(200));
CAD.add(shape);

info()

Get some informative about the polyhedron as a string.

Returns:

Return basic polyhedra information.

Type
string

join()

The Conway join operation is basically an ambo operation performed on the dual of the original shape, then converted back to a dual.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
/// Cupola-based space frame.
const poly = PD.Shape.cupola(9).scale(12000);
poly.join().expand().triakis(9, 2000).join();
poly.translate([ 0, 0, -6700 ]).scale([ 1, 1, 3 ]).cutAt(0, 1);
const frame = PD.Shape.frame(poly, 250, 150);
CAD.add(frame);

loft( [sides] [, inset] [, offset])

The loft operation insets each edge of the specified faces and creates new quad faces to fill the gap.

If the sides argument is less than 3, all faces in the shape will be lofted. If 3 or more, only those faces with a matching number of sides will be lofted.

If an inset value is given, then the apex of the pyramid will be positioned that far away from the geometric centre of the face in the direction of its surface normal.

This method differs from the Conway Polyhedron Notation version in that the inset and offset distances are given in model units rather than as a fraction of shape radius.

Parameters:
Name Type Argument Description
sides number <optional>

The number of sides as face must have to be affected, defaults to 0.

inset number <optional>

An inset distance from each edge in model units, defaults to 0 (no inset).

offset number <optional>

An optional distance from face surface in model units, defaults to 0 (no offset).

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

makeDefaultShape()

Makes this shape a 4-sided unit tetrahedron as the default shape for empty shapes.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

meta( [sides])

The Conway meta operation is basically the join of a triakis operation.

If the sides argument is less than 3, all faces in the shape will be bevelled. If 3 or more, only those faces with a matching number of sides will be bevelled.

Parameters:
Name Type Argument Description
sides number <optional>

The number of sides as face must have to be affected, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

minEdgeLength()

Computes the minimum edge length.

Returns:

Returns the minimum edge length.

Type
number

minFaceRadius()

Computes the minimum face radius.

Returns:

Returns the minimum face radius.

Type
number

modify(op, args)

Applies a Conway notation modifier to this polyhedron.

See the PD.Polyhedron.parseNotation method for details of the supported modifier operations and their arguments.

You can also use the full modifier names

Parameters:
Name Type Argument Description
op string

The operational modifier.

args number <repeatable>

The numeric arguments for the operation.

Returns:

Returns this polyhedra to support method chaining.

Type
PD.Polyhedron

moreInfo()

Get more informative data about the polyhedron as a string.

Returns:

Return more detailed polyhedra information.

Type
string

noiseXY( [amplitude] [, scale] [, offset])

The noiseXY operation applies some X and Y axis spatial variation to each vertex in the shape based on the amplitude, scale and offset values.

The amplitude, scale and offset values are all applied to the Perlin noise function when it is run for each vertex. You can specify the scale and offset as either [x,y,z] vector arrays to control the variation in each axis, or as single numbers which will be applied equally to all axis.

This method differs from the Conway Polyhedron Notation version in that the amplitude, scale and offset distances are all given in model units rather than as a fraction of shape radius.

To have a noticeable effect, the amplitude and scale values cannot be too small relative to the shape size, so you will typically need to experiment a bit with this.

Parameters:
Name Type Argument Description
amplitude number <optional>

Effectively the magnitude of the spatial variation in model units, defaults to 250mm.

scale number | Array.<number> <optional>

A scale factor or [sx,sy,sz] vector array in model units, defaults to 1000mm (1m).

offset number | Array.<number> <optional>

A phase offset as a number or [dx,dy,dz] vector array in model units, defaults to 0 (no offset).

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const shape = PD.Shape.cylinder(72, 2000, 5000, 36);
shape.noiseXY(5000, 3000, 5000).setRadiusXY(6000);
CAD.add(shape);

normals()

Computes a list of face normal vectors.

The normal vector of each face is returned as an [x,y,z] vector array of unit length (normalized) defining its spatial direction in each major axis.

The order and index of normals in the returned list match the order and index of corresponding faces in the faces list.

Inherited From:
Overrides:
Returns:

Return an array of face normals.

Type
Array.<Array.<number>>
Example
const distance = 250;
const face_normals = shape.normals();
for (let ii = 0; ii < shape.faces.length; ++ii) {
    for (const index of shape.faces[ii]) {
        hull_vertices.push(
            PD.VectorArray.translateInVectorDirection([], shape.vertices[index], face_normals[ii], distance)
        );
    }
}

offset(distance [, detail])

Modifies the shape by expanding all facets in the direction of their surface normals by the given distance, but maintaining their exact shape and surface area.

This process moves existing faces outwards and adds additional faces to cover the now open gaps and seams between them. The benefit of this method is that you can offset any convex shape by any positive amount, even many thousands of times its radius, and still have a valid shape shape.

Unfortunately this isn't true of concave shapes or when the distance value is negative. In these cases, maintaining the shape and area of facets isn't possible as they simply have to shrink in order to fit. As a result, this method will redirect to the PD.Shape#expand method when the given distance is less than zero.

Parameters:
Name Type Argument Description
distance number

The explosion distance as a positive value, defaults to 0 (no change).

detail number <optional>

The geometric detail at each corner (0 to 2), defaults to 2.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

offsetHull(distance [, detail])

Modifies the shape by generating a convex hull offsetting all vertices, edges and facets by their surface normals, but maintaining the exact shape and surface area of each facet.

This process modifies this shape by creating new vertex positions for all faces, but they will be the same size and orientation, just offset by the given distance. It also adds additional vertices and faces to fill in the seams and gaps between the exploded faces.

Parameters:
Name Type Argument Description
distance number

The explosion distance, defaults to 0.

detail number <optional>

The geometric detail at each corner (0 to 32), defaults to 1.

Inherited From:
Overrides:
Returns:

Returns this modified shape.

Type
PD.Shape

openEdgeLoops()

Collects all edges that are not shared by two faces and assembles them into an array of one or more loops.

This method relies on all coincident edges sharing the same vertices, which means that the shape cannot have 'T' junctions where two faces meet somewhere along the edge of another face where it doesn't have a vertex. If you are not absolutely sure of the inter-connection state of your shape, call the PD.Shape#weld method first.

The loops generated by this method will likely be closed but not be planar. If the shape is more like an open surface, you should end up with one big outer boundary loop. If the shape is mostly closed, but has some holes within it, you should end up with loops for each hole.

You will need to work out how best to close a shape if you find that it has open edges.

The vertex indexes in the edges array are ordered such that the lowest ordinal index always comes first (array[0]) followed by the highest ordinal (array[1]).

Inherited From:
Overrides:
Returns:

Returns an array of open edge loops.

Type
Array.<Array.<number>>
Example
/// Collect open edges and fill in top and bottom holes.
const super_shape = PD.Shape.superFormula({ innerRadius: 0.5, unfoldZ: 0.125 });
super_shape.scale(500).setRadiusXY(5000).weld();
const open_edges = super_shape.openEdgeLoops();
for (const loop of open_edges) {
    super_shape.faces.push(loop);
}

CAD.add(super_shape);

ortho()

The Conway ortho operation is effectively a double join operation.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

perlinNoise( [amplitude] [, scale] [, offset])

The Perlin noise operation applies some spatial variation to each vertex in the shape based on the amplitude, scale and offset values.

The amplitude, scale and offset values are all applied to the Perlin noise function when it is run for each vertex. You can specify the scale and offset as either [x,y,z] vector arrays to control the variation in each axis, or as single numbers which will be applied equally to all axis.

This method differs from the Conway Polyhedron Notation version in that the amplitude, scale and offset distances are all given in model units rather than as a fraction of shape radius.

To have a noticeable effect, the amplitude and scale values cannot be too small relative to the shape size, so you will typically need to experiment a bit with this.

Parameters:
Name Type Argument Description
amplitude number <optional>

Effectively the magnitude of the spatial variation in model units, defaults to 250mm.

scale number | Array.<number> <optional>

A scale factor or [sx,sy,sz] vector array in model units, defaults to 1000mm (1m).

offset number | Array.<number> <optional>

A phase offset as a number or [dx,dy,dz] vector array in model units, defaults to 0 (no offset).

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const shape = PD.Shape.cylinder(72, 2000, 5000, 36);
shape.perlinNoise(5000, 3000, 5000).setRadiusXY(6000);
CAD.add(shape);

propellor( [fraction])

The Conway propellor extended operation creates new skewed faces by making new points along each edge, 1/3rd the distance from v1- > v2, then connecting these into a new inset face. This breaks any rotational symmetry about the faces.

Parameters:
Name Type Argument Description
fraction number <optional>

The face rotation fraction (0.001 to 0.999), defaults to 1/3.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const shape = PD.Shape.anticupola(9).scale(9000);
shape.propellor();
CAD.add(shape);

reverse()

Reverses the orientation of all faces in the shape.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

rotate(origin, axis, angle)

Rotates the shape around the given origin/axis by the given angle.

The origin is effectively the point about which the rotation should take place. It is subtracted from each point prior to the rotation, then added back afterwards.

Parameters:
Name Type Description
origin Array.<number>

The [x,y,z] vector array defining the origin point to rotate about.

axis Array.<number>

The [x,y,z] vector array defining the axial vector to rotate around.

angle number

The angle of rotation, in radians.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

scale(scale)

Applies a scaling factor to this shape.

Parameters:
Name Type Description
scale number | Array.<number>

A scale factor or [sx,sy,sz] vector array to multiple vertices by.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

scaleByAxis(axis, from, to, scale [, easing])

Scales the shape in the other two axis by an amount that varies over a range within the given axis.

If the from and to values are both in the range 0 to 1, then they are considered to be fractions of the size of the shape in the given axis. If either value is outside the range 0 to 1, then they are both considered to be in absolute model units along the axis.

You can use the PD.Shape#extents method if you want to find out the size range of your specific shape in each axis.

If the scale is given as a single number, it represents the maximum scale at the to point on the axis, varying from 1 at the from point. If given as a [fromScale, toScale] array, you can specify the scales to use at both the from and to points. You can specify an easing function if you wish to make it a non-linear variation.

If you choose the Z axis, then the varying scale will be applied to the X and Y components of each vertex in the shape. If you choose the X axis the scale will be applied in Y and Z, and for the Y axis, it will be applied in X and Z.

If you wish to scale vertexes in a non-Cartesian axis or about a point other than the origin, use the PD.AxisArray#scalePointsInXY method instead.

Parameters:
Name Type Argument Description
axis number

The axis to scale in (0:X, 1:Y or 2:Z).

from number

A value on the given axis to start scaling from ,in model units.

to number

A value on the given axis to finish scaling at, in model units.

scale number | Array.<number>

The scale at or above the to value, or a [fromScale,toScale] array, defaults to 1 (no scale).

easing function <optional>

An easing function to use, defaults to PD.Easing.linear.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
/// Scale cylinder with 12 sides and 20 segments.
const shape = PD.Shape.cylinder(12, 2000, 5000, 10);
shape.scaleByAxis(2, 0, 1, 2.0, PD.Easing.inOutQuint);
CAD.add(shape);

const frame = PD.Shape.frame(shape, 25, 50);
CAD.add(frame);

setColor(color)

Assigns a single color to all faces of the shape.

This method is a convenience method for setting the colors array to a single color value.

NOTE: This method overwrites any existing data in the colors array.

Parameters:
Name Type Description
color Array.<number>

The color to assign all faces, as an [r,g,b] array.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape

setHeight( [height])

Rescales all vertices so that the maximum range of the shape in the Z axis is equal to the given height.

NOTE: This method assumes that the shape is centred at the origin.

Parameters:
Name Type Argument Description
height number <optional>

The height to normalise shape to, defaults to 1.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const super_shape = PD.Shape.superFormula();
super_shape.setHeight(2500).setRadiusXY(3500);
CAD.add(super_shape);

setRadius( [radius])

Rescales all vertices so that the maximum radius of the shape from the origin in all axis is equal to the given radius.

If you want to set the size based on the actual extents of the shape, use the PD.Shape#setRadius method instead.

NOTE: This method assumes that the shape is centred at the origin.

Parameters:
Name Type Argument Description
radius number <optional>

The radius to normalise shape to, defaults to 1.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const poly = new PD.Polyhedron('D12:S4000');
CAD.add(PD.Shape.bevel(poly).setRadius(3440));
CAD.add(poly);

setRadiusXY( [radius] [, height])

Rescales all vertices so that the maximum radius of the shape in the X and Y axis is equal to the given radius.

If you provide the optional height argument, the height of the shape in the Z axis will be normalised to that too,

NOTE: This method assumes that the shape is centred at the origin.

Parameters:
Name Type Argument Description
radius number <optional>

The radius to normalise shape to, defaults to 1.

height number <optional>

The height to normalise shape to, defaults to 1.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const super_shape = PD.Shape.superFormula();
super_shape.setHeight(2500).setRadiusXY(3500);
CAD.add(super_shape);

setSize( [sizeX] [, sizeY] [, sizeZ])

Rescales all vertices so that the dimensions of the shape's bounding box in each of the X, Y and Z axis is as given.

This method differs from PD.Shape#setRadius in that it is based on the bounding box (extents) of the shape rather than the distance of vertices from its centre.

Parameters:
Name Type Argument Description
sizeX number <optional>

The width of the shape in the X-axis, defaults to 1.

sizeY number <optional>

The depth of the shape in the Y-axis, defaults to width.

sizeZ number <optional>

The height of the shape in the X-axis, defaults to width.

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const super_shape = PD.Shape.superFormula();
super_shape.setSize(5000, 5000, 3500);
CAD.add(super_shape);

snub()

The Conway snub operation creates a new shape which is basically a PD.Shape.gyro operation performed on the dual of the shape. It creates a new face for each vertex, which is then twisted slightly and two new triangular faces added to replace each edges and fill the gaps.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
const shape = new PD.Polyhedron('D12:S5000');
CAD.add(shape.clone().snub().scale(1.2835));
CAD.add(shape);

stretchByAxis(axis, from, to [, scale] [, easing])

Stretches the vertices of shape over a range in the given axis.

If the from and to values are both in the range 0 to 1, then they are considered to be fractions of the size of the shape in the given axis. If either value is outside the range 0 to 1, then they are both considered to be in absolute model units along the axis.

You can use the PD.Shape#extents method if you want to find out the size range of your specific shape in each axis.

Parameters:
Name Type Argument Description
axis number

The X, Y or Z axis to use (0:X, 1:Y, 2:Z).

from number

A value on the given axis to start stretching from in model units.

to number

A value on the given axis to finish stretching at in model units.

scale number <optional>

The amount to scale the axis range area by, defaults to 1 (no scale).

easing function <optional>

An easing function to use, defaults to PD.Easing.linear.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Examples
/// Stretch cylinder with 12 sides and 20 segments.
const shape = PD.Shape.cylinder(12, 2000, 2500, 10);
shape.stretchByAxis(2, 0.25, 1.0, 2.0, PD.Easing.inOutCubic);
CAD.add(shape);

const frame = PD.Shape.frame(shape, 25, 50);
CAD.add(frame);
/// Stretch cylinder with 24 sides and 10 segments.
const shape = PD.Shape.cylinder(24, 2000, 2500, 10);
shape.stretchByAxis(0, 0, 1, 4.0, PD.Easing.inOutQuint);
shape.stretchByAxis(2, 0, 1, 2.0, PD.Easing.outCubic);
shape.meta().cutAt(1700, 1).cutAt(7000, -1).translate([ 0, 0, -1700 ]);
CAD.add(shape);

const frame = PD.Shape.frame(shape, 25, 25).expand().ambo().join();
CAD.add(frame);

toDSV( [separator])

Formats the polyhedron geometry as delimiter-separated values.

If no separator is given it defaults to a comma-separated value format.

Parameters:
Name Type Argument Default Description
separator string <optional>
,

The delimiter to separate values with, defaults to a comma.

Returns:

Returns a DSV string.

Type
string

toFormattedJSON( [compact])

Formats the polyhedron geometry as a compact or human-readable JSON string.

Parameters:
Name Type Argument Default Description
compact string <optional>
false

Generate a more compact form with edges.

Returns:

Returns a human-readable JSON string.

Type
string

toJSON( [data])

Converts the object instance to a simple POJO for JSON storage.

This method is used to copy, store and save the data for ths object, so the returned object must have all the properties required be able to rebuild this instance in its entirety when passed to the class constructor.

NOTE: As vertexes are simple [x,y,z] vector arrays and each face is just an array of ordinal vertex indexes, both the faces and vertices arrays are used directly by the JSON object rather than being copied. This makes converting shapes to JSON very fast and efficient, which is important as this class is used quite a lot for data exchange. If you want to deep copy the data arrays, see the example code below:

Parameters:
Name Type Argument Description
data object <optional>

An optional parent object to append this data to.

Inherited From:
Overrides:
Returns:

Returns a JSON object.

Type
object
Example
const shallow_copy = shape.toJSON();
const deep_copy = shape.clone().toJSON();

toMcCooeyFormat()

Formats the polyhedron geometry as per McCooey (https://dmccooey.com/polyhedra/),

Returns:

Returns a McCooey formatted string.

Type
string

toOBJ(scale)

Produces a simple OBJ file for import into 3D apps.

Parameters:
Name Type Description
scale Array.<number>

An [sx,sy,sz] scale array.

Returns:

Returns the contents of an OBJ file representing the polyhedra.

Type
string

toPLY(scale)

Generates the polyhedron in Polygon File Format.

Parameters:
Name Type Description
scale Array.<number>

An [sx,sy,sz] scale array.

Returns:

Returns the contents of a PLY files representing the polyhedra.

Type
string

toSTL(scale)

Produces an STL file for 3D printing.

Parameters:
Name Type Description
scale Array.<number>

An [sx,sy,sz] scale array.

Returns:

Returns the contents of an STL files representing the polyhedra.

Type
string

toVRML(scale)

Produces an VRML/WRL file for 3D printing.

Parameters:
Name Type Description
scale Array.<number>

An [sx,sy,sz] scale array.

Returns:

Returns a the contents of an VRML files representing the polyhedra.

Type
string

toX3D(scale)

Produces an X3D file for 3D printing.

Parameters:
Name Type Description
scale Array.<number>

An [sx,sy,sz] scale array.

Returns:

Returns the contents of an X3D files representing the polyhedra.

Type
string

translate(offset)

Applies a [dx,dy,dz] translation to this shape.

Parameters:
Name Type Description
offset Array.<number>

A [x,y,z] vector array to move by.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

triakis( [sides] [, offset])

The Conway triakis operation divides specified faces into triangles to form a pyramid with its apex at the center of the face.

If the sides argument is less than 3, all faces in the shape will be divided. If 3 or more, only those faces with a matching number of sides will be divided.

If an offset value is given, then the apex of the pyramid will be positioned that far away from the geometric centre of the face in the direction of its surface normal.

This method differs from the Conway Polyhedron Notation version in that the offset distance is given in model units rather than as a fraction of shape radius.

Parameters:
Name Type Argument Description
sides Array.<number> | number <optional>

An array or face indexes or the number of sides a face must have to be affected, defaults to 0.

offset number <optional>

The distance of the pyramid apex away from the face center in model units, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Example
/// Cupola-based space frame.
const poly = PD.Shape.cupola(9).scale(12000);
poly.join().expand().triakis(9, 2000).join();
poly.translate([ 0, 0, -6700 ]).scale([ 1, 1, 3 ]).cutAt(0, 1);
const frame = PD.Shape.frame(poly, 250, 150);
CAD.add(frame);

triangulate( [sides])

The triangulate operation divides specified faces into a triangular fan centered at the first vertex.

If the sides argument is less than 3, all faces in the shape will be divided. If 3 or more, only those faces with a matching number of sides will be divided.

To produce a useable result, this method requires that each face be convex in shape as dividing a concave face this way will result in overlapping triangular faces.

Parameters:
Name Type Argument Description
sides number <optional>

The number of sides as face must have to be affected, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

truncate( [sides])

The Conway truncate operation is a triakis operation performed of the dual of the original shape, then converted back to a dual.

If the sides argument is less than 3, all faces in the shape will be bevelled. If 3 or more, only those faces with a matching number of sides will be bevelled.

Parameters:
Name Type Argument Description
sides number <optional>

The number of sides as face must have to be affected, defaults to 0.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape

twistByAxis(axis, from, to, angle [, easing])

Rotates the shape in the other two axis by an angle that varies over a range within the given axis.

If the from and to values are both in the range 0 to 1, then they are considered to be fractions of the size of the shape in the given axis. If either value is outside the range 0 to 1, then they are both considered to be in absolute model units along the axis.

You can use the PD.Shape#extents method if you want to find out the size range of your specific shape in each axis.

If the angle is given as a single number, it represents the maximum twist angle at the to point on the axis, varying from 0 at the from point. If given as a [fromAngle, toAngle] array, you can specify the angles to use at both the from and to points. You can specify an easing function if you wish to make it a non-linear variation.

If you choose the Z axis, then the twist will be applied to the X and Y components of each vertex in the shape. If you choose the X axis the twist will be applied in Y and Z, and for the Y axis, it will be applied in X and Z.

If you wish to scale vertexes in a non-Cartesian axis or about a point other than the origin, use the PD.AxisArray#twistPointsInXY method instead.

Parameters:
Name Type Argument Description
axis number

The axis to twist in (0:X, 1:Y or 2:Z).

from number

A value on the given axis to start twisting from ,in model units.

to number

A value on the given axis to finish twisting at, in model units.

angle number | Array.<number>

The angle at or above the to value, or a [fromAngle,toAngle] array, defaults to 0 (no twist).

easing function <optional>

An easing function to use, defaults to PD.Easing.linear.

Inherited From:
Overrides:
Returns:

Returns this modified shape to support method chaining.

Type
PD.Shape
Examples
/// Twist cylinder with 12 sides and 20 segments.
const shape = PD.Shape.cylinder(12, 2000, 5000, 10);
shape.twistByAxis(2, 0.1, 0.95, Math.PI / 4, PD.Easing.inOutSine);
CAD.add(shape);

const frame = PD.Shape.frame(shape, 25, 50);
CAD.add(frame);
const shape = PD.Shape.dome(8, 6, 4000);
shape.extrudeBase(5000, 5).triakis(0, -100);
shape.twistByAxis(2, -5000, 4000, Math.PI / 3, PD.Easing.inOutSine);
CAD.add(shape);

const frame = PD.Shape.frame(shape).expand().join().join();
CAD.add(frame);

updateColors( [method] [, sensitivity])

Sets the color of each face of the polyhedra for display.

The available color methods are as follows:

  • 'none': No color(s) assigned.
  • 'edges': Group faces by their number of edges.
  • 'area': Group faces by similar surface areas.
  • 'signature': Group faces by the congruency of their normals.
  • 'smooth': Use smooth surface normals.
Parameters:
Name Type Argument Description
method string <optional>

The method to use to assign face colors, defaults to PD.Polyhedron.colorMethod.

sensitivity string <optional>

The color sensitivity to variation in congruence signature or planar area, defaults to PD.Polyhedron.colorSensitivity.

Returns:

Returns this polyhedron to support method chaining.

Type
PD.Polyhedron

vertexNormals()

Computes the averaged surface normal for each vertex.

The normal vector of each vertex in the shape is returned as an [x,y,z] vector array of unit length (normalized) defining its spatial direction in each major axis. Vertex normals are calculated as the average of all the face normals from faces that contain that vertex.

The order and index of vertex normals in the returned list match the order and index of corresponding vertices in the vertices list.

To allow further processing, additional information is appended to each normal array. Assuming the vertex is shared by N faces, each normal array has the following form:

[ normalX, normalY, normalZ, N, faceIndex1, faceIndex2, ..., faceIndexN ]

Inherited From:
Overrides:
Returns:

Returns an array of averages vertex normals.

Type
Array.<Array.<number>>
Example
const distance = 250;
const vertex_normals = shape.vertexNormals();
for (let ii = 0; ii < shape.vertices.length; ++ii) {
    hull_vertices.push(
        PD.VectorArray.translateInVectorDirection([], shape.vertices[ii], vertex_normals[ii], distance)
    );
}

weld( [decimals])

Iterates the shape to merge vertices that share the same positions and ensure that adjacent edges share the same vertices.

This also ensures that all faces are oriented outwards relative to the geometric centre of the shape.

Parameters:
Name Type Argument Description
decimals number <optional>

The number of decimal places when comparing millimeter coordinates, defaults to 1 (0.1mm).

Inherited From:
Overrides:
Returns:

Returns this shape to support method chaining.

Type
PD.Shape
Example
const config = {
    params: [ 1, 4, 0, 0, 0, 0, 2, -3 ],
    innerRadius: 0.5,
    unfoldZ: 0.75
};

const half_shape = PD.Shape.sphericalHarmonics(config).scale(400);
half_shape.cutAt(0, 1).cutAt(4500, -1).weld().join().expand();
CAD.add(half_shape);

adjustColorPalette(factor) <static>

Lighten or darken the color palette to suit the color scheme.

Parameters:
Name Type Description
factor number

The fraction to multiply the color pallette by.


archimedeanSolid(n) <static>

Generates one of the 13 Archimedean solid polyhedrons.

Parameters:
Name Type Description
n number

The numeric index of the Archimedean solid (1 to 13).

Returns:

Returns a new polyhedron.

Type
PD.Polyhedron

cancel() <static>

Requests the cancellation of any current modification or calculation process.


catalanSolid(n) <static>

Generates one of the 13 Catalan solid polyhedrons.

Parameters:
Name Type Description
n number

The numeric index of the Catalan solid (1 to 13).

Returns:

Returns a new polyhedron.

Type
PD.Polyhedron

cube() <static>

Generates a 6-sided cube.

Returns:

Returns a new Platonic solid.

Type
PD.Polyhedron

dodecahedron() <static>

Generates a 12-sided unit dodecahedron.

Returns:

Returns a new Platonic solid.

Type
PD.Polyhedron

formatModifier(modifier) <static>

Checks for a valid modifier and formats its arguments to become part of a Conway Polyhedron Notation string.

Parameters:
Name Type Description
modifier object

An {op,args} modifier object.

Returns:

Returns a formatted modifier string.

Type
string

fromData(vertices, faces, name) <static>

Generates a new polyhedron from the given faces and vertices.

Parameters:
Name Type Description
vertices Array.<Array.<number>>

A flat array of [x,y,z] vertex coordinates.

faces Array.<Array.<number>>

An array of face boundary arrays, each containing three or more vertex indices.

name string

A human-readable name for the shape.


fromModifiers(poly, modifiers) <static>

Generates polyhedron from an array of modifier operations.

The method performs all the required calculations synchronously, which can block the main thread of your application for several seconds for long modifier chains. To perform the calculations asynchronously with progress updates, use the PD.PolyhedronFactory.applyModifiers method instead.

Each modifier in the list is an object with an op property that is a string defining the operation to be performed and an args property which is an array of any arguments the operation requires.

See the PD.PolyhedronFactory.parseNotation method for details of the supported modifier operations and their arguments.

Parameters:
Name Type Description
poly PD.Polyhedron

The polyhedron to process.

modifiers Array.<object>

A list of modifier operations.

Returns:

Returns a modified polyhedra.

Type
PD.Polyhedron

fromNotation(poly, notation) <static>

Create polyhedron from a Conway notation string such as 'qoh(0.15,0.05)eeuz'.

See the PD.Polyhedron.parseNotation method for details of the supported modifier operations and their arguments.

Parameters:
Name Type Description
poly PD.Polyhedron

The polyhedron to process.

notation string

A string containing 'a(n,n)bcd9' modifier operations.

Returns:

Returns a modified polyhedra.

Type
PD.Polyhedron

fromType(type, sides) <static>

Generates a new polyhedron of a known type.

The supported types are as follows:

  • 'T'|'D4': Tetrahedron
  • 'C'|'D6': Cube
  • 'O'|'D8': Octahedron
  • 'D'|'D12': Dodecahedron
  • 'I'|'D20': Icosahedron
  • 'J': Johnson Solid (1 to 92)
  • 'L': Catalan Solid (1 to 13)
  • 'M': Archimedean Solid (1 to 13)
  • 'P': Prism (number_of_sides)
  • 'A': Antiprism (number_of_sides)
  • 'Y': Pyramid (number_of_sides)
  • 'B': Bipyramid (number_of_sides)
  • 'R': Pentagonal Rotunda
  • 'U': Cupola (number_of_sides)
  • 'V': Anticupola (number_of_sides)
  • 'G': Geodesic Dome (subdivisions)
  • 'F': Fibonacci Dome (density)
Parameters:
Name Type Description
type string

The type of polyhedron to create, defaults to 'T' for a Tetrahedron.

sides number

The number of sides, where appropriate, defaults to 4.


getModifierLog() <static>

Retrieves the modifier event log.

The event log is cleared each time a generator method that takes modifiers is called, so contains only events generated during the previous processing of modifiers.

Returns:

Returns the current event log as a multi-line string,

Type
string

getSupportedTypes( [category]) <static>

Retrieves a list of the names and type abbreviations for each supported type of polyhedra and Johnson solids.

These include the five Platonic solids (0 to 4), the twelve Archimedean solids (5 to 17), Prisms (18 to 25), Anti-prisms (26 to 33) and Johnson solids (34 to 126).

Each item in the list is a [name,type] array, where the name entry is a string containing the full name of the polyhedra and the type is a short string containing the code for that polyhedra that can be used with the PD.Polyhedron.fromType static method.

Parameters:
Name Type Argument Description
category string <optional>

An optional category to restrict the list to ('platonic', archimedean', 'prism', 'antiprism', 'johnson').

Returns:

Returns a list of [name,type] arrays.

Type
Array.<Array.<string>>

icosahedron() <static>

Generates a 20-sided unit icosahedron.

Returns:

Returns a new Platonic solid.

Type
PD.Polyhedron

johnsonSolid(n) <static>

Generates one of 92 different Johnson solid polyhedrons.

Parameters:
Name Type Description
n number

The numeric index of the Johnson Solid (1 to 92).

Returns:

Returns a new polyhedron.

Type
PD.Polyhedron

newInstance( [vertices] [, faces] [, name]) <static>

This is used to allow subclasses to create instance of their own class when using static generators.

Parameters:
Name Type Argument Description
vertices Array.<Array.<number>> <optional>

An array of [x,y,z] vertex coordinates.

faces Array.<Array.<number>> <optional>

An array of face boundary arrays, each containing three or more vertex indices.

name string <optional>

A human-readable name for the polyhedron.

Returns:

Returns a new polyhedron.

Type
PD.Shape

octahedron() <static>

Generates a 8-sided unit octahedron.

Returns:

Returns a new Platonic solid.

Type
PD.Polyhedron

parseNotation(poly, notation [, modifiers]) <static>

Generates a list of modifier operations and their arguments from a Conway polyhedron notation string such as 'qoh(0.15,0.05)eeuz'.

The supported modifier operations are as follows:

  • 'a': ambo()
  • 'b': bevel()
  • 'c': chamfer(detail, distance)
  • 'd': dual()
  • 'e': expand()
  • 'f': frame(inset, thickness)
  • 'g': gyro()
  • 'h': hollow(inset_dist, thickness)
  • 'i': inflate(degree)
  • 'j': join()
  • 'k': triakis(sides, offset)
  • 'l': loft(sides, inset)
  • 'm': meta(sides, offset)
  • 'n': insetN(sides, inset, offset)
  • 'o': ortho()
  • 'p': propellor()
  • 'q': quinto()
  • 'r': reflect(axis)
  • 's': snub()
  • 't': truncate(sides)
  • 'u': trisub(divisions)
  • 'w': whirl()
  • 'x': extrudeN(edge_count, pop_out_distance)
  • 'z': triangulate(sides, set_colors),

  • 'A': adjustXYZ(iterations),
  • 'C': canonicalize(iterations),
  • 'F': triangularFan(sides, offset)
  • 'J': jitter(seed, radial_fraction, spatial_fraction)
  • 'N': noise(amplitude, scale, offset)
  • 'P': stellation()
  • 'R': rotate(rx, ry, rz)
  • 'S': scale(sx, sy, sz)
  • 'T': translate(dx, dy, dz)
  • 'U': unitRadius(radius)
  • 'V': unitSize(size)
  • 'W': wrinkle(seed, radial_fraction, spatial_fraction)

As the PD.Polyhedron class supports almost any conceivable polyhedron type, the inclusion of specific polyhedron types within the notation string is not recommended as the seed polygon is almost always supplied to this method by the calling function.

It is still supported, but rather than simply appending it as a capital letter at the end of the notation string, you must include it at the start of the string and separate it from from main notation string with a full colon. For example, you can override the given polyhedron with the string C:kee for a cube or J32:ggd for a particular Johnson solid.

Parameters:
Name Type Argument Description
poly PD.Polyhedron

The polyhedron to process, which may be changed if a type modifier is included.

notation string

A string containing 'a(n,n)bcd' modifier operations.

modifiers Array.<object> <optional>

An optional list of modifiers to update and reuse.

Returns:

Returns a list of {op,args} modifiers.

Type
Array.<object>

tetrahedron() <static>

Generates a 4-sided unit tetrahedron.

Returns:

Returns a new Platonic solid.

Type
PD.Polyhedron