Skip to content

Instantly share code, notes, and snippets.

@gustavolsson
Last active March 17, 2021 18:45
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save gustavolsson/4393854 to your computer and use it in GitHub Desktop.
Save gustavolsson/4393854 to your computer and use it in GitHub Desktop.
This code generates an ISO metric screw thread given a set of parameters. The code is intended for Tinkercad Shape Scripts but it should be straightforward to port it to other platforms.
/*
Copyright (c) 2012 Gustav Olsson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This code generates an ISO metric screw thread given a set of parameters. The code is intended
for Tinkercad Shape Scripts but it should be straightforward to port it to other platforms.
I used the following wikipedia page as reference:
http://en.wikipedia.org/wiki/ISO_metric_screw_thread/
Tinkercard developer documentation is at:
https://tinkercad.com/developer/
Parameter explanations:
Diameter: The major diameter of the thread (ie. 12 for an M12 screw etc)
Pitch: The pitch of the thread (defined in millimeters)
Segments: The number of subdivisions to use for the cylinder and thread
Rotations: The number of rotations of the thread (This value determines the height of the thread using the pitch)
Tip Scale: The scale at the top/bottom-most segment of the thread
Tip Segments: The number of segments to use in the transition from a tip
Thread Scale: The width of the scale as seen from the plane of the thread axis (Can be used to achieve a better fit when 3d printing)
*/
var Debug = Core.Debug;
var Mesh3D = Core.Mesh3D;
var Path2D = Core.Path2D;
var Plugin = Core.Plugin;
var Tess = Core.Tess;
var Solid = Core.Solid;
params = [
{
"id": "diameter",
"displayName": "Diameter",
"type": "length",
"rangeMin": 1.0,
"rangeMax": 50.0,
"default": 12.0
},
{
"id": "pitch",
"displayName": "Pitch",
"type": "length",
"rangeMin": 0.1,
"rangeMax": 10.0,
"default": 1.5
},
{
"id": "segments",
"displayName": "Segments",
"type": "int",
"rangeMin": 3,
"rangeMax": 32,
"default": 16
},
{
"id": "rotations",
"displayName": "Rotations",
"type": "int",
"rangeMin": 1,
"rangeMax": 20,
"default": 5
},
{
"id": "tipScale",
"displayName": "Tip Scale",
"type": "float",
"rangeMin": 0.0,
"rangeMax": 1.0,
"default": 0.0
},
{
"id": "tipSegments",
"displayName": "Tip Segments",
"type": "int",
"rangeMin": 1,
"rangeMax": 16,
"default": 2
},
{
"id": "threadScale",
"displayName": "Thread Scale",
"type": "float",
"rangeMin": 0.0,
"rangeMax": 1.0,
"default": 1.0
}
];
// Vector operations
function add(a, b) {
return [a[0]+b[0], a[1]+b[1], a[2]+b[2]];
}
function sub(a, b) {
return [a[0]-b[0], a[1]-b[1], a[2]-b[2]];
}
function mul(v, s) {
return [v[0]*s, v[1]*s, v[2]*s];
}
function normalize(v) {
var lengthSq = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
if (lengthSq > 0.0) {
return mul(v, 1.0 / Math.sqrt(lengthSq));
}
return [0.0, 0.0, 0.0];
}
function cross(a, b) {
return [a[1]*b[2]-a[2]*b[1],
a[2]*b[0]-a[0]*b[2],
a[0]*b[1]-a[1]*b[0]];
}
// Returns the normal at the start of a given segment
function normalAt(c, segment) {
var angle = segment * c.anglePerSeg;
return [Math.cos(angle), Math.sin(angle), 0.0];
}
// Returns the thread position at the start of a given segment
function threadAt(c, segment) {
var xy = mul(normalAt(c, segment), c.radius);
var z = segment * c.risePerSeg;
return [xy[0], xy[1], z];
}
// Scales vertices given a starting segment and process direction (according to constants)
function scaleSegments(c, p, start, forward) {
for (var i = 0; i < c.tipSegments; i++) {
if (forward) {
var current = (start + i) * 4;
}
else {
var current = (start - i) * 4;
}
var scale = c.tipScale + c.tipScaleStep * i;
var pivot = mul(add(p[current + 0], p[current + 3]), 0.5);
for (var j = current; j < current + 4; j++) {
p[j] = add(pivot, mul(sub(p[j], pivot), scale));
}
}
}
function createThread(c, mesh) {
var segmentCount = c.segments * c.rotations;
// Create the vertices
var v = [];
for (var i = 0; i < segmentCount + 1; i++) {
var point = threadAt(c, i);
var nextPoint = threadAt(c, i + 1);
var normal = normalAt(c, i);
var tangent = sub(nextPoint, point);
var bitangent = normalize(cross(normal, tangent));
var lowPoint = sub(point, mul(normal, c.depth));
var v0 = add(lowPoint, mul(bitangent, c.slopeEnd));
var v1 = add(point, mul(bitangent, c.slopeStart));
var v2 = sub(point, mul(bitangent, c.slopeStart));
var v3 = sub(lowPoint, mul(bitangent, c.slopeEnd));
// Move v0 and v3 along the slope into the cylinder to account for precision errors
v0 = add(v0, mul(sub(v0, v1), 0.05));
v3 = add(v3, mul(sub(v3, v2), 0.05));
v.push(v0);
v.push(v1);
v.push(v2);
v.push(v3);
}
// Scale bottom end
scaleSegments(c, v, 0, true);
// Scale top end
scaleSegments(c, v, segmentCount, false);
// Fill thread faces
for (var i = 0; i < segmentCount; i++) {
var current = i * 4;
var next = (i + 1) * 4;
// Upper front
mesh.quad(v[current + 0], v[current + 1],
v[next + 1], v[next + 0]);
// Front
mesh.quad(v[current + 1], v[current + 2],
v[next + 2], v[next + 1]);
// Lower front
mesh.quad(v[current + 2], v[current + 3],
v[next + 3], v[next + 2]);
// Back
mesh.quad(v[next + 0], v[next + 3],
v[current + 3], v[current + 0]);
}
// Close bottom end
mesh.quad(v[0], v[3], v[2], v[1]);
// Close top end
var top = segmentCount * 4;
mesh.quad(v[top + 0], v[top + 1], v[top + 2], v[top + 3]);
}
function createCylinder(c, mesh) {
var radius = c.radius - c.depth;
var height = c.pitch * c.rotations;
// Create vertices
var bottom = [0.0, 0.0, -c.slopeEnd];
var top = [0.0, 0.0, height + c.slopeEnd];
var v = [];
for (var i = 0; i < c.segments + 1; i++) {
var xy = mul(normalAt(c, i), radius);
v.push([xy[0], xy[1], -c.slopeEnd]);
v.push([xy[0], xy[1], height + c.slopeEnd]);
}
// Fill faces
for (var i = 0; i < c.segments; i++) {
var current = i * 2;
var next = (i + 1) * 2;
mesh.quad(v[current + 1], v[current + 0], v[next + 0], v[next + 1]);
mesh.triangle(bottom, v[next + 0], v[current + 0]);
mesh.triangle(top, v[current + 1], v[next + 1]);
}
}
function process(params) {
// Validate input
params.diameter = Math.abs(params.diameter);
params.pitch = Math.abs(params.pitch);
params.segments = Math.abs(params.segments);
params.rotations = Math.abs(params.rotations);
params.tipScale = Math.abs(params.tipScale);
params.tipSegments = Math.abs(params.tipSegments);
params.threadScale = Math.abs(params.threadScale);
var threshold = 0.01;
if (params.diameter < threshold) {
Plugin.panic("Diameter is below threshold!");
}
if (params.pitch < threshold) {
Plugin.panic("Pitch is below threshold!");
}
if (params.segments < 3) {
Plugin.panic("Segments is below 3!");
}
if (params.rotations < 1) {
Plugin.panic("Rotations is below 1");
}
if (params.tipSegments * 2 > params.segments * params.rotations) {
Plugin.panic("There are more tip segments than the total of the thread!");
}
// Go!
var constants = {
diameter: params.diameter,
pitch: params.pitch,
segments: params.segments,
rotations: params.rotations,
radius: params.diameter * 0.5,
anglePerSeg: (2.0 * Math.PI) / params.segments,
risePerSeg: params.pitch / params.segments,
slopeStart: (params.pitch / 16.0) * params.threadScale,
slopeEnd: (params.pitch * (1.0/2.0 - 1.0/8.0)) * params.threadScale,
depth: params.pitch * (Math.sqrt(3.0)/2.0) * (5.0/8.0),
tipSegments: params.tipSegments,
tipScale: params.tipScale,
tipScaleStep: (1.0 - params.tipScale) / params.tipSegments
};
var mesh = new Mesh3D();
createThread(constants, mesh);
createCylinder(constants, mesh);
return Solid.make(mesh);
}
presets = [
{ 'color': [174, 190, 237] }
];
@funlw65
Copy link

funlw65 commented Mar 27, 2017

Thank you! I want to make a female m42x1 thread for an M42 lens, is enough to use a male screw of 42x1 (metric 42, pitch 1) as a boolean to make the required hole? I mean, to obtain a female real life workable thread for an M42x1 screw? Thank you again! 👍

@jusplainmike
Copy link

Why not set the range max on diameter to 64?

@tryblinking
Copy link

Hi. Great script.
Modelling a peg with a threaded section on one end, to be 3D printed (first project); you mentioned that the 'thread scale' parameter needs to be adjusted for best fit in practical use. What settings do you recommend here for the best chance of fitting into an existing ISO threaded hole?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment