OpenJSCAD.org ユーザー ガイド

出典: フリー教科書『ウィキブックス(Wikibooks)』

ようこそ、OpenJSCAD.org ユーザー ガイドへ。

Original Japanese Translation by Kariya

OpenJSCAD.org Overview
OpenJSCAD.org Overview

文脈を理解してもらうための説明ですが、 OpenJSCAD.orgOpenJsCad (Github)上に構築され、これ自身はOpenSCAD.orgに触発されたもので、本質的には3Dモデルを開発するJavaScriptを使ったプログラマー的取り組み方を提供し、特にこの強化は3D印刷のためのモデル作成用に調整されています。

OpenJSCADは非常にオブジェクト指向的で、 OpenSCADから来たプログラマーは以下のことに歓迎の意を表すかもしれません。

  • OpenJSCADへの移行を簡単にするいくつかのJavaScriptの関数
  • OpenSCAD のソースコードのサポート(約 95% の関数が利用可能)
  • additional functions to ease the transition to OpenJSCAD
  • ability to create and manipulate 3D shapes, as well as 2D shapes

この文章を続けて読んで下さい。

There is also a クイックリファレンス.

OpenJSCAD.org ユーザー ガイド[編集]

WEBブラウザとコマンドライン・インタフェース(「2つの特徴を持つ用法」)[編集]

WEBブラウザー (オンライン、ローカルとオフライン)[編集]

OpenJSCAD.orgには利用者のためのエディターが含まれます:

エディター内で

  • 組み込みのエディターを使ってオンラインで編集できます
  • 好みのエディターを使ってオフラインで編集できます

ファイルをブラウザーで示された領域にドラッグアンドドロップするだけです

好みのエディターを使って、Auto Reload [x] がチェックされていることを確認して下さい。

注:現段階ではブラウザーをサポートしています。Try another browser if your not satisfied with the performance of your current browser.

ローカルインストール (オフライン)[編集]

前提条件:

  • NodeJSをインストールして下さい(例 apt-get install nodejs)

注:NodeJS >= 0.8.1であることを確かめて下さい。(Ubuntu 12.04 installs NodeJS 0.6.1).

注:実際のNodeJS実行ファイル名が/usr/local/bin/node (デフォルト) か /usr/bin/nodejsであることと、openjscadの1行目がその名前であることをチェックして下さい。

以下では、次のようにレポジトリをクローンしたことを仮定します。

% git clone https://github.com/Spiritdude/OpenJSCAD.org.git
% cd OpenJSCAD.org
% make install

WEBブラウザ (オフライン)[編集]

index.htmlのローカルコピーに利用中のブラウザでアクセスして下さい。 The initial example should display. You can now open other OpenJSCAD files by dragging and dropping the file to the viewer. Other supported file formats can be converted and displayed as well.

コマンドラインインターフェース (オフライン)[編集]

以下のコマンドで logo.stl または test.stl が作成されます。

% cd examples
% openjscad logo.jscad
% openjscad logo.jscad -o test.stl
% openjscad logo.jscad -of stl

さらに OpenSCAD (.scad)、 STL ASCII または Binary (.stl)、そして AMF (.amf) ファイルが取込可能です。 .jscad、 .stl (ASCII または Binary)か .amfが作成可能です。

% openjscad example001.scad -o example001.jscad
% openjscad example001.scad -o example001.stl
% openjscad frog.stl -o frog.jscad
% openjscad frog.stl -o frog2.stl             # does actually stl -> jscad -> stl (ascii)
% openjscad example001.jscad -o example001.amf  
% openjscad example001.jscad -of amf          # creates example001.amf
% openjscad example001.jscad -of stlb         # creates example001.stl (binary)
% openjscad example001.jscad -of stlb -o test.stl
  • -o は出力を表します。
  • -of は出力形式を表します。(jscad, stl (default), stla, stlb, amf, dxf)

コマンドラインからmain()へ変数を渡す方法Command Line Interface Parametersも参照して下さい

言語 / ファイル形式のサポート[編集]

現在、次の言語とファイル形式をサポートしています。

Format Extension Website Notes
JSCAD .jscad OpenJSCAD.org OpenJSCAD is a software for creating solid 3D CAD objects using your browser.
SCAD .scad OpenSCAD.org OpenSCAD is a software for creating solid 3D CAD objects.
STL .stl Wikipedia: STL (file format) STL files describe only the surface geometry of three-dimensional objects
AMF .amf Wikipedia: AMF (file format) Additive Manufacturing File Format (very experimental)
SVG .svg W3C SVG Standard Scalable Vector Graphics Format

ファイルをドラッグアンドドロップすると、言語かファイルフォーマットがファイル拡張子(.jscad,...)に従って設定されます。ブラウザで直接編集を始める場合、デフォルトの言語はJSCADです。

ローカルかリモートのJSCADやSCAD、STL、AMFへの直接リンク[編集]

特定の例へのリンクを他の人に渡すことが出来ます。

ローカル

  1. http://openjscad.org/#examples/slices/tor.jscad
  2. http://localhost/OpenJSCAD.org/#examples/slices/tor.jscad

JSCADを参照する場合、include()がサポートされます。

リモート

  1. http://openjscad.org/#http://openjscad.org/examples/slices/tor.jscad
  2. http://openjscad.org/#http://www.thingiverse.com/download:164128 (STL)
  3. http://openjscad.org/#http://pastebin.com/raw.php?i=5RbzVguT (SCAD)
  4. http://openjscad.org/#http://amf.wikispaces.com/file/view/Rook.amf/268219202/Rook.amf (AMF)


JSCADを参照する場合、include()は サポートされません (おそらくサポートは後ほどになります)。

OpenJSCAD プログラミング ガイド[編集]

In general, designs are written using the JavaScript language. Training and help about JavaScript can be found online.

Creating a new design starts by writing simple scripts which call CSG functions, and other special functions, as provided by OpenJSCAD. OpenJSCAD executes the script, and renders the 3D design for viewing.

OpenJSCAD adheres to specific standards for passing parameters to functions. But most parameters are optional as default values are provided.

When 3D vectors are required, parameters can be passed as an array. If a scalar (single value) is passed for a parameter which expects a 3D vector, the scalar is used for the x, y and z values. In other words: radius: 1 will give radius: [1,1,1].

NEED EXAMPLE

JSCADファイルの解剖学[編集]

OpenJSCADの.jscadファイルは、ライブラリやヘルパー(複数ファイル)でない限り、少なくとも1つの関数main()を定義する必要があります。その関数はCSGオブジェクトか交わらないCSGオブジェクトの配列を返す必要があります。

function main() {
   return union(sphere(), ...);    // an union of objects or
   return [sphere(), ...];        // an array of non-intersecting objects
}

また次のようにします:

var w = new Array();
function a() {
   w.push( sphere() );
   w.push( cube().translate([2,0,0]) );
}
function main() {
   a();
   return w;
}

しかし以下の例は動作しません:

var w = new Array();
w.push( sphere() );                    // Note: it's not within a function (!!)
w.push( cube().translate([2,0,0]) );

function main() {
    return w;
}

なぜなら、3Dプリミティブのような全てのCSG作成物はmain()を結果的に通って呼ばれる関数内に現れなければならないからです。

3Dプリミティブ[編集]

All rounded solids have a resolution parameter which controls tesselation. If resolution is set to 8, then 8 polygons per 360 degree of revolution are used. Beware that rendering time will increase dramatically when increasing the resolution. For a sphere, the number of polygons increases quadratically with the resolution used. If the resolution parameter is omitted, the following two global defaults are used

  • CSG.defaultResolution2D
  • CSG.defaultResolution3D

The former is used for 2D curves (circle, cylinder), the latter for 3D curves (sphere, 3D expand).

OpenSCAD like functions support the fn parameter, which is the number of segments to approximate a sphere (default 32, total polygons per sphere fn*fn).

立方体[編集]

立方体やどちらかと言えば箱は以下の様に作成できます:

cube(); // openscad like
cube(1);
cube({size: 1});
cube({size: [1,2,3]});
cube({size: 1, center: true}); // default center:false
cube({size: 1, center: [true,true,false]}); // individual axis center true or false
cube({size: [1,2,3], round: true});
CSG.cube(); // object-oriented
CSG.cube({
    center: [0, 0, 0],
    radius: [1, 1, 1]
});
CSG.roundedCube({ // rounded cube
    center: [0, 0, 0],
    radius: 1,
    roundradius: 0.2,
    resolution: 8,
});

[編集]

球は次のようにして作成できます:

sphere();                          // openscad like
sphere(1);
sphere({r: 2});                    // Note: center:true is default (unlike other primitives, as OpenSCAD)
sphere({r: 2, center: false});     // Note: OpenSCAD doesn't support center for sphere but we do
sphere({r: 2, center: [true, true, false]}); // individual axis center 
sphere({r: 10, fn: 100 });
sphere({r: 10, fn: 100, type: 'geodesic'});  // geodesic approach (icosahedron further triangulated)

CSG.sphere();                      // object-oriented
CSG.sphere({
  center: [0, 0, 0],
  radius: 2,                      // must be scalar
  resolution: 32
});

type: 'geodesic'の場合、fnは非測地線のfnに適合させようとしますが、実際は6のステップ(例えば fn=6..11は同じ)で、fn = 1 ではベースとなる形の20面体が明らかになります。

注: 球を作成し(例えばunion()やintersection()で)操作すると、使われる大量のポリゴンのため、レンダリングや構築処理が遅くなります。

円柱[編集]

円柱と円錐は以下のようにして作成できます:

cylinder({r: 1, h: 10});                 // openscad like
cylinder({d: 1, h: 10});
cylinder({r: 1, h: 10, center: true});   // default: center:false
cylinder({r: 1, h: 10, center: [true, true, false]});  // individual x,y,z center flags
cylinder({r: 1, h: 10, round: true});
cylinder({r1: 3, r2: 0, h: 10});
cylinder({d1: 1, d2: 0.5, h: 10});
cylinder({start: [0,0,0], end: [0,0,10], r1: 1, r2: 2, fn: 50});

CSG.cylinder({                      // object-oriented
  start: [0, -1, 0],
  end: [0, 1, 0],
  radius: 1,                        // true cylinder
  resolution: 16
});
CSG.cylinder({
  start: [0, -1, 0],
  end: [0, 1, 0],
  radiusStart: 1,                   // start- and end radius defined, partial cones
  radiusEnd: 2,
  resolution: 16
});
CSG.roundedCylinder({               // and its rounded version
  start: [0, -1, 0],
  end: [0, 1, 0],
  radius: 1,
  resolution: 16
});

ここでfは円柱の丸い形を近似するための断片の量です(デフォルト32)。

トーラス[編集]

トーラスは以下の様に定義されます:

  • ri = 内径 (デフォルト: 1),
  • ro = 外径 (デフォルト: 4),
  • fni = 内側の分解度 (デフォルト: 16),
  • fno = 外側の分解度 (デフォルト: 32),
  • roti = 内側の回転 (デフォルト: 0)
torus();                    // ri = 1, ro = 4;  
torus({ ri: 1.5, ro: 3 });
torus{{ ri: 0.2 });

torus({ fni:4 });           // make inner circle fn = 4 => square
torus({ fni:4,roti:45 });   // rotate inner circle, so flat is top/bottom
torus({ fni:4,fno:4,roti:45 });
torus({ fni:4,fno:5,roti:45 });

多面体[編集]

多面体は点のリストと三角形やポリゴンのリストで作ります。点のリストは形の頂点全てで、三角形のリストは点が多面体の表面にどのように関連するかを定めます。

polyhedron({      // openscad-like (e.g. pyramid)
  points: [ [10,10,0],[10,-10,0],[-10,-10,0],[-10,10,0], // the four points at base
            [0,0,10] ],                                  // the apex point 
  triangles: [ [0,1,4],[1,2,4],[2,3,4],[3,0,4],          // each triangle side
               [1,0,3],[2,1,3] ]                         // two triangles for square base
});

さらにtriangles:だけではなくpolygons: [ [0,1,4,5], [..] ] とも定義できます。

多面体はより低水準でオブジェクト指向的に作成できます:

var polygons = [];
polygons.push(new CSG.Polygon([
      new CSG.Vertex(new CSG.Vector3D(x1,y1,z1)),
      new CSG.Vertex(new CSG.Vector3D(x2,y2,z2)),
      new CSG.Vertex(new CSG.Vector3D(x3,y3,z3))
   ])
);
// add more polygons and finally:
solid = CSG.fromPolygons(polygons);

テキスト[編集]

vector_text(x,y,string)vector_char(x,y,char) はベクトルでレンダリングされたテキストや文字の線分を与えます:

var l = vector_text(0,0,"Hello World!");   // l contains a list of polylines to be drawn
var o = [];
l.forEach(function(pl) {                   // pl = polyline (not closed)
   o.push(rectangular_extrude(pl, {w: 2, h: 2}));   // extrude it to 3D
});
return union(o);

また"\n"を使った複数行もサポートされます。今の所左詰めのみサポートされています。もっと詳細を知りたいなら、単一の文字を要求することもできます:

var c = vector_char(x,y,"A");
c.width;    // width of the vector font rendered character
c.segments; // array of segments / polylines

3D変換[編集]

スケール変換[編集]

scale(2,obj);          // openscad like
scale([1,2,3],obj);    //      '' 

obj.scale([1,2,3]);    // object-oriented

回転[編集]

rotate([90,15,30],obj);       // openscad like
rotate(90,[1,0.25,0.5],obj);  //    ''

obj.rotateX(90);              // object-oriented
obj.rotateY(45);
obj.rotateZ(30);

移動[編集]

translate([0,0,10],obj);  // openscad like

obj.translate([0,0,10]);  // object-oriented

センタリング[編集]

オブジェクトを全ての軸で、または軸単位でセンタリングするには:

center(true,cube());                // openscad-like all axis
center([true,true,false],cube());   // openscad-like axis-wise [x,y]

cube().center();                // object oriented center all axis
cube().center('x','y');         // object oriented center axis-wise [x,y]

false = 何もしない、 true = 軸にセンタリング

center() や .center() は左右対称で構築時には完全にはサイズがわからない物体を構成するのに役に立ちます。例えばパラメータ化されたデザインでのように。

行列操作[編集]

var m = new CSG.Matrix4x4();
m = m.multiply(CSG.Matrix4x4.rotationX(40));
m = m.multiply(CSG.Matrix4x4.rotationZ(40));
m = m.multiply(CSG.Matrix4x4.translation([-.5, 0, 0]));
m = m.multiply(CSG.Matrix4x4.scaling([1.1, 1.2, 1.3]));

// and apply the transform:
var cube3 = cube.transform(m);

ミラーリング[編集]

mirror([10,20,90], cube(1)); // openscad like

var cube = CSG.cube().translate([1,0,0]);   // object-oriented

var cube2 = cube.mirroredX(); // mirrored in the x=0 plane
var cube3 = cube.mirroredY(); // mirrored in the y=0 plane
var cube4 = cube.mirroredZ(); // mirrored in the z=0 plane

// create a plane by specifying 3 points:
var plane = CSG.Plane.fromPoints([5,0,0], [5, 1, 0], [3, 1, 7]);

// and mirror in that plane:
var cube5 = cube.mirrored(plane);

和集合[編集]

union(sphere({r: 1, center:true}),cube({size: 1.5, center:true}));  // openscad like

複数のオブジェクトの和を取ることができます。配列も可能です。

sphere({r: 1, center:true}).union(cube({size: 1.5, center:true}));  // object-oriented

積集合[編集]

intersection(sphere({r: 1, center:true}),cube({size: 1.5, center:true})); // openscad like

複数のオブジェクトの積を取ることができます。配列も可能です。

sphere({r: 1, center:true}).intersect(cube({size: 1.5, center:true}));   // object-oriented

注: intersection() (openscad と同様) と intersect() との対比(メソッド、オブジェクト指向)

差分 (減算)[編集]

difference(sphere({r: 1, center:true}),cube({size: 1.5, center:true}));    // openscad like

複数のオブジェクトの差分(減算)を取ることができます。配列も可能です。

sphere({r: 1, center:true}).subtract(cube({size: 1.5, center:true}));      // object-oriented

注: difference() (openscad と同様) と substract() との対比(メソッド、オブジェクト指向)

2Dプリミティブ[編集]

[編集]

circle();                        // openscad like
circle(1); 
circle({r: 2, fn:5});
circle({r: 3, center: true});    // center: false (default)

CAG.circle({center: [0,0], radius: 3, resolution: 32});   // object-oriented

正方形 / 長方形[編集]

square();                                   // openscad like
square(1);                                  // 1x1
square([2,3]);                              // 2x3
square({size: [2,4], center: true});        // 2x4, center: false (default)

CAG.rectangle({center: [0,0], radius: [w/2, h/2]});   // object-oriented, whereas w or h = side-length of square
CAG.roundedRectangle({center: [0,0], radius: [w/2, h/2], roundradius: 1, resolution: 4});

ポリゴン[編集]

polygon([ [0,0],[3,0],[3,3] ]);                // openscad like
polygon({ points: [ [0,0],[3,0],[3,3] ] });                    
polygon({ points: [ [0,0],[3,0],[3,3],[0,6] ], paths: [ [0,1,2],[1,2,3] ] }); // multiple paths not yet implemented

var shape1 = CAG.fromPoints([ [0,0],[5,0],[3,5],[0,5] ]);    // object-oriented

2D変換[編集]

translate([2,2], circle(1));      // openscad like
rotate([0,0,90], square());       //     ''
shape = center(true, shape());    // center both axis
shape = center([true,false], shape()); // center axis-wise [x] 

shape = shape.translate([-2, -2]);   // object-oriented
shape = shape.rotateZ(20);
shape = shape.scale([0.7, 0.9]);
shape = shape.center();          // center both axis
scape = shape.center('x');  // center axis-wise [x]

2Dパス[編集]

パスとは単なる点の列で、直線で結合されているものです。パスは開放することも、閉じる(追加の直線が最初と最後の点の間に描かれます)こともできます。2DパスはCSG.Path2Dクラスを通してサポートされます。2Dパスと2D CAGとの違いは、パスが「細い」直線なのに対し、CAGは囲まれた領域であることです。

パスは2D座標の列を与えたり、CSG.Path2D.arc()関数を通じたりして構築できます。後者は環状のカーブしたパスを構築します。パスは結合でき、結果は新しいパスになります。

パスをCAGに変換するには2つの方法があります:

  • expandToCAG(pathradius, resolution) は円でパスを追跡します。結果、パスの線分は太くなります。
  • innerToCAG() はパスで囲まれたCAGを作成します。パスは閉じたパスでなけばいけません。

3Dソリッドの作成は現状、rectangularExtrude()関数でサポートされます。この関数は2D長方形で(直立しパスの方向に垂直に)パスをなぞって3Dのシェイプを作成します。

var path = new CSG.Path2D([ [10,10], [-10,10] ], /* closed = */ false);
var anotherpath = new CSG.Path2D([ [-10,-10] ]);
path = path.concat(anotherpath);
path = path.appendPoint([10,-10]);
path = path.close(); // close the path

// of course we could simply have done:
// var path = new CSG.Path2D([ [10,10], [-10,10], [-10,-10], [10,-10] ], /* closed = */ true);

// We can make arcs and circles:
var curvedpath = CSG.Path2D.arc({
  center: [0,0,0],
  radius: 10,
  startangle: 0,
  endangle: 180,
  resolution: 16,
});

凸包[編集]

複数の2Dポリゴン(例えば circle()やsquare()、polygon())を合わせて凸包にすることができます。

var h = hull( square(10),circle(10).translate([10,10,0]) );

linear_extrude({ height: 10 }, h);

連鎖凸包[編集]

連鎖した凸包とは、複数の2Dの形の上の凸包の変種です。本質的に順次凸包にして、それらの和集合を取ります。Whosa whatsisのアイデアにもとづきます。

chain_hull( 
    circle(), circle().translate([2,0,0]), ... );   // list of CAG/2D forms

var a = [];
a.push(circle()); 
chain_hull( a );                       // array of CAG/2D forms

chain_hull({closed: true},             // default is false
   circle(),circle().translate([2,0,0]),circle().translate([2,2,0]));

押し出し(Extruding / Extrusion[編集]

線形押し出し[編集]

高さ、ねじり(twist)(角度)、スライス(ねじるなら)を与え、2Dの形状を3Dに押し出します:

// openscad like
linear_extrude({ height: 10 }, square());
linear_extrude({ height: 10, twist: 90 }, square([1,2]));
linear_extrude({ height: 10, twist: 360, slices: 50}, circle().translate([1,0,0]) );

linear_extrude({ height: 10, center: true, twist: 360, slices: 50}, translate([2,0,0], square([1,2])) );
linear_extrude({ height: 10, center: true, twist: 360, slices: 50}, square([1,2]).translate([2,0,0]) );

2D形状の線形押し出しにはオプションでねじりを指定できます。2D形状はz=0平面上に配置され、CSG.Vector3Dの<offset> 方向に押し出されます。最終の表面は<twistangle>度だけ回転します。回転は2D形状の原点(つまりx=0, y=0)周りになされ、twiststepはねじり(1以上でなければならない)の分解度を決定します。CSGオブジェクトを返します。

// object-oriented
var c = CAG.circle({radius: 3});
extruded = c.extrude({offset: [0,0,10], twistangle: 360, twiststeps: 100});

長方形押し出し[編集]

パスを(直立で、パスの方向に垂直に)長方形でたどり押し出し、CSGソリッドを返します。

rectangular_extrude()を使うと単純化されます(OpenSCADはこれを提供していないがopenscadと同様)。ここで Simplified (openscad like, even though OpenSCAD doesn't provide this) via rectangular_extrude(), where as

  • w: 幅 (デフォルト: 1)
  • h: 高さ (デフォルト: 1)
  • fn: 分解度 (デフォルト: 8)
  • closed: パスが閉じているか (デフォルト: false)
rectangular_extrude([ [10,10], [-10,10], [-20,0], [-10,-10], [10,-10] ],  // path is an array of 2d coords
    {w: 1, h: 3, closed: true});

あるいはより低水準でオブジェクト指向的なrectangularExtrude()も使えます。次の無名の変数を与えます。

  1. z=0平面での押し出しの幅
  2. z方向に押し出す高さ
  3. resolution: 分解度、つまり隅のカーブに対しての360度あたりの断片の数
  4. roundEnds: 真ならポリゴンの末端は丸められます。そうでなければ真っ直ぐなままで
// first creating a 2D path, and then extrude it
var path = new CSG.Path2D([ [10,10], [-10,10], [-20,0], [-10,-10], [10,-10] ], /*closed=*/true);
var csg = path.rectangularExtrude(3, 4, 16, true);   // w, h, resolution, roundEnds
return csg;

回転押し出し[編集]

さらに rotate_extrude() も利用可能です:

// openscad-like
rotate_extrude( translate([4,0,0], circle({r: 1, fn: 30, center: true}) ) );

// more object-oriented
rotate_extrude({fn:4}, square({size: [1,1], center: true}).translate([4,0,0]) );

rotate_extrude( polygon({points:[ [0,0],[2,1],[1,2],[1,3],[3,4],[0,5] ]}) );
rotate_extrude({fn:4}, polygon({points:[ [0,0],[2,1],[1,2],[1,3],[3,4],[0,5] ]}) );

本質的に2Dポリゴン(円、正方形、ポリゴン)を押し出します。

プロパティー[編集]

ソリッドの'property'プロパティーはそのオブジェクトのメタ情報を格納するのに使うことができます。例えばソリッドの特定の興味のある点の座標などです。オブジェクトが変換(回転、スケール変換、移動など)された場合必ずプロパティーも変換されます。 そのためソリッドを何度変換してもプロパティーは興味のある同じ点を指し続けます。

プロパティーは任意の型を持つことができますが、'transform'メソッドをサポートするクラスのプロパティーしか実際に変換されません。これにはCSG.Vector3DやCSG.Plane、CSG.Connectorが含まれます。特にCSG.Connectorのプロパティー(下記参照)は非常に有用です:これはソリッドを別のソリッドに事前に決められた位置で現在の向きに関係なく取り付けるのに使用可能です。

他のソリッドのプロパティーとしてCSGソリッドを含ませることも可能です。これは例えばあるオブジェクトに適合するネジ穴を作成するために切り抜き円柱を定義するのに使えるでしょう。これらの'solid properties'はソリッドのオーナーと同じ変換を受けますが、union()のようなCSG操作の結果としては目に見えません。

他の種類のプロパティー(例えば文字列)は変換されたソリッドのプロパティーに含まれはしますが、オーナーソリッドが変換されてもその値はなんら変換されません。

全てのプリミティブソリッドはいくつかの事前定義されたプロパティーを持ちます。例えば球の中心点などです。(TODO: 文書化)

union()やsubtract()、intersect()といったCSG操作の結果作られるソリッドは元となるソリッド両者の併合されたプロパティーを持ちます。同名のプロパティーがあればそのうち1つのみしか保持されません。

var cube = CSG.cube({radius: 1.0});
cube.properties.aCorner = new CSG.Vector3D([1, 1, 1]);
cube = cube.translate([5, 0, 0]);
cube = cube.scale(2);
// cube.properties.aCorner will now point to [12, 2, 2],
// which is still the same corner point 

// Properties can be stored in arrays; all properties in the array
// will be transformed if the solid is transformed:
cube.properties.otherCorners = [
  new CSG.Vector3D([-1, 1, 1]),
  new CSG.Vector3D([-1, -1, 1])
];

// and we can create sub-property objects; these must be of the 
// CSG.Properties class. All sub properties will be transformed with
// the solid:
cube.properties.myProperties = new CSG.Properties();
cube.properties.myProperties.someProperty = new CSG.Vector3D([-1, -1, -1]);

コネクター[編集]

CSG.Connectorクラスの目的は、2つのソリッドと互いに前もって決められた位置と方向で結合するのを容易にすることです。例えばサーボモーターを描いたCSGソリッドとサーボアームのソリッドがあるとしましょう:それぞれのコネクタープロパティーを定義することで、容易にサーボアームをサーボモーターに正しい位置(つまりモーター軸)と向き(つまり軸に垂直)で取り付けることができます。たとえ3D空間上の現在の位置と向きを知らなくても。

言い換えればコネクターは自在にオブジェクトを回転・移動することを、その位置と境界を追跡することなしに可能にします。そしてサードパーティーのライブラリーがそのソリッドにコネクターを公開すれば、ライブラリーの利用者は実際の寸法や形状を知る必要がなく、ただコネクターのプロパティーの名前さえ知っていればいいのです。

CSG.Connector には3つのプロパティーがあります:

  • point: 3D空間上の結合点を定義するCSG.Vector3D
  • axis: 結合の方向ベクトルを定義するCSG.Vector3D (サーボモーターの例では軸の方向を指す)
  • normal: いずれかの軸に垂直なCSG.Vector3D 方向ベクトル; これは結合の「12時」方向を定義する

2つのコネクターを結合するとき、pointプロパティーが同じになり、axisプロパティーが同じ向き(または mirrot == true なら反対向き)になり、normalができるだけ適合するように、ソリッドは変換されます。

コネクターを結合するには2つの方法があります: CSGソリッドのconnectTo()関数が、2つのコネクターが結合された状態になるようにソリッドを変換します。 別の方法として、コネクターのgetTransformationTo()メソッドを使って、コネクターを結合する変換行列を取得します。この方法は、同じ変換を複数のソリッドに適用する必要がある場合に使うことができます。

var cube1 = CSG.cube({radius: 10});
var cube2 = CSG.cube({radius: 4});

// define a connector on the center of one face of cube1
// The connector's axis points outwards and its normal points
// towards the positive z axis:
cube1.properties.myConnector = new CSG.Connector([10, 0, 0], [1, 0, 0], [0, 0, 1]);

// define a similar connector for cube 2:
cube2.properties.myConnector = new CSG.Connector([0, -4, 0], [0, -1, 0], [0, 0, 1]);

// do some random transformations on cube 1:
cube1 = cube1.rotateX(30);
cube1 = cube1.translate([3.1, 2, 0]);

// Now attach cube2 to cube 1:
cube2 = cube2.connectTo(
  cube2.properties.myConnector, 
  cube1.properties.myConnector, 
  true,   // mirror 
  0       // normalrotation
);

// Or alternatively:
var matrix = cube2.properties.myConnector.getTransformationTo(
  cube1.properties.myConnector, 
  true,   // mirror 
  0       // normalrotation
);
cube2 = cube2.transform(matrix);

var result = cube2.union(cube1);

境界と平面配置[編集]

getBound()関数を使ってオブジェクトのバウンディングボックスを取得できます。getBounds()は2つのCSG.Vector3Dからなる配列を返します。それぞれが最小のx,y,z座標と最大のx,y,z座標を示します。

lieFlat()はオブジェクトをz=0平面上に配置します。その際、z-高さが最小になり、z軸周りにセンタリングされるように処理されます。これはCNCミルで有用です:オブジェクトの一部を切削中の原材料の空間に変換するからです。または3Dプリンタでも同様です:最小の層数で印刷できるからです。lieFLat()の代わりにgetTransformationToFlatLying()関数も使えます。これは変換としてCSG.Matrix4x4を返します。

var cube1 = CSG.cube({radius: 10});
var cube2 = CSG.cube({radius: 5});

// get the right bound of cube1 and the left bound of cube2:
var deltax = cube1.getBounds()[1].x - cube2.getBounds()[0].x;

// align cube2 so it touches cube1:
cube2  = cube2.translate([deltax, 0, 0]);

var cube3 = CSG.cube({radius: [100,120,10]});
// do some random transformations:
cube3 = cube3.rotateZ(31).rotateX(50).translate([30,50,20]);
// now place onto the z=0 plane:
cube3  = cube3.lieFlat();

// or instead we could have used:
var transformation = cube3.getTransformationToFlatLying();
cube3 = cube3.transform(transformation);

return cube3;

[編集]

OpenSCADと同様に:

color([r,g,b], object, object2 ...); // for example, color([1,1,0],sphere());
color([r,g,b], array);
color([r,g,b,a], object, object2 ...);
color([r,g,b,a], array);
color(name, object, object2 ...); // for example, color('red',sphere());
color(name, a, object, object2 ...); // for example, color('red',0.5, sphere());
color(name, array);
color(name, a, array);

ここで名前付きの色は大文字小文字を区別しません。 ('RED'=='red')

オブジェクト指向的には:

object.setColor([r,g,b]);
object.setColor([r,g,b,a]);
object.setColor(r,g,b);
object.setColor(r,g,b,a);

例:

color([1,0.5,0.3],sphere(1));                      // openscad like
color([1,0.5,0.3],sphere(1),cube(2));
color("Red",sphere(),cube().translate([2,0,0]));   // named color (case-insensitive)

sphere().setColor(1,0.5,0.3);                      // object-oriented
sphere().setColor([1,0.5,0.3]);

色調で並べられた全ての利用可能な色名についてはWeb_colorsを参照して下さい。

コード抜粋:

o.push( color([1,0,0],sphere()) );
o.push( color([0,1,0],cube()) );
o.push( color([0,0,1],cylinder()) );

o.push( color("red",sphere()) );
o.push( color("green", cube()) );
o.push( color("blue", cylinder()) );

for(var i=0; i&lt;1; i+=1/12) {
   o.push( cube().setColor(hsl2rgb(i,1,0.5)) );
}

コード:

function main() {
   var o = [];
   for(var i=0; i&lt;8; i++) {
      o.push(cylinder({r:3,h:20}).
         setColor(
            hsl2rgb(i/8,1,0.5).  // hsl to rgb, creating rainbow [r,g,b]
            concat(1/8+i/8)      // and add to alpha to make it [r,g,b,a]
         ).translate([(i-3)*7.5,0,0])
      );
   }
   o.push(color("red",cube(5)).translate([-4,-10,0]));
   o.push(color("red",0.5,cube(5)).translate([4,-10,0]));
   return o;
}

注意: OpenGLの透過色の制限があります。例えば順番次第で、部分的に透明なオブジェクトが透過して見えないかもしれません。

色空間の変換[編集]

次の関数で色空間を変換できます:

var hsl = rgb2hsl(r,g,b); // or rgb2hsl([r,g,b]);
var rgb = hsl2rgb(h,s,l); // or hsl2rgb([h,s,l]);
var hsv = rgb2hsv(r,g,b); // or rgb2hsv([r,g,b]);
var rgb = hsv2rgb(h,s,v); // or hsv2rgb([h,s,v]);

ここで

  • r,g,b (赤, 緑, 青)
  • h,s,l (色調, 彩度, 明度)
  • h,s,v (色調, 彩度, 値)

例えば、虹を作成するには、t=0..1で.setColor(hsl2rgb(t,1,0.5)) とします。

Tor (multi-color)の例を直接参照して下さい。.

Echo[編集]

a = 1, b = 2;
echo("a="+a,"b="+b);

prints out on the JavaScript console: a=1, b=2

Mathematical Functions[編集]

Javascript provides several functions through the Math library. In addition, the following OpenSCAD compatible functions are available:

sin(a);                   // a = 0..360
cos(a);                   //     ''
asin(a);                  // a = 0..1, returns 0..360
acos(a);                  //       ''
tan(a);                   // a = 0..360
atan(a);                  // a = 0..1, returns 0..360
atan2(a,b);               // returns 0..360
ceil(a);
floor(a);
abs(a);
min(a,b);
max(a,b);
rands(min,max,vn,seed);   // returns random vectors of vn dimension, seed not yet implemented
log(a);
lookup(ix,v);             // ix = index, e.g. v = [ [0,100], [10,10], [20,200] ] whereas v[x][0] = index, v[x][1] = value
                          //    return will be linear interpolated (e.g. lookup(5,[ [0,100], [10,10], [20,200] ]) == 45

pow(a,b);
sign(a);                  // -1, 0 or 1
sqrt(a);
round(a);

Direct OpenSCAD Source Import[編集]

An OpenSCAD to OpenJSCAD translator is included, however the following features aren't working yet:

  • DXF import and manipulation (e.g. import_dxf, dxf-cross, dxf_dim functions).
  • rotate_extrude() (Note: OpenJSCAD supports rotate_extrude() )
  • minkowski() and hull() transformations (Note: OpenJSCAD supports hull() )
  • global variable such as $fa, $fs
  • Modifier characters: #, !, %
  • List Comprehension such as: list = [ for (i = [2, 3, 5, 7, 11]) i * i ];

You can edit OpenSCAD source in the built-in editor, just make sure the first line says:

//!OpenSCAD

then the source-code is shown with OpenSCAD syntax.

Further CAD languages support might arrive at a later time.

Converting OpenSCAD to OpenJSCAD[編集]

In order to translate your OpenSCAD into native OpenJSCAD code, consider this comparison.

OpenSCAD

union() {
      //cube(size=[30,30,0.1],center=true);
      translate([3,0,0]) cube();
      difference() {
         rotate([0,-45,0]) cube(size=[8,7,3],center=true);
         sphere(r=3,$fn=20,center=true);
      }
      translate([10,5,5]) scale([0.5,1,2]) sphere(r=5,$fn=50);
      translate([-15,0,0]) cylinder(r1=2,r2=0,h=10,$fn=20);
     
   for(i=[0:19]) {
      rotate([0,i/20*360,0]) 
      translate([i,0,0]) 
      rotate([0,i/20*90,i/20*90,0]) 
      cube(size=[1,1.2,.5],center=true);
   }
}

OpenJSCAD

function main() {  
   var cubes = new Array();
   for(i=0; i&lt;20; i++) {
      cubes[i] = rotate([0,i/20*360,0], 
         translate([i,0,0], 
         rotate([0,i/20*90,i/20*90,0], 
         cube({size:[1,1.2,.5],center:true}))));
   }
   return union(
      //cube({size:[30,30,0.1],center:true}),
      translate([3,0,0],cube()),
      difference(
         rotate([0,-45,0], cube({size:[8,7,3],center:true})),
         sphere({r:3,fn:20,center:true})
      ),
      translate([10,5,5], scale([0.5,1,2], sphere({r:5,fn:50}))),
      translate([-15,0,0], cylinder({r1:2,r2:0,h:10,fn:20})),
      cubes
   );
}

Essentially whenever named arguments in OpenSCAD appear func(a=1), translate it into func({a:1}), for example:

// OpenSCAD
translate([0,0,2]) sphere(size=2,$fn=50)
// becomes OpenJSCAD
translate([0,0,2], sphere({size:2,fn:50}));
// or
sphere({size:2,fn:50}).translate([0,0,2]);

Interactive Parametric Models[編集]

Models can have interactive parameters, allowing users to change values via familiar forms, i.e. typing in numbers, sliding bars, pulling down menus, etc. This allows the user to change values and create any number of possible combinations, allowing the model to become dynamic in nature. Any number of custom designs can be created, which can then be down loaded in any supported format.

Interactive parameters are possible by adding a specific function called getParameterDefinitions(). This function can be added anywhere in to your JSCAD script, but must return an array of parameter definitions.

function getParameterDefinitions() {
  return [{ name: 'width', type: 'float', initial: 10, caption: "Width of the cube:" }];
}

The parameter definitions are used to create a set of fields which the user can change, i.e. options. The values of the fields are supplied to the main() function of your JSCAD script. For example, the value of the 'width' parameter is supplied as the 'params.width' attribute, and so on.

function main(params) {
  // custom error checking:
  if(params.width &lt;= 0) throw new Error("Width should be positive!");
  var mycube = CSG.cube({radius: params.width});
  return mycube();
}

All the common HTML5 field types are available as interactive parameters. This includes checkbox, color, date, email, float, int, number, password, slider, text and url. As well as two special parameter types for pull down choices, and grouping parameters.

A minimum parameter specification contains only 'name' and 'type'. However, a complete parameter specification should have a 'caption' and 'initial' value. In addition, there are 'min', 'max', 'step', 'checked', 'size, 'maxlength', and 'placeholder' which are relevant to specific parameter types. Just keep try different combinations to get a nice parameter specification. Here's an good example.

{
  name: 'width',
  type: 'float',
  initial: 1.20,
  caption: 'Width of the thingy:',
  min: 1.0,
  max: 5.0,
  step: 0.5
}

In addition, there is the 'choice' type which creates a drop down list of choices for the user. The choices are provided by specifying the 'values' and 'captions'. The chosen value is passed into the main() function of the model.

{
  name: 'shape',
  type: 'choice',
  values: ["TRI", "SQU", "CIR"],               // these are the values that will be supplied to your script
  captions: ["Triangle", "Square", "Circle"],  // optional, these values are shown in the listbox
                                               // if omitted, the items in the 'values' array are used
  caption: 'Shape:',                           // optional, displayed left of the input field
  initial: "SQU",                              // optional, default selected value
                                               // if omitted, the first item is selected by default
                                               // NOTE: parameter "default" is deprecated
}

A complete example:

function getParameterDefinitions() {
  return [
    { name: 'width', type: 'float', initial: 10, caption: "Width of the cube:" },
    { name: 'height', type: 'float', initial: 14, caption: "Height of the cube:" },
    { name: 'depth', type: 'float', initial: 7, caption: "Depth of the cube:" },
    { name: 'rounded', type: 'choice', caption: 'Round the corners?', values: [0, 1], captions: ["No thanks", "Yes please"], initial: 1 }
  ];
}

function main(params) {
  var result;
  if(params.rounded == 1) {
    result = CSG.roundedCube({radius: [params.width, params.height, params.depth], roundradius: 2, resolution: 32});
  } else {
    result = CSG.cube({radius: [params.width, params.height, params.depth]});
  }
  return result;
}

There are plenty of examples of "Interactive" parameters available at OpenJSCAD.org.

Parameters via the Command Line Interface[編集]

The command line interface, ``openjscad``, can pass parameters for the interactive designs. Either by

 key value

or

 key=value

For example:

% openjscad name_plate.jscad --name "Just Me" --title "Geek" -o JustMe.amf
% openjscad name_plate.jscad "--name=Just Me" "--title=Geek" -o JustMe.amf

Maintaining Larger Projects[編集]

Including Files[編集]

After creating a few designs using OpenJSCAD, common functions and parts will become useful. The include() function allows one OpenJSCAD script to include another OpenJSCAD script.

// main.jscad
include("lib.jscad");

function main() {
   return myLib.b(2);
}

and

// lib.jscad
myLib = function() {
   var a = function(n) {  // internal 
      return n*2;  
   }
   myLib.b = function(n) {      // public 
      return sphere(a(n));  
   }
}

See Example 50: Platonics with a recursive use of include(). Yet, it's a rather bad example of not localize the function names. A clear writing style-guide will follow how an OpenJSCAD library should look like.

Support of include()[編集]

The include() function is supported

  • web-online remote (e.g. http://openjscad.org/): given you drag & dropped the files, or they are available on the web-server (e.g. the examples)
  • web-online local (e.g. http://localhost/OpenJSCAD/): given you drag & dropped the files, or they are available on the local web-server
  • web-offline local (e.g. file://..../OpenJSCAD/index.html): given you drag & dropped the files
  • command-line interface (CLI): given they are locally available in the filesystem

Example of a setup with drag & dropped files:

File Layout of JSCAD Projects[編集]

Assuming you want to create a larger OpenJSCAD project, you might use include() to split up the functionality:

ProjectName/
   main.jscad          # this one contains the "function main()", this file will be <b>executed</b>
   addon.jscad         # this file could be include("addon.jscad") in main.jscad
   optimizer.jscad     #             ''     include("optimizer.jscad") in main.jscad or also in addon.jscad 
   Makefile            # possible Makefile to do the same on CLI

Note: The file named main.jscad must be present, and must contain the "function main()" declaration.

Developing with Multiple JSCAD Files[編集]

Depending on your browser and your local setup, following applies:

  • Chrome (Version 26):
* Online (http://...): drag & drop entire folder, e.g. ProjectName/ to the drag & drop zone
* Offline (file://...): drag & drop all jscad files (but not folder) to the drag & drop zone
  • Firefox (Version 19+): drag & drop all jscad files of the project to the drag & drop zone
  • Opera: not yet working (WebGL support not yet available)
  • IE10: not yet working (WebGL support not yet available)

Addendum[編集]