Merge pull request #1 from xibyte/webpackify

webpackify
This commit is contained in:
xibyte 2016-09-08 22:17:24 -07:00 committed by GitHub
commit 80eb0da7fa
53 changed files with 2397 additions and 2668 deletions

3
.babelrc Normal file
View file

@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}

5
.gitignore vendored
View file

@ -6,4 +6,7 @@
*.iml
*.ipr
*.iws
/web/app/test/viz/**
/web/app/test/viz/**
/npm-debug.log
/node_modules
/dist

3
build/.eslintignore Normal file
View file

@ -0,0 +1,3 @@
/web/app/math/lm.js
/web/app/math/qr.js

24
build/.eslintrc.json Normal file
View file

@ -0,0 +1,24 @@
{
"extends": "eslint:recommended",
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"parser": "babel-eslint",
"plugins": [
"babel"
],
"globals" : {
"THREE" : true,
"CSG" : true,
"PNLTRI" : true
},
"rules": {
"comma-dangle": "off",
"no-unused-vars": "off",
"max-len": "off",
"no-console": "off",
"no-extra-boolean-cast": "off"
}
}

View file

@ -1,51 +0,0 @@
#!/usr/bin/env bash
cd `dirname "$0"`
git rev-parse --short HEAD #make sure git in place
mkdir -p out
rm -rf out/*
> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/canvas.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/io.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/history.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/shapes/arc.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/shapes/circle.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/shapes/segment.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/shapes/dim.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/helpers.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/vector.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/math.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/qr.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/matrix.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/optim.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/lm.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/constr/constraints.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/constr/solver.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/parametric.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/fetchers.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/engine.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/sketcher/main2d.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/ui.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/ui/toolkit.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/math/graph.js >> out/app.js
java -jar yuic.jar --disable-optimizations ../web/app/app-init.js >> out/app.js
sed -n \
'/<\!--\$\$\$javascript_start\$\$\$-->/{:a;N;/<\!--\$\$\$javascript_end\$\$\$-->/!ba;N;s|.*\n| <script src="app.js"></script>|};p' \
../web/sketcher.html > out/sketcher.html
echo >> out/sketcher.html
echo '<!-- R:' "`git rev-parse --short HEAD` -->" >> out/sketcher.html
#now make it work inside out dir
ln -sf ../../web/img/ out/img
ln -sf ../../web/css/ out/css
mkdir -p out/lib
ln -sf ../../../web/lib/jquery-2.1.0.min.js out/lib/jquery-2.1.0.min.js
ln -sf ../../../web/lib/numeric-1.2.6.js out/lib/numeric-1.2.6.js
ln -sf ../../../web/lib/diff_match_patch.js out/lib/diff_match_patch.js
ln -sf ../../../web/lib/font-awesome out/lib/font-awesome

2
build/publish.sh Executable file → Normal file
View file

@ -2,4 +2,4 @@
cd `dirname "$0"`
aws s3 sync ../web/ s3://sketcher/
aws s3 sync ./web/ s3://sketcher/

Binary file not shown.

43
package.json Normal file
View file

@ -0,0 +1,43 @@
{
"name": "jsketcher",
"version": "0.1.0",
"description": "JS.Sketcher is a parametric 2D and 3D CAD modeler written in pure javascript",
"scripts": {
"start": "webpack-dev-server --content-base web/ --port 3000",
"build": "webpack --config webpack.config.js --progress --profile --colors",
"lint": "eslint web/app -c ./build/.eslintrc.json --ignore-path ./build/.eslintignore"
},
"repository": {
"type": "git",
"url": "https://github.com/xibyte/jsketcher.git"
},
"keywords": [
"parametric",
"cad"
],
"author": "Val Erastov <xibyte@gmail.com> (http://github.com/xibyte)",
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/xibyte/jsketcher/issues"
},
"homepage": "https://github.com/xibyte/jsketcher",
"devDependencies": {
"babel-cli": "6.14.0",
"babel-core": "6.14.0",
"babel-eslint": "6.1.2",
"babel-loader": "6.2.5",
"babel-preset-es2015": "6.14.0",
"css-loader": "0.24.0",
"eslint": "3.2.0",
"eslint-config-airbnb-base": "5.0.1",
"eslint-plugin-babel": "3.2.0",
"eslint-plugin-import": "1.12.0",
"style-loader": "0.13.1",
"webpack": "1.13.2",
"webpack-dev-server": "1.15.0"
},
"dependencies": {
"diff-match-patch": "1.0.0",
"numeric": "1.2.6"
}
}

View file

@ -1,9 +1,14 @@
import * as tk from '../ui/toolkit'
import * as cad_utils from '../utils/cad-utils'
import * as math from '../math/math'
import * as workbench from './workbench'
import {ExtrudeWizard, PlaneWizard} from './wizards/wizards'
import {IO} from '../sketcher/io'
TCAD.UI = function(app) {
function UI(app) {
this.app = app;
this.viewer = app.viewer;
var tk = TCAD.toolkit;
var mainBox = new tk.Box();
mainBox.root.css({height : '100%'});
var propFolder = new tk.Folder("Solid's Properties");
@ -53,7 +58,7 @@ TCAD.UI = function(app) {
rows.removeClass('history-selected');
rows.eq(craft.historyPointer).addClass('history-selected');
var op = craft.history[craft.historyPointer];
historyWizard = TCAD.UI.createWizard(op, app, mainBox);
historyWizard = UI.createWizard(op, app, mainBox);
finishHistory.root.show();
} else {
finishHistory.root.hide();
@ -80,7 +85,7 @@ TCAD.UI = function(app) {
var op = JSON.parse(JSON.stringify(craft.history[craft.historyPointer]));
op.protoParams = historyWizard.currentParams();
historyWizard.close();
historyWizard = TCAD.UI.createWizard(op, app, mainBox);
historyWizard = UI.createWizard(op, app, mainBox);
}
});
@ -94,7 +99,7 @@ TCAD.UI = function(app) {
if (app.viewer.selectionMgr.selection.length == 0) {
return;
}
TCAD.UI.createCutExtrudeWizard(isCut, ui.app, app.viewer.selectionMgr.selection[0], mainBox);
UI.createCutExtrudeWizard(isCut, ui.app, app.viewer.selectionMgr.selection[0], mainBox);
}
}
@ -103,7 +108,7 @@ TCAD.UI = function(app) {
edit.root.click(tk.methodRef(app, "sketchFace"));
refreshSketches.root.click(tk.methodRef(app, "refreshSketches"));
addPlane.root.click(function() {
TCAD.UI.createPlaneWizard(app, mainBox);
UI.createPlaneWizard(app, mainBox);
});
printSolids.root.click(function () {
app.findAllSolids().map(function(o) {
@ -139,17 +144,17 @@ TCAD.UI = function(app) {
app.viewer.selectionMgr.deselectAll();
});
stlExport.root.click(function() {
var allPolygons = TCAD.utils.arrFlatten1L(app.findAllSolids().map(function (s) {
var allPolygons = cad_utils.arrFlatten1L(app.findAllSolids().map(function (s) {
return s.csg.toPolygons()
}));
var stl = CSG.fromPolygons(allPolygons).toStlString();
TCAD.io.exportTextData(stl.data[0], app.id + ".stl");
IO.exportTextData(stl.data[0], app.id + ".stl");
})
};
}
TCAD.UI.prototype.getInfoForOp = function(op) {
UI.prototype.getInfoForOp = function(op) {
var p = op.params;
var norm2 = TCAD.math.norm2;
var norm2 = math.norm2;
if ('CUT' === op.type) {
return op.type + " (" + norm2(p.target) + ")";
} else if ('PAD' === op.type) {
@ -162,31 +167,30 @@ TCAD.UI.prototype.getInfoForOp = function(op) {
return op.type;
};
TCAD.UI.createWizard = function(op, app, alignComponent) {
UI.createWizard = function(op, app, alignComponent) {
var initParams = op.protoParams;
var face = op.face !== undefined ? app.findFace(op.face) : null;
if (face != null) {
app.viewer.selectionMgr.select(face);
}
if ('CUT' === op.type) {
return TCAD.UI.createCutExtrudeWizard(true, app, face, alignComponent, initParams, true);
return UI.createCutExtrudeWizard(true, app, face, alignComponent, initParams, true);
} else if ('PAD' === op.type) {
return TCAD.UI.createCutExtrudeWizard(false, app, face, alignComponent, initParams, true);
return UI.createCutExtrudeWizard(false, app, face, alignComponent, initParams, true);
} else if ('PLANE' === op.type) {
return TCAD.UI.createPlaneWizard(app, alignComponent, initParams, true);
return UI.createPlaneWizard(app, alignComponent, initParams, true);
}
return null;
};
TCAD.UI.createCutExtrudeWizard = function (isCut, app, face, alignComponent, initParams, overriding) {
var tk = TCAD.toolkit;
UI.createCutExtrudeWizard = function (isCut, app, face, alignComponent, initParams, overriding) {
function def(index, fallback) {
return !!initParams ? initParams[index] : fallback;
}
var normal = TCAD.utils.vec(face.csgGroup.plane.normal);
var polygons = TCAD.craft.getSketchedPolygons3D(app, face);
var normal = cad_utils.vec(face.csgGroup.plane.normal);
var polygons = workbench.getSketchedPolygons3D(app, face);
var box = new tk.Box();
box.root.css({left : (alignComponent.root.width() + 10) + 'px', top : 0});
@ -196,7 +200,7 @@ TCAD.UI.createCutExtrudeWizard = function (isCut, app, face, alignComponent, ini
var scale = new tk.Number("Expansion", def(1, 1), 0.1, 1);
var deflection = new tk.Number("Deflection", def(2, 0), 1);
var angle = new tk.Number("Angle", def(3, 0), 5);
var wizard = new TCAD.wizards.ExtrudeWizard(app.viewer, polygons);
var wizard = new ExtrudeWizard(app.viewer, polygons);
function onChange() {
var depthValue = theValue.input.val();
var scaleValue = scale.input.val();
@ -248,12 +252,10 @@ TCAD.UI.createCutExtrudeWizard = function (isCut, app, face, alignComponent, ini
}
tk.add(folder, new tk.ButtonRow(["Cancel", "OK"], [close, isCut ? applyCut : applyExtrude]));
return new TCAD.UI.WizardRef(wizard, box, close, protoParams);
return new UI.WizardRef(wizard, box, close, protoParams);
};
TCAD.UI.createPlaneWizard = function (app, alignComponent, initParams, overiding) {
var tk = TCAD.toolkit;
UI.createPlaneWizard = function (app, alignComponent, initParams, overiding) {
var box = new tk.Box();
box.root.css({left : (alignComponent.root.width() + 10) + 'px', top : 0});
var folder = new tk.Folder("Add a Plane");
@ -264,7 +266,7 @@ TCAD.UI.createPlaneWizard = function (app, alignComponent, initParams, overiding
tk.add(folder, orientation);
tk.add(folder, depth);
var wizard = new TCAD.wizards.PlaneWizard(app.viewer);
var wizard = new PlaneWizard(app.viewer);
var orientationValue, w;
function onChange() {
wizard.update(orientationValue = orientation.getValue(), w = depth.input.val());
@ -289,12 +291,14 @@ TCAD.UI.createPlaneWizard = function (app, alignComponent, initParams, overiding
depth.input.on('t-change', onChange);
onChange();
tk.add(folder, new tk.ButtonRow(["Cancel", "OK"], [close, ok]));
return new TCAD.UI.WizardRef(wizard, box, close, protoParams);
return new UI.WizardRef(wizard, box, close, protoParams);
};
TCAD.UI.WizardRef = function(wizard, box, close, currentParams) {
UI.WizardRef = function(wizard, box, close, currentParams) {
this.wizard = wizard;
this.box = box;
this.close = close;
this.currentParams = currentParams;
};
};
export {UI}

File diff suppressed because one or more lines are too long

View file

@ -1,19 +1,7 @@
TCAD.DPR = (window.devicePixelRatio) ? window.devicePixelRatio : 1;
import * as cad_utils from '../utils/cad-utils'
import {Matrix3, AXIS, ORIGIN} from '../math/l3space'
TCAD.view = {};
TCAD.view.setFacesColor = function(faces, color) {
for (var i = 0; i < faces.length; ++i) {
var face = faces[i];
if (color == null) {
face.color.set(new THREE.Color());
} else {
face.color.set( color );
}
}
};
TCAD.view.FACE_COLOR = 0xB0C4DE;
TCAD.Viewer = function(bus) {
function Viewer(bus) {
this.bus = bus;
function aspect() {
return window.innerWidth / window.innerHeight;
@ -30,7 +18,7 @@ TCAD.Viewer = function(bus) {
scene.add(light);
var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(TCAD.DPR);
renderer.setPixelRatio(cad_utils.DPR);
renderer.setClearColor(0x808080, 1);
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
@ -87,15 +75,15 @@ TCAD.Viewer = function(bus) {
}
function addAxis(axis, color) {
var lineMaterial = new THREE.LineBasicMaterial({color: color, linewidth: 1/TCAD.DPR});
var lineMaterial = new THREE.LineBasicMaterial({color: color, linewidth: 1/cad_utils.DPR});
var axisGeom = new THREE.Geometry();
axisGeom.vertices.push(axis.multiply(-1000).three());
axisGeom.vertices.push(axis.multiply(1000).three());
scene.add(new THREE.Line(axisGeom, lineMaterial));
}
addAxis(TCAD.math.AXIS.X, 0xFF0000);
addAxis(TCAD.math.AXIS.Y, 0x00FF00);
addAxis(TCAD.math.AXIS.Z, 0x0000FF);
addAxis(AXIS.X, 0xFF0000);
addAxis(AXIS.Y, 0x00FF00);
addAxis(AXIS.Z, 0x0000FF);
function updateControlsAndHelpers() {
trackballControls.update();
@ -104,7 +92,7 @@ TCAD.Viewer = function(bus) {
this.workGroup = new THREE.Object3D();
this.scene.add(this.workGroup);
this.selectionMgr = new TCAD.SelectionManager( this, 0xFAFAD2, 0xFF0000, null);
this.selectionMgr = new SelectionManager( this, 0xFAFAD2, 0xFF0000, null);
var viewer = this;
var raycaster = new THREE.Raycaster();
@ -152,9 +140,20 @@ TCAD.Viewer = function(bus) {
render();
animate();
}
Viewer.setFacesColor = function(faces, color) {
for (var i = 0; i < faces.length; ++i) {
var face = faces[i];
if (color == null) {
face.color.set(new THREE.Color());
} else {
face.color.set( color );
}
}
};
TCAD.SelectionManager = function(viewer, selectionColor, readOnlyColor, defaultColor) {
function SelectionManager(viewer, selectionColor, readOnlyColor, defaultColor) {
this.viewer = viewer;
this.selectionColor = selectionColor;
this.readOnlyColor = readOnlyColor;
@ -173,7 +172,7 @@ TCAD.SelectionManager = function(viewer, selectionColor, readOnlyColor, defaultC
arrow.matrixAutoUpdate = false;
arrow.line.renderOrder = 1e11;
arrow.cone.renderOrder = 1e11;
arrow.line.material.linewidth = 1/TCAD.DPR;
arrow.line.material.linewidth = 1/cad_utils.DPR;
arrow.line.material.depthWrite = false;
arrow.line.material.depthTest = false;
arrow.cone.material.depthWrite = false;
@ -187,9 +186,9 @@ TCAD.SelectionManager = function(viewer, selectionColor, readOnlyColor, defaultC
this.basisGroup.add(yAxis);
this.basisGroup.visible = false;
viewer.scene.add(this.basisGroup);
};
}
TCAD.SelectionManager.prototype.updateBasis = function(basis, depth) {
SelectionManager.prototype.updateBasis = function(basis, depth) {
this.basisGroup.matrix.identity();
var mx = new THREE.Matrix4();
mx.makeBasis(basis[0].three(), basis[1].three(), basis[2].three());
@ -199,7 +198,7 @@ TCAD.SelectionManager.prototype.updateBasis = function(basis, depth) {
this.basisGroup.applyMatrix(mx);
};
TCAD.SelectionManager.prototype.handlePick = function(event) {
SelectionManager.prototype.handlePick = function(event) {
var pickResults = this.viewer.raycast(event);
for (var i = 0; i < pickResults.length; i++) {
@ -214,26 +213,26 @@ TCAD.SelectionManager.prototype.handlePick = function(event) {
}
};
TCAD.SelectionManager.prototype.select = function(sketchFace) {
SelectionManager.prototype.select = function(sketchFace) {
this.clear();
if (sketchFace.curvedSurfaces !== null) {
for (var i = 0; i < sketchFace.curvedSurfaces.length; i++) {
var face = sketchFace.curvedSurfaces[i];
this.selection.push(face);
TCAD.view.setFacesColor(face.faces, this.readOnlyColor);
Viewer.setFacesColor(face.faces, this.readOnlyColor);
}
} else {
this.selection.push(sketchFace);
this.updateBasis(sketchFace.basis(), sketchFace.depth());
this.basisGroup.visible = true;
TCAD.view.setFacesColor(sketchFace.faces, this.selectionColor);
Viewer.setFacesColor(sketchFace.faces, this.selectionColor);
}
sketchFace.solid.mesh.geometry.colorsNeedUpdate = true;
this.viewer.bus.notify('selection', sketchFace);
this.viewer.render();
};
TCAD.SelectionManager.prototype.deselectAll = function() {
SelectionManager.prototype.deselectAll = function() {
for (var i = 0; i < this.selection.length; ++ i) {
this.selection[i].solid.mesh.geometry.colorsNeedUpdate = true;
}
@ -241,15 +240,16 @@ TCAD.SelectionManager.prototype.deselectAll = function() {
this.viewer.render();
};
TCAD.SelectionManager.prototype.contains = function(face) {
SelectionManager.prototype.contains = function(face) {
return this.selection.indexOf(face) != -1;
};
TCAD.SelectionManager.prototype.clear = function() {
SelectionManager.prototype.clear = function() {
for (var i = 0; i < this.selection.length; ++ i) {
TCAD.view.setFacesColor(this.selection[i].faces, this.defaultColor);
Viewer.setFacesColor(this.selection[i].faces, this.defaultColor);
}
this.selection.length = 0;
this.basisGroup.visible = false;
};
export {Viewer, SelectionManager}

View file

@ -1,27 +1,31 @@
TCAD.wizards = {};
import Vector from '../../math/vector'
import * as cad_utils from '../../utils/cad-utils'
import * as math from '../../math/math'
import {Matrix3, AXIS, ORIGIN, IDENTITY_BASIS} from '../../math/l3space'
TCAD.wizards.IMAGINE_MATERIAL = new THREE.LineBasicMaterial({
var IMAGINE_MATERIAL = new THREE.LineBasicMaterial({
color: 0xFA8072,
linewidth: 1/TCAD.DPR,
linewidth: 1/cad_utils.DPR,
depthWrite: false,
depthTest: false
});
TCAD.wizards.BASE_MATERIAL = new THREE.LineBasicMaterial({
var BASE_MATERIAL = new THREE.LineBasicMaterial({
color: 0x8B0000,
linewidth: 3/TCAD.DPR,
linewidth: 3/cad_utils.DPR,
depthWrite: false,
depthTest: false
});
TCAD.wizards.OpWizard = function(viewer) {
function OpWizard(viewer) {
this.previewGroup = new THREE.Object3D();
this.lines = [];
this.viewer = viewer;
viewer.scene.add(this.previewGroup);
};
}
TCAD.wizards.OpWizard.prototype.setupLine = function(lineId, a, b, material) {
OpWizard.prototype.setupLine = function(lineId, a, b, material) {
var line = this.lines[lineId];
if (line === undefined) {
var lg = new THREE.Geometry();
@ -38,27 +42,27 @@ TCAD.wizards.OpWizard.prototype.setupLine = function(lineId, a, b, material) {
}
};
TCAD.wizards.OpWizard.prototype.dispose = function() {
OpWizard.prototype.dispose = function() {
this.viewer.scene.remove(this.previewGroup);
this.viewer.render();
};
TCAD.wizards.ExtrudeWizard = function(viewer, polygons) {
TCAD.wizards.OpWizard.call(this, viewer);
function ExtrudeWizard(viewer, polygons) {
OpWizard.call(this, viewer);
this.polygons = polygons;
};
}
TCAD.wizards.ExtrudeWizard.prototype = Object.create( TCAD.wizards.OpWizard.prototype );
ExtrudeWizard.prototype = Object.create( OpWizard.prototype );
TCAD.wizards.ExtrudeWizard.prototype.update = function(basis, normal, depth, scale, deflection, angle) {
ExtrudeWizard.prototype.update = function(basis, normal, depth, scale, deflection, angle) {
var linesCounter = 0;
var target;
if (deflection != 0) {
target = normal.copy();
if (depth < 0) target._negate();
target = TCAD.math.rotateMatrix(deflection * Math.PI / 180, basis[0], TCAD.math.ORIGIN)._apply(target);
target = Matrix3.rotateMatrix(deflection * Math.PI / 180, basis[0], ORIGIN)._apply(target);
if (angle != 0) {
target = TCAD.math.rotateMatrix(angle * Math.PI / 180, basis[2], TCAD.math.ORIGIN)._apply(target);
target = Matrix3.rotateMatrix(angle * Math.PI / 180, basis[2], ORIGIN)._apply(target);
}
target._multiply(Math.abs(depth));
} else {
@ -66,14 +70,14 @@ TCAD.wizards.ExtrudeWizard.prototype.update = function(basis, normal, depth, sca
}
for (var i = 0; i < this.polygons.length; i++) {
var poly = this.polygons[i];
var lid = TCAD.geom.calculateExtrudedLid(poly, normal, target, scale);
var lid = cad_utils.calculateExtrudedLid(poly, normal, target, scale);
var p, q, n = poly.length;
for (p = n - 1, q = 0; q < n; p = q++) {
this.setupLine(linesCounter ++, poly[p], poly[q], TCAD.wizards.BASE_MATERIAL);
this.setupLine(linesCounter ++, lid[p], lid[q], TCAD.wizards.IMAGINE_MATERIAL);
this.setupLine(linesCounter ++, poly[p], poly[q], BASE_MATERIAL);
this.setupLine(linesCounter ++, lid[p], lid[q], IMAGINE_MATERIAL);
}
for (q = 0; q < n; q++) {
this.setupLine(linesCounter ++, poly[q], lid[q], TCAD.wizards.IMAGINE_MATERIAL);
this.setupLine(linesCounter ++, poly[q], lid[q], IMAGINE_MATERIAL);
}
}
this.operationParams = {
@ -82,27 +86,26 @@ TCAD.wizards.ExtrudeWizard.prototype.update = function(basis, normal, depth, sca
}
};
TCAD.wizards.PlaneWizard = function(viewer) {
function PlaneWizard(viewer) {
this.previewGroup = new THREE.Object3D();
this.viewer = viewer;
viewer.scene.add(this.previewGroup);
this.previewGroup.add(this.plane = this.createPlane());
this.viewer.render();
this.operationParams = {
basis : TCAD.math.IDENTITY_BASIS,
basis : IDENTITY_BASIS,
depth : 0
};
};
}
TCAD.wizards.PlaneWizard.prototype.createPlane = function() {
PlaneWizard.prototype.createPlane = function() {
var geometry = new THREE.PlaneGeometry(750,750,1,1,1);
var material = new THREE.MeshLambertMaterial( { color : TCAD.view.FACE_COLOR, transparent: true, opacity:0.5, side: THREE.DoubleSide });
var material = new THREE.MeshLambertMaterial( { color : cad_utils.FACE_COLOR, transparent: true, opacity:0.5, side: THREE.DoubleSide });
var plane = new THREE.Mesh(geometry, material);
return plane;
};
TCAD.wizards.PlaneWizard.prototype.update = function(orientation, w) {
PlaneWizard.prototype.update = function(orientation, w) {
if (orientation === 'XY') {
this.plane.rotation.x = 0;
this.plane.rotation.y = 0;
@ -110,7 +113,7 @@ TCAD.wizards.PlaneWizard.prototype.update = function(orientation, w) {
this.plane.position.x = 0;
this.plane.position.y = 0;
this.plane.position.z = w;
this.operationParams.basis = TCAD.math.IDENTITY_BASIS;
this.operationParams.basis = IDENTITY_BASIS;
} else if (orientation === 'XZ') {
this.plane.rotation.x = Math.PI / 2;
this.plane.rotation.y = 0;
@ -118,7 +121,7 @@ TCAD.wizards.PlaneWizard.prototype.update = function(orientation, w) {
this.plane.position.x = 0;
this.plane.position.y = w;
this.plane.position.z = 0;
this.operationParams.basis = [TCAD.math.AXIS.X, TCAD.math.AXIS.Z, TCAD.math.AXIS.Y];
this.operationParams.basis = [AXIS.X, AXIS.Z, AXIS.Y];
} else if (orientation === 'ZY') {
this.plane.rotation.x = 0;
this.plane.rotation.y = Math.PI / 2;
@ -126,7 +129,7 @@ TCAD.wizards.PlaneWizard.prototype.update = function(orientation, w) {
this.plane.position.x = w;
this.plane.position.y = 0;
this.plane.position.z = 0;
this.operationParams.basis = [TCAD.math.AXIS.Z, TCAD.math.AXIS.Y, TCAD.math.AXIS.X];
this.operationParams.basis = [AXIS.Z, AXIS.Y, AXIS.X];
} else {
throw orientation + " isn't supported yet";
}
@ -134,7 +137,9 @@ TCAD.wizards.PlaneWizard.prototype.update = function(orientation, w) {
this.viewer.render();
};
TCAD.wizards.PlaneWizard.prototype.dispose = function() {
PlaneWizard.prototype.dispose = function() {
this.viewer.scene.remove(this.previewGroup);
this.viewer.render();
};
};
export {ExtrudeWizard, PlaneWizard}

View file

@ -1,15 +1,19 @@
TCAD.workbench = {};
import Vector from '../math/vector'
import * as cad_utils from '../utils/cad-utils'
import * as math from '../math/math'
import {Matrix3, AXIS, ORIGIN} from '../math/l3space'
import {HashTable} from '../utils/hashmap'
TCAD.workbench.SketchConnection = function(a, b, sketchObject) {
function SketchConnection(a, b, sketchObject) {
this.a = a;
this.b = b;
this.sketchObject = sketchObject;
};
}
TCAD.workbench._SKETCH_OBJ_COUNTER = 0;
TCAD.workbench.readSketchGeom = function(sketch) {
var _SKETCH_OBJ_COUNTER = 0;
export function readSketchGeom(sketch) {
function genId() {
return TCAD.workbench._SKETCH_OBJ_COUNTER++;
return _SKETCH_OBJ_COUNTER++;
}
var out = {connections : [], loops : []};
if (sketch.layers !== undefined) {
@ -21,26 +25,26 @@ TCAD.workbench.readSketchGeom = function(sketch) {
if (obj.edge !== undefined) continue;
if (!!obj.aux) continue;
if (obj._class === 'TCAD.TWO.Segment') {
var a = new TCAD.Vector(obj.points[0][1][1], obj.points[0][2][1], 0);
var b = new TCAD.Vector(obj.points[1][1][1], obj.points[1][2][1], 0);
out.connections.push(new TCAD.workbench.SketchConnection(a, b, {_class : obj._class, id : genId()}));
var segA = new Vector(obj.points[0][1][1], obj.points[0][2][1], 0);
var segB = new Vector(obj.points[1][1][1], obj.points[1][2][1], 0);
out.connections.push(new SketchConnection(segA, segB, {_class : obj._class, id : genId()}));
} else if (obj._class === 'TCAD.TWO.Arc') {
var a = new TCAD.Vector(obj.points[0][1][1], obj.points[0][2][1], 0);
var b = new TCAD.Vector(obj.points[1][1][1], obj.points[1][2][1], 0);
var center = new TCAD.Vector(obj.points[2][1][1], obj.points[2][2][1], 0);
var approxArc = TCAD.workbench.approxArc(a, b, center, 20);
var data = {_class : obj._class, id : genId()};
for (var j = 0; j < approxArc.length - 1; j++) {
out.connections.push(new TCAD.workbench.SketchConnection(approxArc[j], approxArc[j+1], data));
var arcA = new Vector(obj.points[0][1][1], obj.points[0][2][1], 0);
var arcB = new Vector(obj.points[1][1][1], obj.points[1][2][1], 0);
var arcCenter = new Vector(obj.points[2][1][1], obj.points[2][2][1], 0);
var approxedArc = approxArc(arcA, arcB, arcCenter, 20);
var arcData = {_class : obj._class, id : genId()};
for (var j = 0; j < approxedArc.length - 1; j++) {
out.connections.push(new SketchConnection(approxedArc[j], approxedArc[j+1], arcData));
}
} else if (obj._class === 'TCAD.TWO.Circle') {
var center = new TCAD.Vector(obj.c[1][1], obj.c[2][1], 0);
var approxCircle = TCAD.workbench.approxCircle(center, obj.r, 20);
var data = {_class : obj._class, id : genId()};
var circleCenter = new Vector(obj.c[1][1], obj.c[2][1], 0);
var approxedCircle = approxCircle(circleCenter, obj.r, 20);
var circleData = {_class : obj._class, id : genId()};
var loop = [];
var p, q, n = approxCircle.length;
for (var p = n - 1, q = 0; q < n; p = q++) {
loop.push(new TCAD.workbench.SketchConnection(approxCircle[p], approxCircle[q], data));
var p, q, n = approxedCircle.length;
for (p = n - 1, q = 0; q < n; p = q++) {
loop.push(new SketchConnection(approxedCircle[p], approxedCircle[q], circleData));
}
out.loops.push(loop);
}
@ -48,9 +52,9 @@ TCAD.workbench.readSketchGeom = function(sketch) {
}
}
return out;
};
}
TCAD.workbench.approxArc = function(ao, bo, c, resolution) {
export function approxArc(ao, bo, c, resolution) {
var a = ao.minus(c);
var b = bo.minus(c);
var points = [ao];
@ -66,14 +70,14 @@ TCAD.workbench.approxArc = function(ao, bo, c, resolution) {
var angle = Math.atan2(a.y, a.x) + step;
for (var i = 0; i < k - 1; ++i) {
points.push(new TCAD.Vector(c.x + r*Math.cos(angle), c.y + r*Math.sin(angle)));
points.push(new Vector(c.x + r*Math.cos(angle), c.y + r*Math.sin(angle)));
angle += step;
}
points.push(bo);
return points;
};
}
TCAD.workbench.approxCircle = function(c, r, resolution) {
export function approxCircle(c, r, resolution) {
var points = [];
resolution = 1;
@ -82,31 +86,19 @@ TCAD.workbench.approxCircle = function(c, r, resolution) {
var k = Math.round((2 * Math.PI) / step);
for (var i = 0, angle = 0; i < k; ++i, angle += step) {
points.push(new TCAD.Vector(c.x + r*Math.cos(angle), c.y + r*Math.sin(angle)));
points.push(new Vector(c.x + r*Math.cos(angle), c.y + r*Math.sin(angle)));
}
return points;
};
}
TCAD.workbench.serializeSolid = function(solid) {
var data = {};
data.faceCounter = TCAD.geom.FACE_COUNTER;
for (var fi = 0; fi < solid.faces.length; ++fi) {
var face = solid.faces[fi];
var faceData = {};
faceData.id = face.id;
}
return data;
};
TCAD.craft = {};
TCAD.craft.getSketchedPolygons3D = function(app, face) {
export function getSketchedPolygons3D(app, face) {
var savedFace = localStorage.getItem(app.faceStorageKey(face.id));
if (savedFace == null) return null;
var geom = TCAD.workbench.readSketchGeom(JSON.parse(savedFace));
var polygons2D = TCAD.utils.sketchToPolygons(geom);
var geom = readSketchGeom(JSON.parse(savedFace));
var polygons2D = cad_utils.sketchToPolygons(geom);
var normal = face.csgGroup.normal;
var depth = null;
@ -116,7 +108,7 @@ TCAD.craft.getSketchedPolygons3D = function(app, face) {
if (poly2D.length < 3) continue;
if (depth == null) {
var _3dTransformation = new TCAD.Matrix().setBasis(face.basis());
var _3dTransformation = new Matrix3().setBasis(face.basis());
//we lost depth or z off in 2d sketch, calculate it again
depth = face.csgGroup.plane.w;
}
@ -125,7 +117,7 @@ TCAD.craft.getSketchedPolygons3D = function(app, face) {
for (var m = 0; m < poly2D.length; ++m) {
var vec = poly2D[m];
vec.z = depth;
// var a = _3dTransformation.apply(new TCAD.Vector(poly2D[m][0], poly2D[m][1], depth));
// var a = _3dTransformation.apply(new Vector(poly2D[m][0], poly2D[m][1], depth));
var a = _3dTransformation.apply(vec);
a.sketchConnectionObject = vec.sketchConnectionObject;
polygon.push(a);
@ -134,32 +126,32 @@ TCAD.craft.getSketchedPolygons3D = function(app, face) {
sketchedPolygons.push(polygon);
}
return sketchedPolygons;
};
}
TCAD.craft.extrude = function(app, request) {
export function extrude(app, request) {
var face = request.face;
var sketchedPolygons = TCAD.craft.getSketchedPolygons3D(app, face);
var sketchedPolygons = getSketchedPolygons3D(app, face);
if (sketchedPolygons == null) return null;
var normal = TCAD.utils.vec(face.csgGroup.plane.normal);
var normal = cad_utils.vec(face.csgGroup.plane.normal);
var toMeldWith = [];
for (var i = 0; i < sketchedPolygons.length; i++) {
var extruded = TCAD.geom.extrude(sketchedPolygons[i], normal, request.params.target, request.params.expansionFactor );
var extruded = cad_utils.extrude(sketchedPolygons[i], normal, request.params.target, request.params.expansionFactor );
toMeldWith = toMeldWith.concat(extruded);
}
var solid = request.solids[0];
var meld = CSG.fromPolygons(TCAD.craft._triangulateCSG(toMeldWith));
var meld = CSG.fromPolygons(_triangulateCSG(toMeldWith));
if (solid.mergeable) {
meld = solid.csg.union(meld);
}
face.csgGroup.shared.__tcad.faceId += '$';
return [TCAD.utils.createSolid(meld)];
};
return [cad_utils.createSolid(meld)];
}
TCAD.craft._pointOnLine = function(p, a, b) {
function _pointOnLine(p, a, b) {
var ab = a.minus(b);
var ap = a.minus(p);
@ -169,12 +161,12 @@ TCAD.craft._pointOnLine = function(p, a, b) {
var abLength = ab.length();
var apLength = ap.length();
return apLength > 0 && apLength < abLength && TCAD.utils.areEqual(abLength * apLength, dp, 1E-6);
};
return apLength > 0 && apLength < abLength && math.areEqual(abLength * apLength, dp, 1E-6);
}
TCAD.craft.polygonsToSegments = function(polygons) {
export function polygonsToSegments(polygons) {
function selfIntersecting(a, b, c) {
var f = TCAD.craft._pointOnLine;
var f = _pointOnLine;
return f(c, a, b) || f(a, b, c) || f(b, c, a);
}
//polygons.filter(function(p) {
@ -199,9 +191,9 @@ TCAD.craft.polygonsToSegments = function(polygons) {
segmentsByPolygon.push(segments);
}
return segmentsByPolygon;
};
}
TCAD.craft.reconstructSketchBounds = function(csg, face, strict) {
export function reconstructSketchBounds(csg, face, strict) {
strict = strict || false;
var polygons = csg.toPolygons();
var plane = face.csgGroup.plane;
@ -209,8 +201,8 @@ TCAD.craft.reconstructSketchBounds = function(csg, face, strict) {
var planePolygons = [];
for (var pi = 0; pi < polygons.length; pi++) {
var poly = polygons[pi];
if (TCAD.utils.equal(poly.plane.normal.dot(plane.normal), 1)) {
if (TCAD.utils.equal(plane.w, poly.plane.w) && (!strict || !!poly.shared.__tcad && poly.shared.__tcad.faceId === face.id)) {
if (math.equal(poly.plane.normal.dot(plane.normal), 1)) {
if (math.equal(plane.w, poly.plane.w) && (!strict || !!poly.shared.__tcad && poly.shared.__tcad.faceId === face.id)) {
planePolygons.push(poly);
}
continue;
@ -219,68 +211,67 @@ TCAD.craft.reconstructSketchBounds = function(csg, face, strict) {
for(p = n - 1, q = 0; q < n; p = q ++) {
var a = poly.vertices[p];
var b = poly.vertices[q];
var pointAOnPlane = TCAD.utils.equal(plane.signedDistanceToPoint(a.pos), 0);
var pointAOnPlane = math.equal(plane.signedDistanceToPoint(a.pos), 0);
if (!pointAOnPlane) continue;
var pointBOnPlane = TCAD.utils.equal(plane.signedDistanceToPoint(b.pos), 0);
var pointBOnPlane = math.equal(plane.signedDistanceToPoint(b.pos), 0);
if (pointBOnPlane) {
outerEdges.push([a.pos, b.pos, poly]);
}
}
}
var outline = TCAD.craft.findOutline(planePolygons);
var outline = findOutline(planePolygons);
TCAD.craft.pickUpCraftInfo(outline, outerEdges);
pickUpCraftInfo(outline, outerEdges);
return TCAD.craft.segmentsToPaths(outline);
};
return segmentsToPaths(outline);
}
TCAD.craft.pickUpCraftInfo = function(outline, outerEdges) {
var eq = TCAD.utils.strictEqual;
function pickUpCraftInfo(outline, outerEdges) {
var eq = math.strictEqual;
for (var psi1 = 0; psi1 < outline.length; psi1++) {
var s1 = outline[psi1];
for (var psi2 = 0; psi2 < outerEdges.length; psi2++) {
var s2 = outerEdges[psi2];
if (TCAD.utils.equal(Math.abs(s1[0].minus(s1[1]).unit().dot(s2[0].minus(s2[1]).unit())), 1) &&
if (math.equal(Math.abs(s1[0].minus(s1[1]).unit().dot(s2[0].minus(s2[1]).unit())), 1) &&
(eq(s1[0], s2[0]) || eq(s1[1], s2[1]) || eq(s1[0], s2[1]) || eq(s1[1], s2[0]) ||
TCAD.craft._pointOnLine(s1[0], s2[0], s2[1]) || TCAD.craft._pointOnLine(s1[1], s2[0], s2[1]))) {
_pointOnLine(s1[0], s2[0], s2[1]) || _pointOnLine(s1[1], s2[0], s2[1]))) {
s1[2] = s2[2];
}
}
}
};
}
TCAD.craft.getOutlineByCollision = function(segments, outerEdges) {
var eq = TCAD.utils.strictEqual;
function getOutlineByCollision(segments, outerEdges) {
var eq = math.strictEqual;
var outline = [];
for (var psi1 = 0; psi1 < segments.length; psi1++) {
var s1 = segments[psi1];
for (var psi2 = 0; psi2 < outerEdges.length; psi2++) {
var s2 = outerEdges[psi2];
if (TCAD.utils.equal(Math.abs(s1[0].minus(s1[1]).unit().dot(s2[0].minus(s2[1]).unit())), 1) &&
if (math.equal(Math.abs(s1[0].minus(s1[1]).unit().dot(s2[0].minus(s2[1]).unit())), 1) &&
(eq(s1[0], s2[0]) || eq(s1[1], s2[1]) || eq(s1[0], s2[1]) || eq(s1[1], s2[0]) ||
TCAD.craft._pointOnLine(s1[0], s2[0], s2[1]) || TCAD.craft._pointOnLine(s1[1], s2[0], s2[1]))) {
_pointOnLine(s1[0], s2[0], s2[1]) || _pointOnLine(s1[1], s2[0], s2[1]))) {
outline.push(s1);
}
}
}
return outline;
};
}
TCAD.craft.findOutline = function(planePolygons, outer) {
var segmentsByPolygon = TCAD.craft.polygonsToSegments(planePolygons);
//TCAD.craft.simplifySegments(segmentsByPolygon);
var planeSegments = TCAD.utils.arrFlatten1L(segmentsByPolygon);
//planeSegments = TCAD.craft.removeSharedEdges(planeSegments);
TCAD.craft.removeTJoints(planeSegments);
planeSegments = TCAD.craft.removeSharedEdges(planeSegments);
function findOutline (planePolygons, outer) {
var segmentsByPolygon = polygonsToSegments(planePolygons);
//simplifySegments(segmentsByPolygon);
var planeSegments = cad_utils.arrFlatten1L(segmentsByPolygon);
//planeSegments = removeSharedEdges(planeSegments);
removeTJoints(planeSegments);
planeSegments = removeSharedEdges(planeSegments);
return planeSegments;
};
}
TCAD.craft.removeSharedEdges = function(segments) {
function removeSharedEdges(segments) {
segments = segments.slice();
var eq = TCAD.utils.strictEqual;
var eq = math.strictEqual;
for (var psi1 = 0; psi1 < segments.length; psi1++) {
var s1 = segments[psi1];
if (s1 == null) continue;
@ -295,9 +286,9 @@ TCAD.craft.removeSharedEdges = function(segments) {
}
}
return segments.filter(function(e) {return e !== null});
};
}
TCAD.craft.simplifySegments = function(polygonToSegments) {
function simplifySegments(polygonToSegments) {
for (var pi1 = 0; pi1 < polygonToSegments.length; ++pi1) {
for (var pi2 = 0; pi2 < polygonToSegments.length; ++pi2) {
if (pi1 === pi2) continue;
@ -307,7 +298,7 @@ TCAD.craft.simplifySegments = function(polygonToSegments) {
var seg1 = polygon1[si1];
for (var si2 = 0; si2 < polygon2.length; ++si2) {
var point = polygon2[si2][0];
if (TCAD.craft._pointOnLine(point, seg1[0], seg1[1])) {
if (_pointOnLine(point, seg1[0], seg1[1])) {
polygon1.push([point, seg1[1]]);
seg1[1] = point;
}
@ -315,9 +306,9 @@ TCAD.craft.simplifySegments = function(polygonToSegments) {
}
}
}
};
}
TCAD.craft._closeFactorToLine = function(p, seg1, seg2) {
function _closeFactorToLine(p, seg1, seg2) {
var a = p.minus(seg1);
var b = seg2.minus(seg1);
@ -331,10 +322,10 @@ TCAD.craft._closeFactorToLine = function(p, seg1, seg2) {
var c = a.minus(bx);
return c.length();
};
}
TCAD.craft.removeTJoints = function(segments) {
var pointIndex = TCAD.struct.hashTable.forVector3d();
function removeTJoints(segments) {
var pointIndex = HashTable.forVector3d();
for (var i = 0; i < segments.length; ++i) {
pointIndex.put(segments[i][0], 1);
@ -342,14 +333,14 @@ TCAD.craft.removeTJoints = function(segments) {
}
var points = pointIndex.getKeys();
var eq = TCAD.utils.strictEqual;
var eq = math.strictEqual;
for (var pi1 = 0; pi1 < points.length; ++pi1) {
var point = points[pi1];
var best = null, bestFactor;
for (var pi2 = 0; pi2 < segments.length; ++pi2) {
var seg = segments[pi2];
if (eq(seg[0], point) || eq(seg[1], point)) continue;
var factor = TCAD.craft._closeFactorToLine(point, seg[0], seg[1]);
var factor = _closeFactorToLine(point, seg[0], seg[1]);
if (factor != -1 && factor < 1E-6 && (best == null || factor < bestFactor)) {
best = seg;
bestFactor = factor;
@ -360,10 +351,9 @@ TCAD.craft.removeTJoints = function(segments) {
best[1] = point;
}
}
};
}
TCAD.craft.deleteRedundantPoints = function(path) {
function deleteRedundantPoints(path) {
var cleanedPath = [];
//Delete redundant point
var pathLength = path.length;
@ -373,20 +363,19 @@ TCAD.craft.deleteRedundantPoints = function(path) {
var a = path[pi];
var b = path[bIdx];
var c = path[(pi + 2) % pathLength];
var eq = TCAD.utils.areEqual;
var eq = math.areEqual;
if (!skipMode) cleanedPath.push(a);
skipMode = eq(a.minus(b).unit().dot(b.minus(c).unit()), 1, 1E-9);
}
return cleanedPath;
};
}
TCAD.craft.segmentsToPaths = function(segments) {
var veq = TCAD.struct.hashTable.vectorEquals;
function segmentsToPaths(segments) {
var veq = math.strictEqual;
var paths = [];
var index = TCAD.struct.hashTable.forVector3d();
var csgIndex = TCAD.struct.hashTable.forEdge();
var index = HashTable.forVector3d();
var csgIndex = HashTable.forEdge();
function indexPoint(p, edge) {
var edges = index.get(p);
@ -425,13 +414,14 @@ TCAD.craft.segmentsToPaths = function(segments) {
return null;
}
var path;
for (var ei = 0; ei < segments.length; ei++) {
var edge = segments[ei];
if (edge[3]) {
continue;
}
edge[3] = true;
var path = [edge[0], edge[1]];
path = [edge[0], edge[1]];
paths.push(path);
var next = nextPoint(edge[1]);
while (next !== null) {
@ -446,10 +436,10 @@ TCAD.craft.segmentsToPaths = function(segments) {
var filteredPaths = [];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
path = paths[i];
//Set derived from object to be able to recunstruct
TCAD.utils.iteratePath(path, 0, function (a, b) {
cad_utils.iteratePath(path, 0, function (a, b) {
var fromPolygon = csgIndex.get([a, b]);
if (fromPolygon !== null) {
if (fromPolygon.shared.__tcad.csgInfo) {
@ -458,7 +448,7 @@ TCAD.craft.segmentsToPaths = function(segments) {
}
return true;
});
path = TCAD.craft.deleteRedundantPoints(path);
path = deleteRedundantPoints(path);
if (path.length > 2) {
filteredPaths.push({
vertices: path
@ -467,9 +457,9 @@ TCAD.craft.segmentsToPaths = function(segments) {
}
return filteredPaths;
};
}
TCAD.craft._triangulateCSG = function(polygons) {
function _triangulateCSG(polygons) {
function csgVec(v) {
return new CSG.Vector3D(v.x, v.y, v.z);
}
@ -477,7 +467,7 @@ TCAD.craft._triangulateCSG = function(polygons) {
for (var ei = 0; ei < polygons.length; ++ei) {
var poly = polygons[ei];
var points = poly.vertices;
var refs = TCAD.geom.triangulate(points, poly.plane.normal);
var refs = cad_utils.triangulate(points, poly.plane.normal);
for ( var i = 0; i < refs.length; ++ i ) {
var a = refs[i][0];
var b = refs[i][1];
@ -487,9 +477,9 @@ TCAD.craft._triangulateCSG = function(polygons) {
}
}
return triangled;
};
}
TCAD.craft.splitTwoSegments = function (a, b) {
function splitTwoSegments(a, b) {
var da = a[1].minus(a[0]);
var db = b[1].minus(b[0]);
var dc = b[0].minus(a[0]);
@ -499,34 +489,33 @@ TCAD.craft.splitTwoSegments = function (a, b) {
// lines are not coplanar
return null;
}
var veq = TCAD.utils.vectorsEqual;
var veq = math.strictEqual;
if (veq(a[0], b[0]) || veq(a[0], b[1]) || veq(a[1], b[0]) || veq(a[1], b[1])) {
return null;
}
var dcXdb = dc.cross(db);
function _split(s, ip) {
if (s[0].equals(ip) || s[1].equals(ip)) {
return [s];
}
return [[s[0], ip, s[2]], [ip, s[1], s[2]]]
}
var s = dcXdb.dot(daXdb) / daXdb.lengthSquared();
if (s > 0.0 && s < 1.0) {
var ip = a[0].plus(da.times(s));
function _split(s, ip) {
if (s[0].equals(ip) || s[1].equals(ip)) {
return [s];
}
return [[s[0], ip, s[2]], [ip, s[1], s[2]]]
}
return {
splitterParts : _split(a, ip),
residual : _split(b, ip)
}
}
return null;
};
}
TCAD.craft.attract = function(vectors, precision) {
var eq = TCAD.utils.areEqual();
var dist = TCAD.math.distanceAB3;
function attract(vectors, precision) {
var eq = math.areEqual();
var dist = math.distanceAB3;
vectors = vectors.slice();
for (var i = 0; i < vectors.length; i++) {
var v1 = vectors[i];
@ -535,27 +524,28 @@ TCAD.craft.attract = function(vectors, precision) {
var v2 = vectors[j];
if (v2 == null) continue;
if (dist(v1, v2) <= precision) {
TCAD.Vector.prototype.setV.call(v2, v1);
Vector.prototype.setV.call(v2, v1);
vectors[j] = null;
}
}
}
};
}
TCAD.craft.recoverySketchInfo = function(polygons) {
function recoverySketchInfo(polygons) {
var nonStructuralGons = [];
var sketchEdges = TCAD.struct.hashTable.forDoubleArray();
function key(a, b) {return [a.x, a.y, b.x, b.y]};
var sketchEdges = HashTable.forDoubleArray();
function key(a, b) {return [a.x, a.y, b.x, b.y]}
for (var pi = 0; pi < polygons.length; pi++) {
var poly = polygons[pi];
var paths = [];
poly.collectPaths(paths);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var i, path, n, p, q;
for (i = 0; i < paths.length; i++) {
path = paths[i];
if (poly.csgInfo !== undefined && poly.csgInfo.derivedFrom !== undefined) {
var n = path.length;
for (var p = n - 1, q = 0; q < n ; p = q++ ) {
n = path.length;
for (p = n - 1, q = 0; q < n ; p = q++ ) {
sketchEdges.put(key(path[p], path[q]), poly.csgInfo);
}
} else {
@ -564,10 +554,10 @@ TCAD.craft.recoverySketchInfo = function(polygons) {
}
}
for (var i = 0; i < nonStructuralGons.length; i++) {
var path = nonStructuralGons[i];
var n = path.length;
for (var p = n - 1, q = 0; q < n ; p = q++ ) {
for (i = 0; i < nonStructuralGons.length; i++) {
path = nonStructuralGons[i];
n = path.length;
for (p = n - 1, q = 0; q < n ; p = q++ ) {
var csgInfo = sketchEdges.get(key(path[p], path[q]));
if (csgInfo === null) {
csgInfo = sketchEdges.get(key(path[q], path[p]));
@ -577,235 +567,33 @@ TCAD.craft.recoverySketchInfo = function(polygons) {
}
}
}
};
}
TCAD.craft.reconstruct = function (cut) {
function pInP(p1, p2) {
var notEqPoints = [];
for (var i = 0; i < p1.length; ++i) {
var v1 = p1[i];
for (var j = 0; j < p2.length; ++j) {
var v2 = p2[j];
if (!v1.equals(v2)) {
notEqPoints.push(v1);
break;
}
}
}
if (notEqPoints.length == 0) {
return true;
}
for (var i = 0; i < notEqPoints.length; ++i) {
var v = notEqPoints[i];
if (!TCAD.utils.isPointInsidePolygon(v, p2)) {
return false;
}
}
return true;
}
function sortPaths(paths3D) {
var transforms = TCAD.struct.hashTable.forVector3d();
var paths = paths3D.map(function(path) {
var tr = transforms.get(path.normal);
if (tr === null) {
var _3dTransformation = new TCAD.Matrix().setBasis(TCAD.geom.someBasis(path.vertices, path.normal));
var tr = _3dTransformation.invert();
transforms.put(path.normal, tr);
}
return {
vertices : path.vertices.map(function(v) {return tr.apply(v);}),
normal : path.normal,
shared : path.shared
}
});
var index = [];
for (var pi = 0; pi < paths.length; ++pi) {
index[pi] = [];
paths3D[pi].holes = [];
}
for (var pi = 0; pi < paths.length; ++pi) {
var path = paths[pi];
for (var piTest = 0; piTest < paths.length; ++piTest) {
var pathTest = paths[piTest];
if (piTest === pi) continue;
if (pInP(pathTest.vertices, path.vertices)) {
index[piTest].push(pi);
}
}
}
function collect(master, level) {
var success = false;
for (var i = 0; i < index.length; ++i) {
var masters = index[i];
if (level != masters.length) continue;
for (var j = 0; j < masters.length; ++j) {
var m = masters[j];
if (m === master) {
paths3D[m].holes.push(paths3D[i])
success = true;
}
}
}
return success;
}
for (var success = true, level = 1;
level < paths3D.length && success;
level ++, success = false) {
for (var i = 0; i < index.length; ++i) {
var masters = index[i];
if (masters.length == level - 1) {
if (collect(i, level)) {
success = true;
}
}
}
}
function separate(path, separated) {
separated.push(path);
for (var i = 0; i < path.holes.length; ++i) {
var hole = path.holes[i];
for (var j = 0; j < hole.holes.length; ++j) {
var inner = hole.holes[j];
separate(inner, separated)
}
}
}
var separated = [];
for (var i = 0; i < index.length; ++i) {
var masters = index[i];
if (masters.length == 0) {
separate(paths3D[i], separated);
}
}
return separated;
}
var byShared = {};
for (var i = 0; i < cut.polygons.length; i++) {
var p = cut.polygons[i];
var tag = p.shared.getTag();
if (byShared[tag] === undefined) byShared[tag] = [];
byShared[tag].push(p);
}
var result = [];
var allPoints = [];
for (var tag in byShared) {
var merged = TCAD.craft._mergeCSGPolygons(byShared[tag], allPoints);
var sorted = sortPaths(merged);
result.push.apply(result, sorted.map(function(path) {
var p = new TCAD.Polygon(path.vertices, path.holes.map(function (path) {
return path.vertices
}), path.normal);
if (path.shared !== undefined) {
p.csgInfo = path.shared.csgInfo;
p.__face = path.shared.face;
}
return p;
})
);
}
TCAD.craft.recoverySketchInfo(result);
return result;
};
TCAD.craft.collectFaces = function(solids) {
var faces = [];
for (var i = 0; i < solids.length; i++) {
TCAD.utils.addAll(faces, solids[i].polyFaces);
}
return faces;
};
TCAD.craft.collectCSGPolygons = function(faces) {
var out = [];
for (var fi = 0; fi < faces.length; fi++) {
var face = faces[fi];
TCAD.utils.addAll(out, face.csgGroup.toCSGPolygons());
}
return out;
};
TCAD.craft.toGroups = function(csgPolygons) {
function vec(p) {
var v = new TCAD.Vector();
v.setV(p);
return v;
}
var byShared = {};
var infos = {};
for (var i = 0; i < csgPolygons.length; i++) {
var p = csgPolygons[i];
var tag = p.shared.getTag();
infos[tag] = p.shared;
if (byShared[tag] === undefined) byShared[tag] = [];
byShared[tag].push(p);
}
var result = [];
for (var tag in byShared) {
var groupedPolygons = byShared[tag];
if (groupedPolygons.length === 0) continue;
var plane = groupedPolygons[0].plane;
var normal = vec(plane.normal);
var simplePolygons = groupedPolygons.map(function (p) {
var vertices = p.vertices.map(function (v) {
return vec(v.pos);
});
return new TCAD.SimplePolygon(vertices, normal);
});
var csgGroup = new TCAD.CSGGroup(simplePolygons, normal, plane.w);
var tcadShared = infos[tag].__tcad;
if (tcadShared !== undefined) {
csgGroup.csgInfo = tcadShared.csgInfo;
csgGroup.__face = tcadShared.face;
}
result.push(csgGroup);
}
return result;
};
TCAD.craft.cut = function(app, request) {
export function cut(app, request) {
var face = request.face;
var sketchedPolygons = TCAD.craft.getSketchedPolygons3D(app, face);
var sketchedPolygons = getSketchedPolygons3D(app, face);
if (sketchedPolygons == null) return null;
var normal = TCAD.utils.vec(face.csgGroup.plane.normal);
var normal = cad_utils.vec(face.csgGroup.plane.normal);
var cutter = [];
for (var i = 0; i < sketchedPolygons.length; i++) {
var extruded = TCAD.geom.extrude(sketchedPolygons[i], normal, request.params.target, request.params.expansionFactor );
var extruded = cad_utils.extrude(sketchedPolygons[i], normal, request.params.target, request.params.expansionFactor );
cutter = cutter.concat(extruded);
}
var cutterCSG = CSG.fromPolygons(TCAD.craft._triangulateCSG(cutter));
var cutterCSG = CSG.fromPolygons(_triangulateCSG(cutter));
face.csgGroup.shared.__tcad.faceId += '$';
var outSolids = [];
for (var si = 0; si < request.solids.length; si++) {
var work = request.solids[si].csg;
var cut = work.subtract(cutterCSG);
var solidMesh = TCAD.utils.createSolid(cut);
var solidMesh = cad_utils.createSolid(cut);
outSolids.push(solidMesh);
}
return outSolids;
};
}
TCAD.Craft = function(app) {
export function Craft(app) {
this.app = app;
this.history = [];
this._historyPointer = 0;
@ -820,9 +608,9 @@ TCAD.Craft = function(app) {
this.app.viewer.render();
}
});
};
}
TCAD.Craft.prototype.loadHistory = function(history) {
Craft.prototype.loadHistory = function(history) {
this.history = history;
this._historyPointer = history.length;
this.reset(history);
@ -831,25 +619,25 @@ TCAD.Craft.prototype.loadHistory = function(history) {
this.app.viewer.render();
};
TCAD.Craft.prototype.reset = function(modifications) {
TCAD.geom.SOLID_COUNTER = 0;
TCAD.utils.SHARED_COUNTER = 0;
Craft.prototype.reset = function(modifications) {
cad_utils.Counters.solid = 0;
cad_utils.Counters.shared = 0;
this.app.findAllSolids().forEach(function(s) {s.vanish()})
for (var i = 0; i < modifications.length; i++) {
var request = TCAD.craft.materialize(this.app.indexEntities(), modifications[i]);
var request = materialize(this.app.indexEntities(), modifications[i]);
this.modifyInternal(request);
}
};
TCAD.Craft.prototype.finishHistoryEditing = function() {
Craft.prototype.finishHistoryEditing = function() {
this.loadHistory(this.history);
};
TCAD.Craft.prototype.current = function() {
Craft.prototype.current = function() {
return this.history[this.history.length - 1];
};
TCAD.craft.detach = function(request) {
function detach(request) {
var detachedConfig = {};
for (var prop in request) {
if (request.hasOwnProperty(prop)) {
@ -863,16 +651,16 @@ TCAD.craft.detach = function(request) {
} else if (prop == 'basis') {
detachedConfig[prop] = value.map(function(v){return [v.x, v.y, v.z]});
} else if (prop == 'params') {
detachedConfig[prop] = TCAD.craft.detach(value);
detachedConfig[prop] = detach(value);
} else {
detachedConfig[prop] = value;
}
}
}
return detachedConfig
};
}
TCAD.craft.materialize = function(index, detachedConfig) {
function materialize(index, detachedConfig) {
var request = {};
function required(value) {
if (value == null || value == undefined) throw "value is required";
@ -884,23 +672,23 @@ TCAD.craft.materialize = function(index, detachedConfig) {
if (prop == 'solids') {
request[prop] = value.map(function(id){return required(index.solids[id])});
} else if (prop == 'target') {
request[prop] = new TCAD.Vector().set3(value);
request[prop] = new Vector().set3(value);
} else if (prop == 'face') {
request[prop] = required(index.faces[value]);
} else if (prop == 'basis') {
request[prop] = value.map(function(v) {return new TCAD.Vector().set3(v)});
request[prop] = value.map(function(v) {return new Vector().set3(v)});
} else if (prop == 'params') {
request[prop] = TCAD.craft.materialize(index, value);
request[prop] = materialize(index, value);
} else {
request[prop] = value;
}
}
}
return request;
};
}
TCAD.Craft.prototype.modifyInternal = function(request) {
var op = TCAD.craft.OPS[request.type];
Craft.prototype.modifyInternal = function(request) {
var op = OPERATIONS[request.type];
if (!op) return;
var newSolids = op(this.app, request);
@ -915,9 +703,9 @@ TCAD.Craft.prototype.modifyInternal = function(request) {
}
};
TCAD.Craft.prototype.modify = function(request, overriding) {
Craft.prototype.modify = function(request, overriding) {
this.modifyInternal(request);
var detachedRequest = TCAD.craft.detach(request);
var detachedRequest = detach(request);
if (!overriding && this._historyPointer != this.history.length) {
this.history.splice(this._historyPointer + 1, 0, null);
}
@ -928,13 +716,13 @@ TCAD.Craft.prototype.modify = function(request, overriding) {
this.app.viewer.render();
};
TCAD.craft.OPS = {
CUT : TCAD.craft.cut,
PAD : TCAD.craft.extrude,
export const OPERATIONS = {
CUT : cut,
PAD : extrude,
PLANE : function(app, request) {
return [TCAD.utils.createPlane(request.params.basis, request.params.depth)];
return [cad_utils.createPlane(request.params.basis, request.params.depth)];
},
BOX : function(app, request) {
return [TCAD.utils.createCSGBox(request.size)];
return [cad_utils.createCSGBox(request.size)];
}
};

5
web/app/index.js Normal file
View file

@ -0,0 +1,5 @@
import App from './3d/modeler-app'
window.onload = function() {
window._TCAD_APP = new App();
};

View file

@ -1,12 +1,25 @@
import {HashTable} from '../utils/hashmap'
/** @constructor */
function Graph(data) {
TCAD.graph = {};
this.connections = function(e) {
return data[e];
};
this.at = function(index) {
return index;
};
TCAD.graph.findAllLoops = function(graph, hashCode, equals) {
this.size = function() {
return data.length;
};
}
Graph.findAllLoops = function(graph, hashCode, equals) {
var loops = [];
var visited = new TCAD.struct.HashTable(hashCode, equals);
var visited = new HashTable(hashCode, equals);
function step(vertex, comesFrom, path) {
var i;
visited.put(vertex, true);
@ -22,21 +35,20 @@ TCAD.graph.findAllLoops = function(graph, hashCode, equals) {
path.push(vertex);
var needClone = false;
VERTEX:
for (i = 0; i < next.length; i++) {
var v = next[i];
if (equals(v, comesFrom)) {
continue;
}
var p = needClone ? path.slice(0) : path;
needClone = true;
step(v, vertex, p);
for (i = 0; i < next.length; i++) {
var v = next[i];
if (equals(v, comesFrom)) {
continue;
}
var p = needClone ? path.slice(0) : path;
needClone = true;
step(v, vertex, p);
}
path.pop();
}
for (var i = 0; i < graph.size(); i++) {
for (i = 0; i < graph.size(); i++) {
var vertex = graph.at(i);
if (visited.get(vertex) !== true) {
step(vertex, -1, []);
@ -70,8 +82,8 @@ TCAD.graph.findAllLoops = function(graph, hashCode, equals) {
return true;
}
var duplicates = 0;
for (var i = 0; i < loops.length; i++) {
var i, duplicates = 0;
for (i = 0; i < loops.length; i++) {
var a = loops[i];
if (a == null) continue;
for (var j = i + 1; j < loops.length; j++) {
@ -87,7 +99,7 @@ TCAD.graph.findAllLoops = function(graph, hashCode, equals) {
}
if (duplicates != 0) {
var filtered = [];
for (var i = 0; i < loops.length; i++) {
for (i = 0; i < loops.length; i++) {
if (loops[i] != null) filtered.push(loops[i]);
}
loops = filtered;
@ -96,23 +108,8 @@ TCAD.graph.findAllLoops = function(graph, hashCode, equals) {
return loops;
};
/** @constructor */
TCAD.graph.Graph = function(data) {
this.connections = function(e) {
return data[e];
};
this.at = function(index) {
return index;
};
this.size = function() {
return data.length;
};
};
TCAD.graph.test = function() {
var test = function() {
var data = [
[],
[2],
@ -126,11 +123,11 @@ TCAD.graph.test = function() {
[2, 4]
];
var graph = new TCAD.graph.Graph(data);
console.log(TCAD.graph.findAllLoops(graph));
var graph = new Graph(data);
console.log(Graph.findAllLoops(graph));
};
TCAD.graph.test0 = function() {
var test0 = function() {
var data = [
[3, 1],
[0, 2, 8],
@ -143,6 +140,8 @@ TCAD.graph.test0 = function() {
[1, 7]
];
var graph = new TCAD.graph.Graph(data);
console.log(TCAD.graph.findAllLoops(graph));
var graph = new Graph(data);
console.log(Graph.findAllLoops(graph));
};
export {Graph}

202
web/app/math/l3space.js Normal file
View file

@ -0,0 +1,202 @@
import Vector from './vector';
var ORIGIN = new Vector(0, 0, 0);
var AXIS = {
X : new Vector(1, 0, 0),
Y : new Vector(0, 1, 0),
Z : new Vector(0, 0, 1)
};
var IDENTITY_BASIS = [AXIS.X, AXIS.Y, AXIS.Z];
/** @constructor */
function Matrix3() {
this.reset();
}
Matrix3.prototype.reset = function() {
this.mxx = 1; this.mxy = 0; this.mxz = 0; this.tx = 0;
this.myx = 0; this.myy = 1; this.myz = 0; this.ty = 0;
this.mzx = 0; this.mzy = 0; this.mzz = 1; this.tz = 0;
return this;
};
Matrix3.prototype.setBasis = function(basis) {
var b = basis;
this.mxx = b[0].x; this.mxy = b[1].x; this.mxz = b[2].x; this.tx = 0;
this.myx = b[0].y; this.myy = b[1].y; this.myz = b[2].y; this.ty = 0;
this.mzx = b[0].z; this.mzy = b[1].z; this.mzz = b[2].z; this.tz = 0;
return this;
};
Matrix3.prototype.set3 = function(
mxx, mxy, mxz,
myx, myy, myz,
mzx, mzy, mzz
) {
this.mxx = mxx; this.mxy = mxy; this.mxz = mxz;
this.myx = myx; this.myy = myy; this.myz = myz;
this.mzx = mzx; this.mzy = mzy; this.mzz = mzz;
return this;
};
Matrix3.prototype.set34 = function(
mxx, mxy, mxz, tx,
myx, myy, myz, ty,
mzx, mzy, mzz, tz
) {
this.mxx = mxx; this.mxy = mxy; this.mxz = mxz; this.tx = tx;
this.myx = myx; this.myy = myy; this.myz = myz; this.ty = ty;
this.mzx = mzx; this.mzy = mzy; this.mzz = mzz; this.tz = tz;
return this;
};
Matrix3.prototype.setMatrix = function(m) {
this.mxx = m.mxx; this.mxy = m.mxy; this.mxz = m.mxz; this.tx = m.tx;
this.myx = m.myx; this.myy = m.myy; this.myz = m.myz; this.ty = m.ty;
this.mzx = m.mzx; this.mzy = m.mzy; this.mzz = m.mzz; this.tz = m.tz;
return this;
};
Matrix3.prototype.invert = function() {
var det =
this.mxx * (this.myy * this.mzz - this.mzy * this.myz) +
this.mxy * (this.myz * this.mzx - this.mzz * this.myx) +
this.mxz * (this.myx * this.mzy - this.mzx * this.myy);
if (det == 0.0) {
return null;
}
var cxx = this.myy * this.mzz - this.myz * this.mzy;
var cyx = - this.myx * this.mzz + this.myz * this.mzx;
var czx = this.myx * this.mzy - this.myy * this.mzx;
var cxt = - this.mxy * (this.myz * this.tz - this.mzz * this.ty)
- this.mxz * (this.ty * this.mzy - this.tz * this.myy)
- this.tx * (this.myy * this.mzz - this.mzy * this.myz);
var cxy = - this.mxy * this.mzz + this.mxz * this.mzy;
var cyy = this.mxx * this.mzz - this.mxz * this.mzx;
var czy = - this.mxx * this.mzy + this.mxy * this.mzx;
var cyt = this.mxx * (this.myz * this.tz - this.mzz * this.ty)
+ this.mxz * (this.ty * this.mzx - this.tz * this.myx)
+ this.tx * (this.myx * this.mzz - this.mzx * this.myz);
var cxz = this.mxy * this.myz - this.mxz * this.myy;
var cyz = - this.mxx * this.myz + this.mxz * this.myx;
var czz = this.mxx * this.myy - this.mxy * this.myx;
var czt = - this.mxx * (this.myy * this.tz - this.mzy * this.ty)
- this.mxy * (this.ty * this.mzx - this.tz * this.myx)
- this.tx * (this.myx * this.mzy - this.mzx * this.myy);
var result = new Matrix3();
result.mxx = cxx / det;
result.mxy = cxy / det;
result.mxz = cxz / det;
result.tx = cxt / det;
result.myx = cyx / det;
result.myy = cyy / det;
result.myz = cyz / det;
result.ty = cyt / det;
result.mzx = czx / det;
result.mzy = czy / det;
result.mzz = czz / det;
result.tz = czt / det;
return result;
};
Matrix3.prototype.combine = function(transform) {
var txx = transform.mxx;
var txy = transform.mxy;
var txz = transform.mxz;
var ttx = transform.tx;
var tyx = transform.myx;
var tyy = transform.myy;
var tyz = transform.myz;
var tty = transform.ty;
var tzx = transform.mzx;
var tzy = transform.mzy;
var tzz = transform.mzz;
var ttz = transform.tz;
var m = new Matrix3();
m.mxx = (this.mxx * txx + this.mxy * tyx + this.mxz * tzx);
m.mxy = (this.mxx * txy + this.mxy * tyy + this.mxz * tzy);
m.mxz = (this.mxx * txz + this.mxy * tyz + this.mxz * tzz);
m.tx = (this.mxx * ttx + this.mxy * tty + this.mxz * ttz + this.tx);
m.myx = (this.myx * txx + this.myy * tyx + this.myz * tzx);
m.myy = (this.myx * txy + this.myy * tyy + this.myz * tzy);
m.myz = (this.myx * txz + this.myy * tyz + this.myz * tzz);
m.ty = (this.myx * ttx + this.myy * tty + this.myz * ttz + this.ty);
m.mzx = (this.mzx * txx + this.mzy * tyx + this.mzz * tzx);
m.mzy = (this.mzx * txy + this.mzy * tyy + this.mzz * tzy);
m.mzz = (this.mzx * txz + this.mzy * tyz + this.mzz * tzz);
m.tz = (this.mzx * ttx + this.mzy * tty + this.mzz * ttz + this.tz);
return m;
};
Matrix3.prototype.apply = function(vector) {
return this.__apply(vector, new Vector())
};
Matrix3.prototype._apply = function(vector) {
return this.__apply(vector, vector);
};
Matrix3.prototype.__apply = function(vector, out) {
var x = vector.x;
var y = vector.y;
var z = vector.z;
return out.set(
this.mxx * x + this.mxy * y + this.mxz * z + this.tx,
this.myx * x + this.myy * y + this.myz * z + this.ty,
this.mzx * x + this.mzy * y + this.mzz * z + this.tz);
};
Matrix3.rotateMatrix = function(angle, axis, pivot) {
var sin = Math.sin(angle);
var cos = Math.cos(angle);
var axisX, axisY, axisZ;
var m = new Matrix3();
if (axis === AXIS.X || axis === AXIS.Y || axis === AXIS.Z) {
axisX = axis.x;
axisY = axis.y;
axisZ = axis.z;
} else {
// normalize
var mag = axis.length();
if (mag == 0.0) {
return m;
} else {
axisX = axis.x / mag;
axisY = axis.y / mag;
axisZ = axis.z / mag;
}
}
var px = pivot.x;
var py = pivot.y;
var pz = pivot.z;
m.mxx = cos + axisX * axisX * (1 - cos);
m.mxy = axisX * axisY * (1 - cos) - axisZ * sin;
m.mxz = axisX * axisZ * (1 - cos) + axisY * sin;
m.tx = px * (1 - m.mxx) - py * m.mxy - pz * m.mxz;
m.myx = axisY * axisX * (1 - cos) + axisZ * sin;
m.myy = cos + axisY * axisY * (1 - cos);
m.myz = axisY * axisZ * (1 - cos) - axisX * sin;
m.ty = py * (1 - m.myy) - px * m.myx - pz * m.myz;
m.mzx = axisZ * axisX * (1 - cos) - axisY * sin;
m.mzy = axisZ * axisY * (1 - cos) + axisX * sin;
m.mzz = cos + axisZ * axisZ * (1 - cos);
m.tz = pz * (1 - m.mzz) - px * m.mzx - py * m.mzy;
return m;
};
export {Matrix3, ORIGIN, IDENTITY_BASIS, AXIS};

View file

@ -76,7 +76,7 @@
* @version $Id: LevenbergMarquardtOptimizer.java 1416643 2012-12-03 19:37:14Z tn $
* @constructor
*/
function LMOptimizer(startPoint, target, model, jacobian) {
export default function LMOptimizer(startPoint, target, model, jacobian) {
this.startPoint = startPoint;

View file

@ -1,121 +1,89 @@
TCAD.math = {};
import Vector from './vector'
TCAD.math._arr = function(size) {
var out = [];
out.length = size;
for (var i = 0; i < size; ++i) {
out[i] = 0;
}
return out;
};
export const TOLERANCE = 1E-6;
TCAD.math._matrix = function(m, n) {
var out = [];
out.length = m;
for (var i = 0; i < m; ++i) {
out[i] = TCAD.math._arr(n);
}
return out;
};
export function distanceAB(a, b) {
return distance(a.x, a.y, b.x, b.y);
}
TCAD.math.distanceAB = function(a, b) {
return TCAD.math.distance(a.x, a.y, b.x, b.y);
};
TCAD.math.distance = function(x1, y1, x2, y2) {
export function distance(x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
};
}
TCAD.math.distanceAB3 = function(a, b) {
return TCAD.math.distance3(a.x, a.y, a.z, b.x, b.y, b.z);
};
export function distanceAB3(a, b) {
return distance3(a.x, a.y, a.z, b.x, b.y, b.z);
}
TCAD.math.distance3 = function(x1, y1, z1, x2, y2, z2) {
export function distance3(x1, y1, z1, x2, y2, z2) {
var dx = x1 - x2;
var dy = y1 - y2;
var dz = z1 - z2;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
};
}
TCAD.math.ORIGIN = new TCAD.Vector(0, 0, 0);
TCAD.math.AXIS = {
X : new TCAD.Vector(1, 0, 0),
Y : new TCAD.Vector(0, 1, 0),
Z : new TCAD.Vector(0, 0, 1)
};
TCAD.math.IDENTITY_BASIS = [TCAD.math.AXIS.X, TCAD.math.AXIS.Y, TCAD.math.AXIS.Z];
TCAD.math.rotateMatrix = function(angle, axis, pivot) {
var sin = Math.sin(angle);
var cos = Math.cos(angle);
var axisX, axisY, axisZ;
var m = new TCAD.Matrix();
var AXIS = TCAD.math.AXIS;
if (axis === AXIS.X || axis === AXIS.Y || axis === AXIS.Z) {
axisX = axis.x;
axisY = axis.y;
axisZ = axis.z;
} else {
// normalize
var mag = axis.length();
if (mag == 0.0) {
return m;
} else {
axisX = axis.x / mag;
axisY = axis.y / mag;
axisZ = axis.z / mag;
}
}
var px = pivot.x;
var py = pivot.y;
var pz = pivot.z;
m.mxx = cos + axisX * axisX * (1 - cos);
m.mxy = axisX * axisY * (1 - cos) - axisZ * sin;
m.mxz = axisX * axisZ * (1 - cos) + axisY * sin;
m.tx = px * (1 - m.mxx) - py * m.mxy - pz * m.mxz;
m.myx = axisY * axisX * (1 - cos) + axisZ * sin;
m.myy = cos + axisY * axisY * (1 - cos);
m.myz = axisY * axisZ * (1 - cos) - axisX * sin;
m.ty = py * (1 - m.myy) - px * m.myx - pz * m.myz;
m.mzx = axisZ * axisX * (1 - cos) - axisY * sin;
m.mzy = axisZ * axisY * (1 - cos) + axisX * sin;
m.mzz = cos + axisZ * axisZ * (1 - cos);
m.tz = pz * (1 - m.mzz) - px * m.mzx - py * m.mzy;
return m;
};
TCAD.math.circleFromPoints = function(p1, p2, p3) {
var center = new TCAD.Vector();
export function circleFromPoints(p1, p2, p3) {
var center = new Vector();
var offset = p2.x*p2.x + p2.y*p2.y;
var bc = ( p1.x*p1.x + p1.y*p1.y - offset )/2.0;
var cd = (offset - p3.x*p3.x - p3.y*p3.y)/2.0;
var det = (p1.x - p2.x) * (p2.y - p3.y) - (p2.x - p3.x)* (p1.y - p2.y);
if (Math.abs(det) < TCAD.TOLERANCE) { return null; }
if (Math.abs(det) < TOLERANCE) { return null; }
var idet = 1/det;
center.x = (bc * (p2.y - p3.y) - cd * (p1.y - p2.y)) * idet;
center.y = (cd * (p1.x - p2.x) - bc * (p2.x - p3.x)) * idet;
return center;
};
}
TCAD.math.norm2 = function(vec) {
export function norm2(vec) {
var sq = 0;
for (var i = 0; i < vec.length; i++) {
sq += vec[i] * vec[i];
}
return Math.sqrt(sq);
};
}
export function areEqual(v1, v2, tolerance) {
return Math.abs(v1 - v2) < tolerance;
}
export function areVectorsEqual(v1, v2, tolerance) {
return areEqual(v1.x, v2.x, tolerance) &&
areEqual(v1.y, v2.y, tolerance) &&
areEqual(v1.z, v2.z, tolerance);
}
export function vectorsEqual(v1, v2) {
return areVectorsEqual(v1, v2, TOLERANCE);
}
export function equal(v1, v2) {
return areEqual(v1, v2, TOLERANCE);
}
export function strictEqual(a, b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
export function _vec(size) {
var out = [];
out.length = size;
for (var i = 0; i < size; ++i) {
out[i] = 0;
}
return out;
}
export function _matrix(m, n) {
var out = [];
out.length = m;
for (var i = 0; i < m; ++i) {
out[i] = _vec(n);
}
return out;
}

View file

@ -1,15 +1,19 @@
import * as math from 'math'
/** @constructor */
TCAD.math.Matrix = function(r, c) {
/**
* @constructor
* @deprecated use numeric library
* */
export function Matrix(r, c) {
this.data = [];
this.rSize = r;
this.cSize = c;
for (var i = 0; i < r; i++) {
this.data[i] = TCAD.math._arr(c)
this.data[i] = math._vec(c)
}
};
}
TCAD.math.Matrix.prototype.identity = function() {
Matrix.prototype.identity = function() {
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
@ -18,8 +22,8 @@ TCAD.math.Matrix.prototype.identity = function() {
}
};
TCAD.math.Matrix.prototype.subtract = function(m) {
var out = new TCAD.math.Matrix(this.rSize, this.cSize);
Matrix.prototype.subtract = function(m) {
var out = new Matrix(this.rSize, this.cSize);
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
out.data[i][j] = this.data[i][j] - m.data[i][j];
@ -28,8 +32,8 @@ TCAD.math.Matrix.prototype.subtract = function(m) {
return out;
};
TCAD.math.Matrix.prototype.add = function(m) {
var out = new TCAD.math.Matrix(this.rSize, this.cSize);
Matrix.prototype.add = function(m) {
var out = new Matrix(this.rSize, this.cSize);
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
out.data[i][j] = this.data[i][j] + m.data[i][j];
@ -38,16 +42,16 @@ TCAD.math.Matrix.prototype.add = function(m) {
return out;
};
TCAD.math.Matrix.prototype.multiply = function(m) {
Matrix.prototype.multiply = function(m) {
var nRows = this.rSize;
var nCols = m.cSize;
var nSum = this.cSize;
var out = new TCAD.math.Matrix(nRows, nCols);
var out = new Matrix(nRows, nCols);
var outData = out.data;
var mCol = TCAD.math._arr(nSum);
var mCol = math._vec(nSum);
var mData = m.data;
for (var col = 0; col < nCols; col++) {
@ -68,8 +72,8 @@ TCAD.math.Matrix.prototype.multiply = function(m) {
return out;
};
TCAD.math.Matrix.prototype.scalarMultiply = function(s) {
var out = new TCAD.math.Matrix(this.rSize, this.cSize);
Matrix.prototype.scalarMultiply = function(s) {
var out = new Matrix(this.rSize, this.cSize);
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
out.data[i][j] = this.data[i][j] * s;
@ -78,8 +82,8 @@ TCAD.math.Matrix.prototype.scalarMultiply = function(s) {
return out;
};
TCAD.math.Matrix.prototype.transpose = function() {
var out = new TCAD.math.Matrix(this.cSize, this.rSize);
Matrix.prototype.transpose = function() {
var out = new Matrix(this.cSize, this.rSize);
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
out.data[j][i] = this.data[i][j];
@ -88,8 +92,8 @@ TCAD.math.Matrix.prototype.transpose = function() {
return out;
};
TCAD.math.Matrix.prototype.copy = function() {
var out = new TCAD.math.Matrix(this.rSize, this.cSize);
Matrix.prototype.copy = function() {
var out = new Matrix(this.rSize, this.cSize);
for (var i = 0; i < this.rSize; i++) {
for (var j = 0; j < this.cSize; j++) {
out.data[i][j] = this.data[i][j];
@ -98,7 +102,7 @@ TCAD.math.Matrix.prototype.copy = function() {
return out;
};
TCAD.math.Matrix.prototype.dot = function(v) {
Matrix.prototype.dot = function(v) {
var vData = v.data;
var dot = 0;
for (var i = 0; i < this.rSize; i++) {
@ -107,7 +111,7 @@ TCAD.math.Matrix.prototype.dot = function(v) {
return dot;
};
TCAD.math.Matrix.prototype.norm = function(v) {
Matrix.prototype.norm = function(v) {
var sum = 0;
for (var i = 0; i < this.rSize; i++) {
var a = this.data[i][0];
@ -115,11 +119,3 @@ TCAD.math.Matrix.prototype.norm = function(v) {
}
return Math.sqrt(sum);
};
/** @constructor */
TCAD.math.Vector = function(n) {
TCAD.math.Matrix.call(this, n, 1);
};
TCAD.TWO.utils.extend(TCAD.math.Vector, TCAD.math.Matrix);

View file

@ -1,9 +1,8 @@
optim = {};
optim.DEBUG_HANDLER = function() {};
import numeric from 'numeric';
import {_vec, _matrix} from './math'
//Added strong wolfe condition to numeric's uncmin
optim.bfgs_ = function(f,x0,tol,gradient,maxit,callback,options) {
var bfgs_ = function(f,x0,tol,gradient,maxit,callback,options) {
var grad = numeric.gradient;
if(typeof options === "undefined") { options = {}; }
if(typeof tol === "undefined") { tol = 1e-8; }
@ -44,7 +43,6 @@ optim.bfgs_ = function(f,x0,tol,gradient,maxit,callback,options) {
tR = t;
t = (tL + tR) * 0.5;
++it;
continue;
} else {
var slope = dot(gradient(x1), step);
if (slope <= 0.9 * Math.abs(df0)){
@ -52,14 +50,11 @@ optim.bfgs_ = function(f,x0,tol,gradient,maxit,callback,options) {
}else if ( slope >= 0.9 * df0) {
tR = t;
t = (tL+ tR) * 0.5;
continue;
}else{
tL = t;
t = (tL+ tR)*0.5;
continue;
}
}
break;
}
if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; }
if(it === maxit) { msg = "maxit reached during line search"; break; }
@ -83,7 +78,7 @@ optim.bfgs_ = function(f,x0,tol,gradient,maxit,callback,options) {
};
optim.bfgs = function(f,x0,tol,gradient,maxit,callback,options) {
var bfgs = function(f,x0,tol,gradient,maxit,callback,options) {
var grad = numeric.gradient;
if(typeof options === "undefined") { options = {}; }
if(typeof tol === "undefined") { tol = 1e-8; }
@ -119,7 +114,7 @@ optim.bfgs = function(f,x0,tol,gradient,maxit,callback,options) {
x1 = add(x0,s);
var f2 = f(x1);
t3 = 2.0;
var t3 = 2.0;
s = mul(step,t3);
x1 = add(x0,s);
var f3 = f(x1);
@ -194,7 +189,7 @@ optim.bfgs = function(f,x0,tol,gradient,maxit,callback,options) {
return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg};
};
optim.bfgs_updater = function(gradient, x0) {
var bfgs_updater = function(gradient, x0) {
var n = x0.length;
var max = Math.max, norm2 = numeric.norm2;
var g0,g1,H1 = numeric.identity(n);
@ -202,7 +197,7 @@ optim.bfgs_updater = function(gradient, x0) {
var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg;
var y,Hy,Hs,ys;
var msg = "";
var g0 = gradient(x0);
g0 = gradient(x0);
function step() {
return neg(dot(H1,g0));
@ -227,9 +222,10 @@ optim.bfgs_updater = function(gradient, x0) {
return {step:step, update:update};
};
optim.inv = function inv(x) {
var s = numeric.dim(x), abs = Math.abs, m = s[0], n = s[1];
var A = numeric.clone(x), Ai, Aj;
var inv = function inv(A) {
A = numeric.clone(A);
var s = numeric.dim(A), abs = Math.abs, m = s[0], n = s[1];
var Ai, Aj;
var I = numeric.identity(m), Ii, Ij;
var i,j,k,x;
for(j=0;j<n;++j) {
@ -259,13 +255,13 @@ optim.inv = function inv(x) {
return I;
};
optim._result = function(evalCount, error, returnCode) {
var _result = function(evalCount, error, returnCode) {
this.evalCount = evalCount;
this.error = error;
this.returnCode = returnCode;
};
optim.dog_leg = function (subsys, rough) {
var dog_leg = function (subsys, rough) {
//rough = true
//var tolg = rough ? 1e-3 : 1e-4;
var tolg, tolf;
@ -283,11 +279,11 @@ optim.dog_leg = function (subsys, rough) {
var csize = subsys.constraints.length;
if (xsize == 0) {
return new optim._result(0, 0, 1);
return new _result(0, 0, 1);
}
var vec = TCAD.math._arr;
var mx = TCAD.math._matrix;
var vec = _vec;
var mx = _matrix;
var n = numeric;
@ -315,7 +311,7 @@ optim.dog_leg = function (subsys, rough) {
function lsolve_slow(A, b) {
var At = n.transpose(A);
var res = n.dot(n.dot(At, optim.inv(n.dot(A, At))), b);
var res = n.dot(n.dot(At, inv(n.dot(A, At))), b);
return res;
}
@ -366,7 +362,7 @@ optim.dog_leg = function (subsys, rough) {
// h_gn = lusolve(Jx, n.mul(fx, -1));
//Conjugate gradient method
//h_gn = optim.cg(Jx, h_gn, n.mul(fx, -1), 1e-8, iterLimit);
//h_gn = cg(Jx, h_gn, n.mul(fx, -1), 1e-8, iterLimit);
//solve linear problem using svd formula to get the gauss-newton step
//h_gn = lls(Jx, n.mul(fx, -1));
@ -473,19 +469,18 @@ optim.dog_leg = function (subsys, rough) {
}
//log.push(returnCode);
//window.___log(log);
return new optim._result(iter, err, returnCode);
return new _result(iter, err, returnCode);
};
optim.cg = function(A, x, b, tol, maxIt) {
var cg = function(A, x, b, tol, maxIt) {
var _ = numeric;
var tr = _.transpose;
var At = tr(A);
if (A.length != A[0].length) {
var A = _.dot(At, A);
var b = _.dot(At, b);
At = tr(A);
A = _.dot(At, A);
b = _.dot(At, b);
}
var r = _.sub(_.dot(A, x), b);
@ -509,4 +504,8 @@ optim.cg = function(A, x, b, tol, maxIt) {
}
// console.log("liner problem solved in " + i);
return x;
};
};
var optim = {DEBUG_HANDLER : function() {}}; //backward compatibility
export {dog_leg, optim}

View file

@ -1,22 +1,9 @@
TCAD.math.vec = function(size) {
var out = [];
out.length = size;
for (var i = 0; i < size; ++i) {
out[i] = 0;
}
return out;
};
TCAD.math.Arrays_fill = function(a, fromIndex, toIndex,val) {
for (var i = fromIndex; i < toIndex; i++)
a[i] = val;
};
import {fillArray} from '../utils/utils'
import * as math from './math'
/** @constructor */
TCAD.math.QR = function(matrix) {
var vec = TCAD.math.vec;
function QR(matrix) {
var vec = math._vec;
this.matrix = matrix;
var nR = this.matrix.length;
var nC = nR == 0 ? 0 : this.matrix[0].length;
@ -97,9 +84,9 @@ TCAD.math.QR = function(matrix) {
}
}
this.rank = this.solvedCols;
};
}
TCAD.math.QR.prototype.qTy = function(y) {
QR.prototype.qTy = function(y) {
var nR = this.matrix.length;
var nC = this.matrix[0].length;
@ -116,12 +103,12 @@ TCAD.math.QR.prototype.qTy = function(y) {
}
};
TCAD.math.QR.prototype.solve = function(qy) {
QR.prototype.solve = function(qy) {
var nR = this.matrix.length;
var nC = this.matrix[0].length;
var vec = TCAD.math.vec;
var vec = math._vec;
var diag = vec(nC);
var lmDiag = vec(nC);
@ -147,7 +134,7 @@ TCAD.math.QR.prototype.solve = function(qy) {
var pj = this.permutation[j];
var dpj = diag[pj];
if (dpj != 0) {
TCAD.math.Arrays_fill(lmDiag, j + 1, lmDiag.length, 0);
fillArray(lmDiag, j + 1, lmDiag.length, 0);
}
lmDiag[j] = dpj;
@ -225,4 +212,6 @@ TCAD.math.QR.prototype.solve = function(qy) {
out[this.permutation[j]] = work[j];
}
return out;
};
};
export default QR

View file

@ -1,91 +1,92 @@
import {vectorsEqual} from './math'
/** @constructor */
TCAD.Vector = function(x, y, z) {
function Vector(x, y, z) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
}
TCAD.Vector.prototype.set = function(x, y, z) {
Vector.prototype.set = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
};
TCAD.Vector.prototype.set3 = function(data) {
Vector.prototype.set3 = function(data) {
this.x = data[0];
this.y = data[1];
this.z = data[2];
return this;
};
TCAD.Vector.prototype.setV = function(data) {
Vector.prototype.setV = function(data) {
this.x = data.x;
this.y = data.y;
this.z = data.z;
return this;
};
TCAD.Vector.prototype.multiply = function(scalar) {
return new TCAD.Vector(this.x * scalar, this.y * scalar, this.z * scalar);
Vector.prototype.multiply = function(scalar) {
return new Vector(this.x * scalar, this.y * scalar, this.z * scalar);
};
TCAD.Vector.prototype._multiply = function(scalar) {
Vector.prototype._multiply = function(scalar) {
return this.set(this.x * scalar, this.y * scalar, this.z * scalar);
};
TCAD.Vector.prototype.dot = function(vector) {
Vector.prototype.dot = function(vector) {
return this.x * vector.x + this.y * vector.y + this.z * vector.z;
};
TCAD.Vector.prototype.copy = function() {
return new TCAD.Vector(this.x, this.y, this.z);
Vector.prototype.copy = function() {
return new Vector(this.x, this.y, this.z);
};
TCAD.Vector.prototype.length = function() {
Vector.prototype.length = function() {
return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
};
TCAD.Vector.prototype.minus = function(vector) {
return new TCAD.Vector(this.x - vector.x, this.y - vector.y, this.z - vector.z);
Vector.prototype.minus = function(vector) {
return new Vector(this.x - vector.x, this.y - vector.y, this.z - vector.z);
};
TCAD.Vector.prototype._minus = function(vector) {
Vector.prototype._minus = function(vector) {
this.x -= vector.x;
this.y -= vector.y;
this.z -= vector.z;
return this;
};
TCAD.Vector.prototype._minusXYZ = function(x, y, z) {
Vector.prototype._minusXYZ = function(x, y, z) {
this.x -= x;
this.y -= y;
this.z -= z;
return this;
};
TCAD.Vector.prototype.plus = function(vector) {
return new TCAD.Vector(this.x + vector.x, this.y + vector.y, this.z + vector.z);
Vector.prototype.plus = function(vector) {
return new Vector(this.x + vector.x, this.y + vector.y, this.z + vector.z);
};
TCAD.Vector.prototype._plus = function(vector) {
Vector.prototype._plus = function(vector) {
this.x += vector.x;
this.y += vector.y;
this.z += vector.z;
return this;
};
TCAD.Vector.prototype.normalize = function() {
Vector.prototype.normalize = function() {
var mag = this.length();
if (mag == 0.0) {
return new TCAD.Vector(0.0, 0.0, 0.0);
return new Vector(0.0, 0.0, 0.0);
}
return new TCAD.Vector(this.x / mag, this.y / mag, this.z / mag);
return new Vector(this.x / mag, this.y / mag, this.z / mag);
};
TCAD.Vector.prototype._normalize = function() {
Vector.prototype._normalize = function() {
var mag = this.length();
if (mag == 0.0) {
return this.set(0, 0, 0)
@ -93,174 +94,32 @@ TCAD.Vector.prototype._normalize = function() {
return this.set(this.x / mag, this.y / mag, this.z / mag)
};
TCAD.Vector.prototype.cross = function(a) {
return new TCAD.Vector(
Vector.prototype.cross = function(a) {
return new Vector(
this.y * a.z - this.z * a.y,
this.z * a.x - this.x * a.z,
this.x * a.y - this.y * a.x
);
};
TCAD.Vector.prototype.negate = function() {
Vector.prototype.negate = function() {
return this.multiply(-1);
};
TCAD.Vector.prototype._negate = function() {
Vector.prototype._negate = function() {
return this._multiply(-1);
};
TCAD.Vector.prototype.equals = function(vector) {
return TCAD.utils.vectorsEqual(this, vector);
Vector.prototype.equals = function(vector) {
return vectorsEqual(this, vector);
};
TCAD.Vector.prototype.three = function() {
Vector.prototype.three = function() {
return new THREE.Vector3(this.x, this.y, this.z);
};
TCAD.Vector.prototype.csg = function() {
Vector.prototype.csg = function() {
return new CSG.Vector3D(this.x, this.y, this.z);
};
/** @constructor */
TCAD.Matrix = function() {
this.reset();
};
TCAD.Matrix.prototype.reset = function() {
this.mxx = 1; this.mxy = 0; this.mxz = 0; this.tx = 0;
this.myx = 0; this.myy = 1; this.myz = 0; this.ty = 0;
this.mzx = 0; this.mzy = 0; this.mzz = 1; this.tz = 0;
return this;
};
TCAD.Matrix.prototype.setBasis = function(basis) {
var b = basis;
this.mxx = b[0].x; this.mxy = b[1].x; this.mxz = b[2].x; this.tx = 0;
this.myx = b[0].y; this.myy = b[1].y; this.myz = b[2].y; this.ty = 0;
this.mzx = b[0].z; this.mzy = b[1].z; this.mzz = b[2].z; this.tz = 0;
return this;
};
TCAD.Matrix.prototype.set3 = function(
mxx, mxy, mxz,
myx, myy, myz,
mzx, mzy, mzz
) {
this.mxx = mxx; this.mxy = mxy; this.mxz = mxz;
this.myx = myx; this.myy = myy; this.myz = myz;
this.mzx = mzx; this.mzy = mzy; this.mzz = mzz;
return this;
};
TCAD.Matrix.prototype.set34 = function(
mxx, mxy, mxz, tx,
myx, myy, myz, ty,
mzx, mzy, mzz, tz
) {
this.mxx = mxx; this.mxy = mxy; this.mxz = mxz; this.tx = tx;
this.myx = myx; this.myy = myy; this.myz = myz; this.ty = ty;
this.mzx = mzx; this.mzy = mzy; this.mzz = mzz; this.tz = tz;
return this;
};
TCAD.Matrix.prototype.setMatrix = function(m) {
this.mxx = m.mxx; this.mxy = m.mxy; this.mxz = m.mxz; this.tx = m.tx;
this.myx = m.myx; this.myy = m.myy; this.myz = m.myz; this.ty = m.ty;
this.mzx = m.mzx; this.mzy = m.mzy; this.mzz = m.mzz; this.tz = m.tz;
return this;
};
TCAD.Matrix.prototype.invert = function() {
var det =
this.mxx * (this.myy * this.mzz - this.mzy * this.myz) +
this.mxy * (this.myz * this.mzx - this.mzz * this.myx) +
this.mxz * (this.myx * this.mzy - this.mzx * this.myy);
if (det == 0.0) {
return null;
}
var cxx = this.myy * this.mzz - this.myz * this.mzy;
var cyx = - this.myx * this.mzz + this.myz * this.mzx;
var czx = this.myx * this.mzy - this.myy * this.mzx;
var cxt = - this.mxy * (this.myz * this.tz - this.mzz * this.ty)
- this.mxz * (this.ty * this.mzy - this.tz * this.myy)
- this.tx * (this.myy * this.mzz - this.mzy * this.myz);
var cxy = - this.mxy * this.mzz + this.mxz * this.mzy;
var cyy = this.mxx * this.mzz - this.mxz * this.mzx;
var czy = - this.mxx * this.mzy + this.mxy * this.mzx;
var cyt = this.mxx * (this.myz * this.tz - this.mzz * this.ty)
+ this.mxz * (this.ty * this.mzx - this.tz * this.myx)
+ this.tx * (this.myx * this.mzz - this.mzx * this.myz);
var cxz = this.mxy * this.myz - this.mxz * this.myy;
var cyz = - this.mxx * this.myz + this.mxz * this.myx;
var czz = this.mxx * this.myy - this.mxy * this.myx;
var czt = - this.mxx * (this.myy * this.tz - this.mzy * this.ty)
- this.mxy * (this.ty * this.mzx - this.tz * this.myx)
- this.tx * (this.myx * this.mzy - this.mzx * this.myy);
var result = new TCAD.Matrix();
result.mxx = cxx / det;
result.mxy = cxy / det;
result.mxz = cxz / det;
result.tx = cxt / det;
result.myx = cyx / det;
result.myy = cyy / det;
result.myz = cyz / det;
result.ty = cyt / det;
result.mzx = czx / det;
result.mzy = czy / det;
result.mzz = czz / det;
result.tz = czt / det;
return result;
};
TCAD.Matrix.prototype.combine = function(transform) {
var txx = transform.mxx;
var txy = transform.mxy;
var txz = transform.mxz;
var ttx = transform.tx;
var tyx = transform.myx;
var tyy = transform.myy;
var tyz = transform.myz;
var tty = transform.ty;
var tzx = transform.mzx;
var tzy = transform.mzy;
var tzz = transform.mzz;
var ttz = transform.tz;
var m = new TCAD.Matrix();
m.mxx = (this.mxx * txx + this.mxy * tyx + this.mxz * tzx);
m.mxy = (this.mxx * txy + this.mxy * tyy + this.mxz * tzy);
m.mxz = (this.mxx * txz + this.mxy * tyz + this.mxz * tzz);
m.tx = (this.mxx * ttx + this.mxy * tty + this.mxz * ttz + this.tx);
m.myx = (this.myx * txx + this.myy * tyx + this.myz * tzx);
m.myy = (this.myx * txy + this.myy * tyy + this.myz * tzy);
m.myz = (this.myx * txz + this.myy * tyz + this.myz * tzz);
m.ty = (this.myx * ttx + this.myy * tty + this.myz * ttz + this.ty);
m.mzx = (this.mzx * txx + this.mzy * tyx + this.mzz * tzx);
m.mzy = (this.mzx * txy + this.mzy * tyy + this.mzz * tzy);
m.mzz = (this.mzx * txz + this.mzy * tyz + this.mzz * tzz);
m.tz = (this.mzx * ttx + this.mzy * tty + this.mzz * ttz + this.tz);
return m;
};
TCAD.Matrix.prototype.apply = function(vector) {
return this.__apply(vector, new TCAD.Vector())
};
TCAD.Matrix.prototype._apply = function(vector) {
return this.__apply(vector, vector);
};
TCAD.Matrix.prototype.__apply = function(vector, out) {
var x = vector.x;
var y = vector.y;
var z = vector.z;
return out.set(
this.mxx * x + this.mxy * y + this.mxz * z + this.tx,
this.myx * x + this.myy * y + this.myz * z + this.ty,
this.mzx * x + this.mzy * y + this.mzz * z + this.tz);
};
export default Vector;

View file

@ -1,7 +1,15 @@
function start() {
var app = new TCAD.App2D();
import App2D from './sketcher/sketcher-app';
import {Layer, Styles} from './sketcher/viewer2d';
import $ from '../lib/jquery-2.1.0.min'
import * as ui from './ui/ui.js';
import * as toolkit from './ui/toolkit';
import {askNumber} from './utils/utils';
import {Constraints} from './sketcher/parametric'
function initializeSketcherApplication() {
var app = new App2D();
var sketchId = app.getSketchId();
if (sketchId == TCAD.STORAGE_PREFIX + '__sample2D__') {
if (sketchId == App2D.STORAGE_PREFIX + '__sample2D__') {
var sample = '{"layers":[{"name":"_dim","style":{"lineWidth":1,"strokeStyle":"#bcffc1","fillStyle":"#00FF00"},"data":[{"id":0,"_class":"TCAD.TWO.DiameterDimension","obj":90},{"id":1,"_class":"TCAD.TWO.DiameterDimension","obj":95},{"id":2,"_class":"TCAD.TWO.DiameterDimension","obj":42},{"id":3,"_class":"TCAD.TWO.Dimension","a":5,"b":8,"flip":false},{"id":4,"_class":"TCAD.TWO.DiameterDimension","obj":105}]},{"name":"sketch","style":{"lineWidth":2,"strokeStyle":"#ffffff","fillStyle":"#000000"},"data":[{"id":11,"_class":"TCAD.TWO.Segment","points":[[5,[6,110.1295615870824],[7,313.66509156975803]],[8,[9,419.44198895058975],[10,516.7065215258621]]]},{"id":18,"_class":"TCAD.TWO.Segment","points":[[12,[13,489.1218947877601],[14,477.98601743930897]],[15,[16,481.90945628911174],[17,182.9391540301952]]]},{"id":25,"_class":"TCAD.TWO.Segment","points":[[19,[20,427.6872468325118],[21,163.96220645927505]],[22,[23,349.9023145352797],[24,256.7344291384989]]]},{"id":32,"_class":"TCAD.TWO.Segment","points":[[26,[27,306.81261277555075],[28,273.1404656521002]],[29,[30,135.09050734792822],[31,247.98348666778958]]]},{"id":42,"_class":"TCAD.TWO.Arc","points":[[33,[34,489.1218947877601],[35,477.98601743930897]],[36,[37,419.44198895058975],[38,516.7065215258621]],[39,[40,444.1353623657045],[41,479.08688157090376]]]},{"id":53,"_class":"TCAD.TWO.Arc","points":[[44,[45,427.6872468325118],[46,163.96220645927505]],[47,[48,481.90945628911174],[49,182.9391540301952]],[50,[51,451.2148840882273],[52,183.68960424767275]]]},{"id":64,"_class":"TCAD.TWO.Arc","points":[[55,[56,349.9023145352797],[57,256.7344291384989]],[58,[59,306.81261277555075],[60,273.1404656521002]],[61,[62,313.6665992835383],[63,226.35256652594512]]]},{"id":75,"_class":"TCAD.TWO.Arc","points":[[66,[67,110.1295615870824],[68,313.66509156975803]],[69,[70,135.09050734792822],[71,247.98348666778958]],[72,[73,129.8749213918784],[74,283.58516027516237]]]},{"id":80,"_class":"TCAD.TWO.Circle","c":[77,[78,444.1353623657045],[79,479.08688157090376]],"r":17},{"id":85,"_class":"TCAD.TWO.Circle","c":[82,[83,451.2148840882273],[84,183.68960424767275]],"r":17},{"id":90,"_class":"TCAD.TWO.Circle","c":[87,[88,129.8749213918784],[89,283.58516027516237]],"r":17},{"id":95,"_class":"TCAD.TWO.Circle","c":[92,[93,364.7627927122075],[94,358.27520724354514]],"r":50},{"id":100,"_class":"TCAD.TWO.Circle","c":[97,[98,450.6425914465028],[99,356.1758703461729]],"r":13},{"id":105,"_class":"TCAD.TWO.Circle","c":[102,[103,281.1241663120215],[104,360.3197585470608]],"r":13}]},{"name":"_construction_","style":{"lineWidth":1,"strokeStyle":"#aaaaaa","fillStyle":"#000000"},"data":[{"id":113,"_class":"TCAD.TWO.Segment","points":[[107,[108,366.96497096679207],[109,448.36204633886825]],[110,[111,362.6842565514955],[112,273.2463262825022]]]},{"id":120,"_class":"TCAD.TWO.Segment","points":[[114,[115,254.60331148100178],[116,360.9680624545806]],[117,[118,474.9222739434132],[119,355.5823520325097]]]}]}],"constraints":[["Tangent",[42,18]],["Tangent",[42,11]],["coi",[33,12]],["coi",[36,8]],["Tangent",[53,25]],["Tangent",[53,18]],["coi",[44,19]],["coi",[47,15]],["Tangent",[64,25]],["Tangent",[64,32]],["coi",[55,22]],["coi",[58,26]],["Tangent",[75,11]],["Tangent",[75,32]],["coi",[66,5]],["coi",[69,29]],["coi",[77,39]],["coi",[82,50]],["coi",[87,72]],["RR",[80,85]],["RR",[85,90]],["parallel",[113,18]],["perpendicular",[120,113]],["Symmetry",[92,120]],["PointOnLine",[92,113]],["PointOnLine",[102,120]],["PointOnLine",[97,120]],["RR",[105,100]]]}';
localStorage.setItem(sketchId, sample);
}
@ -10,17 +18,17 @@ function start() {
function addLayer(name, style) {
if (app.viewer.findLayerByName(name) === null) {
app.viewer.layers.push(new TCAD.TWO.Layer(name, style));
app.viewer.layers.push(new Layer(name, style));
}
}
addLayer("sketch", TCAD.TWO.Styles.DEFAULT);
addLayer("_construction_", TCAD.TWO.Styles.CONSTRUCTION);
var actionsWin = new TCAD.ui.Window($('#actions'), app.winManager);
addLayer("sketch", Styles.DEFAULT);
addLayer("_construction_", Styles.CONSTRUCTION);
TCAD.ui.bindOpening( $('#showActions'), actionsWin );
var addAction = TCAD.ui.createActionsWinBuilder(actionsWin);
var actionsWin = new ui.Window($('#actions'), app.winManager);
ui.bindOpening( $('#showActions'), actionsWin );
var addAction = ui.createActionsWinBuilder(actionsWin);
for (var p = 0; p < app._actionsOrder.length; ++p) {
var act = app.actions[app._actionsOrder[p]];
@ -36,7 +44,7 @@ function start() {
if (isNaN(num)) {
num = Number(app.viewer.parametricManager.constantResolver(val));
return val + "(" + (isNaN(num) ? "?" : num.toFixed(2)) + ")" ;
}
}
return num.toFixed(2);
}).join(", ");
if (info.length != 0) {
@ -46,7 +54,7 @@ function start() {
}
var pm = app.viewer.parametricManager;
var constrList = new TCAD.ui.List('constrs', {
var constrList = new ui.List('constrs', {
items : function() {
var theItems = [];
for (var j = 0; j < pm.subSystems.length; j++) {
@ -87,9 +95,9 @@ function start() {
for (var f in c.SettableFields) {
var value = c[f];
var intro = c.SettableFields[f];
value = TCAD.TWO.utils.askNumber(intro, typeof(value) == "number" ? value.toFixed(4) : value, prompt, pm.constantResolver);
value = askNumber(intro, typeof(value) == "number" ? value.toFixed(4) : value, prompt, pm.constantResolver);
if (value != null) {
c[f] = value;
}
@ -101,19 +109,19 @@ function start() {
function configureConstraintsFilter() {
var constraintsCaption = constraintsView.node.find('.tool-caption');
var constraintsFilterBtn = TCAD.App2D.faBtn("filter");
var constraintsFilterBtn = ui.faBtn("filter");
constraintsFilterBtn.css({'float': 'right', 'margin-right': '10px', cursor: 'pointer'});
constraintsCaption.append(constraintsFilterBtn);
var constraintsFilterWin = new TCAD.ui.Window($('#constrFilter'), app.winManager);
TCAD.ui.bindOpening(constraintsFilterBtn, constraintsFilterWin);
var constraintsFilterWin = new ui.Window($('#constrFilter'), app.winManager);
ui.bindOpening(constraintsFilterBtn, constraintsFilterWin);
var content = constraintsFilterWin.root.find('.content');
var constrTypes = [], constrType;
for (var cname in TCAD.TWO.Constraints) {
c = TCAD.TWO.Constraints[cname];
for (var cname in Constraints) {
c = Constraints[cname];
if (c.prototype !== undefined && c.prototype.UI_NAME !== undefined && !c.prototype.aux) {
constrTypes.push(c);
}
}
}
constrTypes.sort(function (a, b) {
if (a.prototype.NAME == 'coi') {
@ -126,10 +134,10 @@ function start() {
if (c.prototype !== undefined && c.prototype.UI_NAME !== undefined && !c.prototype.aux) {
var checkbox = $('<input>', {type : 'checkbox', checked : 'checked', value : c.prototype.NAME});
content.append(
$('<label>', { css : {display : 'block', 'white-space' : 'nowrap'}})
.append(checkbox)
.append(c.prototype.UI_NAME)
);
$('<label>', { css : {display : 'block', 'white-space' : 'nowrap'}})
.append(checkbox)
.append(c.prototype.UI_NAME)
);
checkbox.change(function(){
var checkbox = $(this);
app.constraintFilter[checkbox.val()] = checkbox.is(':checked') != true;
@ -143,9 +151,9 @@ function start() {
app.viewer.parametricManager.listeners.push(function() {constrList.refresh()});
constrList.refresh();
var layerSelection = new TCAD.toolkit.Combo('layerSelection', 'Layer');
var layerSelection = new toolkit.Combo('layerSelection', 'Layer');
app.dock.views['Properties'].node.append(layerSelection.root);
var updateLayersList = function () {
var options = '';
for (var i = 0; i < app.viewer.layers.length; i++) {
@ -167,11 +175,11 @@ function start() {
}
});
var dimScale = new TCAD.toolkit.Number("Dim Scale", 1, 0.1, 1);
var dimScale = new toolkit.Number("Dim Scale", 1, 0.1, 1);
dimScale.min = 0.1;
app.dock.views['Properties'].node.append(dimScale.root);
dimScale.input.on('t-change', function() {
app.viewer.dimScale = $(this).val();
app.viewer.dimScale = $(this).val();
});
app.viewer.bus.subscribe('dimScale', function(value) {
dimScale.input.val(value);
@ -192,12 +200,7 @@ function start() {
app.dock.views['Dimensions'].node.append(constantTextArea);
}
window.___log = function(log) {
$('#log').append( " *****************<br><br><br><br>");
for (var i = 0; i < log.length; i++) {
$('#log').append( log[i] + " <br>");
}
};
window.onload = function() {
setTimeout(start, 0);
setTimeout(initializeSketcherApplication, 0);
};

View file

@ -1,41 +1,41 @@
TCAD.constraints = {};
import {fillArray} from '../../utils/utils'
/**
* This intermediate layer should be eliminated since constraint server isn't used anymore
*/
TCAD.constraints.create = function(name, params, values) {
function createByConstraintName(name, params, values) {
switch (name) {
case "equal":
return new TCAD.constraints.Equal(params);
return new Equal(params);
case "equalsTo":
return new TCAD.constraints.EqualsTo(params, values[0]);
return new EqualsTo(params, values[0]);
case "MinLength":
return new TCAD.constraints.MinLength(params, values[0]);
return new MinLength(params, values[0]);
case "perpendicular":
return new TCAD.constraints.Perpendicular(params);
return new Perpendicular(params);
case "parallel":
return new TCAD.constraints.Parallel(params);
return new Parallel(params);
case "P2LDistance":
return new TCAD.constraints.P2LDistance(params, values[0]);
return new P2LDistance(params, values[0]);
case "P2LDistanceV":
return new TCAD.constraints.P2LDistanceV(params);
return new P2LDistanceV(params);
case "P2PDistance":
return new TCAD.constraints.P2PDistance(params, values[0]);
return new P2PDistance(params, values[0]);
case "P2PDistanceV":
return new TCAD.constraints.P2PDistanceV(params);
return new P2PDistanceV(params);
case "angle":
return new TCAD.constraints.Angle(params);
return new Angle(params);
case "angleConst":
var _ = true, x = false;
// Exclude angle value from parameters
return new TCAD.constraints.ConstantWrapper(new TCAD.constraints.Angle(params), [x,x,x,x,x,x,x,x,_]);
return new ConstantWrapper(new Angle(params), [x,x,x,x,x,x,x,x,_]);
case 'LockConvex':
return new TCAD.constraints.LockConvex(params);
return new LockConvex(params);
}
};
}
/** @constructor */
TCAD.constraints.Equal = function(params) {
function Equal(params) {
this.params = params;
@ -47,10 +47,10 @@ TCAD.constraints.Equal = function(params) {
out[0] = 1;
out[1] = -1;
}
};
}
TCAD.constraints.MinLength = function(params, distance) {
function MinLength(params, distance) {
this.params = params;
this.distance = distance;
@ -85,9 +85,9 @@ TCAD.constraints.MinLength = function(params, distance) {
out[p2x] = -dx / d;
out[p2y] = -dy / d;
}
};
}
TCAD.constraints.LockConvex = function(params) {
function LockConvex(params) {
this.params = params;
var _pcx = 0;
@ -126,11 +126,11 @@ TCAD.constraints.LockConvex = function(params) {
out[_ptx] = ay-cy;
out[_pty] = cx-ax;
}
};
}
/** @constructor */
TCAD.constraints.ConstantWrapper = function(constr, mask) {
function ConstantWrapper(constr, mask) {
this.params = [];
this.grad = [];
@ -148,7 +148,7 @@ TCAD.constraints.ConstantWrapper = function(constr, mask) {
};
this.gradient = function(out) {
TCAD.math.Arrays_fill(this.grad, 0, this.grad.length, 0);
fillArray(this.grad, 0, this.grad.length, 0);
constr.gradient(this.grad);
var jj = 0;
for (j = 0; j < mask.length; j++) {
@ -157,10 +157,10 @@ TCAD.constraints.ConstantWrapper = function(constr, mask) {
}
}
}
};
}
/** @constructor */
TCAD.constraints.Weighted = function(constr, weight) {
function Weighted(constr, weight) {
this.weight = weight;
this.params = constr.params;
@ -176,11 +176,11 @@ TCAD.constraints.Weighted = function(constr, weight) {
out[i] *= this.weight;
}
}
};
}
/** @constructor */
TCAD.constraints.EqualsTo = function(params, value) {
function EqualsTo(params, value) {
this.params = params;
this.value = value;
@ -192,10 +192,10 @@ TCAD.constraints.EqualsTo = function(params, value) {
this.gradient = function(out) {
out[0] = 1;
};
};
}
/** @constructor */
TCAD.constraints.P2LDistance = function(params, distance) {
function P2LDistance(params, distance) {
this.params = params;
this.distance = distance;
@ -241,12 +241,12 @@ TCAD.constraints.P2LDistance = function(params, distance) {
out[LP2X] = j * (y0 - y1) / d - AM * dx / d3;
out[LP2Y] = j * (x1 - x0) / d - AM * dy / d3;
TCAD.constraints._fixNaN(out);
_fixNaN(out);
}
};
}
/** @constructor */
TCAD.constraints.P2LDistanceV = function(params) {
function P2LDistanceV(params) {
this.params = params;//.slice(0, params.length -1);
@ -294,12 +294,12 @@ TCAD.constraints.P2LDistanceV = function(params) {
out[LP2Y] = j * (x1 - x0) / d - AM * dy / d3;
out[D] = -1;
TCAD.constraints._fixNaN(out);
_fixNaN(out);
}
};
}
/** @constructor */
TCAD.constraints.P2PDistance = function(params, distance) {
function P2PDistance(params, distance) {
this.params = params;
this.distance = distance;
@ -330,11 +330,11 @@ TCAD.constraints.P2PDistance = function(params, distance) {
out[p2y] = -dy / d;
}
};
}
/** @constructor */
TCAD.constraints.P2PDistanceV = function(params) {
function P2PDistanceV(params) {
this.params = params;
@ -365,11 +365,11 @@ TCAD.constraints.P2PDistanceV = function(params) {
out[p2y] = -dy / d;
out[D] = -1;
}
};
}
/** @constructor */
TCAD.constraints.Parallel = function(params) {
function Parallel(params) {
this.params = params;
@ -400,10 +400,10 @@ TCAD.constraints.Parallel = function(params) {
out[l2p1y] = (params[l1p1x].get() - params[l1p2x].get());
out[l2p2y] = -(params[l1p1x].get() - params[l1p2x].get());
}
};
}
/** @constructor */
TCAD.constraints.Perpendicular = function(params) {
function Perpendicular(params) {
this.params = params;
@ -435,10 +435,10 @@ TCAD.constraints.Perpendicular = function(params) {
out[l2p1y] = (params[l1p1y].get() - params[l1p2y].get());
out[l2p2y] = -(params[l1p1y].get() - params[l1p2y].get());
}
};
}
/** @constructor */
TCAD.constraints.Angle = function(params) {
function Angle(params) {
this.params = params;
@ -478,8 +478,8 @@ TCAD.constraints.Angle = function(params) {
out[l1p1y] = dx1 / r2;
out[l1p2x] = dy1 / r2;
out[l1p2y] = -dx1 / r2;
var dx1 = (p(l1p2x) - p(l1p1x));
var dy1 = (p(l1p2y) - p(l1p1y));
dx1 = (p(l1p2x) - p(l1p1x));
dy1 = (p(l1p2y) - p(l1p1y));
var dx2 = (p(l2p2x) - p(l2p1x));
var dy2 = (p(l2p2y) - p(l2p1y));
var a = Math.atan2(dy1, dx1) + p(angle);
@ -487,7 +487,7 @@ TCAD.constraints.Angle = function(params) {
var sa = Math.sin(a);
var x2 = dx2 * ca + dy2 * sa;
var y2 = -dx2 * sa + dy2 * ca;
var r2 = dx2 * dx2 + dy2 * dy2;
r2 = dx2 * dx2 + dy2 * dy2;
dx2 = -y2 / r2;
dy2 = x2 / r2;
out[l2p1x] = (-ca * dx2 + sa * dy2);
@ -495,20 +495,22 @@ TCAD.constraints.Angle = function(params) {
out[l2p2x] = ( ca * dx2 - sa * dy2);
out[l2p2y] = ( sa * dx2 + ca * dy2);
out[angle] = -1;
TCAD.constraints.rescale(out, scale);
rescale(out, scale);
}
};
}
TCAD.constraints._fixNaN = function(grad) {
function _fixNaN(grad) {
for (var i = 0; i < grad.length; i++) {
if (isNaN(grad[i])) {
grad[i] = 0;
}
}
};
}
TCAD.constraints.rescale = function(grad, factor) {
function rescale(grad, factor) {
for (var i = 0; i < grad.length; i++) {
grad[i] *= factor;
}
};
}
export {createByConstraintName, EqualsTo, ConstantWrapper}

View file

@ -1,27 +1,32 @@
TCAD.parametric = {};
import * as utils from '../../utils/utils'
import * as math from '../../math/math'
import QR from '../../math/qr'
import LMOptimizer from '../../math/lm'
import {ConstantWrapper, EqualsTo} from './constraints'
import {dog_leg} from '../../math/optim'
/** @constructor */
TCAD.parametric.Param = function(id, value, readOnly) {
function Param(id, value, readOnly) {
this.reset(value);
};
}
TCAD.parametric.Param.prototype.reset = function(value) {
Param.prototype.reset = function(value) {
this.set(value);
this.j = -1;
};
TCAD.parametric.Param.prototype.set = function(value) {
Param.prototype.set = function(value) {
this.value = value;
};
TCAD.parametric.Param.prototype.get = function() {
Param.prototype.get = function() {
return this.value;
};
TCAD.parametric.Param.prototype.nop = function() {};
Param.prototype.nop = function() {};
/** @constructor */
TCAD.parametric.System = function(constraints) {
function System(constraints) {
this.constraints = constraints;
this.params = [];
for (var ci = 0; ci < constraints.length; ++ci) {
@ -34,10 +39,10 @@ TCAD.parametric.System = function(constraints) {
}
}
}
};
}
TCAD.parametric.System.prototype.makeJacobian = function() {
System.prototype.makeJacobian = function() {
var jacobi = [];
var i;
var j;
@ -52,7 +57,7 @@ TCAD.parametric.System.prototype.makeJacobian = function() {
var cParams = c.params;
var grad = [];
TCAD.math.Arrays_fill(grad, 0, cParams.length, 0);
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
@ -64,13 +69,13 @@ TCAD.parametric.System.prototype.makeJacobian = function() {
return jacobi;
};
TCAD.parametric.System.prototype.fillJacobian = function(jacobi) {
System.prototype.fillJacobian = function(jacobi) {
for (var i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
var cParams = c.params;
var grad = [];
TCAD.math.Arrays_fill(grad, 0, cParams.length, 0);
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
@ -82,7 +87,7 @@ TCAD.parametric.System.prototype.fillJacobian = function(jacobi) {
return jacobi;
};
TCAD.parametric.System.prototype.calcResidual = function(r) {
System.prototype.calcResidual = function(r) {
var i=0;
var err = 0.;
@ -97,7 +102,7 @@ TCAD.parametric.System.prototype.calcResidual = function(r) {
return err;
};
TCAD.parametric.System.prototype.calcGrad_ = function(out) {
System.prototype.calcGrad_ = function(out) {
var i;
for (i = 0; i < out.length || i < this.params.length; ++i) {
out[i][0] = 0;
@ -108,7 +113,7 @@ TCAD.parametric.System.prototype.calcGrad_ = function(out) {
var cParams = c.params;
var grad = [];
TCAD.math.Arrays_fill(grad, 0, cParams.length, 0);
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
@ -119,7 +124,7 @@ TCAD.parametric.System.prototype.calcGrad_ = function(out) {
}
};
TCAD.parametric.System.prototype.calcGrad = function(out) {
System.prototype.calcGrad = function(out) {
var i;
for (i = 0; i < out.length || i < this.params.length; ++i) {
out[i] = 0;
@ -130,10 +135,8 @@ TCAD.parametric.System.prototype.calcGrad = function(out) {
var cParams = c.params;
var grad = [];
TCAD.math.Arrays_fill(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
utils.fillArray(grad, 0, cParams.length, 0);
for (var p = 0; p < cParams.length; p++) {
var param = cParams[p];
var j = param.j;
out[j] += this.constraints[i].error() * grad[p]; // (10.4)
@ -141,25 +144,25 @@ TCAD.parametric.System.prototype.calcGrad = function(out) {
}
};
TCAD.parametric.System.prototype.fillParams = function(out) {
System.prototype.fillParams = function(out) {
for (var p = 0; p < this.params.length; p++) {
out[p] = this.params[p].get();
}
};
TCAD.parametric.System.prototype.getParams = function() {
System.prototype.getParams = function() {
var out = [];
this.fillParams(out);
return out;
};
TCAD.parametric.System.prototype.setParams = function(point) {
System.prototype.setParams = function(point) {
for (var p = 0; p < this.params.length; p++) {
this.params[p].set(point[p]);
}
};
TCAD.parametric.System.prototype.error = function() {
System.prototype.error = function() {
var error = 0;
for (var i=0; i < this.constraints.length; i++) {
error += Math.abs(this.constraints[i].error());
@ -167,7 +170,7 @@ TCAD.parametric.System.prototype.error = function() {
return error;
};
TCAD.parametric.System.prototype.errorSquare = function() {
System.prototype.errorSquare = function() {
var error = 0;
for (var i=0; i < this.constraints.length; i++) {
var t = this.constraints[i].error();
@ -176,7 +179,7 @@ TCAD.parametric.System.prototype.errorSquare = function() {
return error * 0.5;
};
TCAD.parametric.System.prototype.getValues = function() {
System.prototype.getValues = function() {
var values = [];
for (var i=0; i < this.constraints.length; i++) {
values[i] = this.constraints[i].error();
@ -184,14 +187,14 @@ TCAD.parametric.System.prototype.getValues = function() {
return values;
};
TCAD.parametric.wrapAux = function(constrs, locked) {
var wrapAux = function(constrs, locked) {
var lockedSet = {};
for (var i = 0; i < locked.length; i++) {
var i, lockedSet = {};
for (i = 0; i < locked.length; i++) {
lockedSet[locked[i].j] = true;
}
for (var i = 0; i < constrs.length; i++) {
for (i = 0; i < constrs.length; i++) {
var c = constrs[i];
var mask = [];
var needWrap = false;
@ -201,21 +204,21 @@ TCAD.parametric.wrapAux = function(constrs, locked) {
needWrap = needWrap || mask[j];
}
if (needWrap) {
var wrapper = new TCAD.constraints.ConstantWrapper(c, mask);
var wrapper = new ConstantWrapper(c, mask);
constrs[i] = wrapper;
}
}
};
TCAD.parametric.lock2Equals2 = function(constrs, locked) {
var lock2Equals2 = function(constrs, locked) {
var _locked = [];
for (var i = 0; i < locked.length; ++i) {
_locked.push(new TCAD.constraints.EqualsTo([locked[i]], locked[i].get()));
_locked.push(new EqualsTo([locked[i]], locked[i].get()));
}
return _locked;
};
TCAD.parametric.diagnose = function(sys) {
var diagnose = function(sys) {
if (sys.constraints.length == 0 || sys.params.length == 0) {
return {
conflict : false,
@ -223,24 +226,24 @@ TCAD.parametric.diagnose = function(sys) {
}
}
var jacobian = sys.makeJacobian();
var qr = new TCAD.math.QR(jacobian);
var qr = new QR(jacobian);
return {
conflict : sys.constraints.length > qr.rank,
dof : sys.params.length - qr.rank
}
};
TCAD.parametric.prepare = function(constrs, locked, aux, alg) {
var prepare = function(constrs, locked, aux, alg) {
var simpleMode = true;
if (!simpleMode) {
var lockingConstrs = TCAD.parametric.lock2Equals2(constrs, locked);
var lockingConstrs = lock2Equals2(constrs, locked);
Array.prototype.push.apply( constrs, lockingConstrs );
}
var sys = new TCAD.parametric.System(constrs);
var sys = new System(constrs);
TCAD.parametric.wrapAux(constrs, aux);
wrapAux(constrs, aux);
var model = function(point) {
sys.setParams(point);
@ -263,14 +266,14 @@ TCAD.parametric.prepare = function(constrs, locked, aux, alg) {
if (sys.params.length == 0) return nullResult;
switch (alg) {
case 2:
return TCAD.parametric.solve_lm(sys, model, jacobian, rough);
return solve_lm(sys, model, jacobian, rough);
case 1:
default:
return optim.dog_leg(sys, rough);
return dog_leg(sys, rough);
}
}
var systemSolver = {
diagnose : function() {return TCAD.parametric.diagnose(sys)},
diagnose : function() {return diagnose(sys)},
error : function() {return sys.error()},
solveSystem : solve,
system : sys,
@ -287,8 +290,8 @@ TCAD.parametric.prepare = function(constrs, locked, aux, alg) {
return systemSolver;
};
TCAD.parametric.solve_lm = function(sys, model, jacobian, rough) {
var opt = new LMOptimizer(sys.getParams(), TCAD.math.vec(sys.constraints.length), model, jacobian);
var solve_lm = function(sys, model, jacobian, rough) {
var opt = new LMOptimizer(sys.getParams(), math.vec(sys.constraints.length), model, jacobian);
opt.evalMaximalCount = 100 * sys.params.length;
var eps = rough ? 0.001 : 0.00000001;
opt.init0(eps, eps, eps);
@ -306,3 +309,4 @@ TCAD.parametric.solve_lm = function(sys, model, jacobian, rough) {
};
};
export {Param, prepare}

View file

@ -1,4 +1,4 @@
TCAD.TWO.ParametricManager.prototype._fetchTwoPoints = function(objs) {
export function twoPoints(objs) {
var points = [];
for (var i = 0; i < objs.length; ++i) {
if (objs[i]._class == 'TCAD.TWO.EndPoint') {
@ -12,9 +12,9 @@ TCAD.TWO.ParametricManager.prototype._fetchTwoPoints = function(objs) {
throw "Illegal Argument. Constraint requires 2 points or 1 line."
}
return points;
};
}
TCAD.TWO.ParametricManager.prototype._fetchPoints = function(objs) {
export function points(objs) {
var points = [];
for (var i = 0; i < objs.length; ++i) {
objs[i].accept(function(o) {
@ -28,9 +28,9 @@ TCAD.TWO.ParametricManager.prototype._fetchPoints = function(objs) {
throw "Illegal Argument. Constraint requires at least 1 point/line/arc/circle."
}
return points;
};
}
TCAD.TWO.ParametricManager.prototype._fetchArkCirc = function(objs, min) {
export function arkCirc(objs, min) {
var arcs = [];
for (var i = 0; i < objs.length; ++i) {
if (objs[i]._class === 'TCAD.TWO.Arc' || objs[i]._class === 'TCAD.TWO.Circle') {
@ -41,9 +41,9 @@ TCAD.TWO.ParametricManager.prototype._fetchArkCirc = function(objs, min) {
throw "Illegal Argument. Constraint requires at least " + min + " arcs/circles."
}
return arcs;
};
}
TCAD.TWO.ParametricManager.prototype._fetch = function(objs, types, min) {
export function generic(objs, types, min) {
var result = [];
for (var i = 0; i < objs.length; ++i) {
if (types.indexOf(objs[i]._class) > -1 ) {
@ -54,9 +54,9 @@ TCAD.TWO.ParametricManager.prototype._fetch = function(objs, types, min) {
throw "Illegal Argument. Constraint requires at least " + min + " of " + types;
}
return result;
};
}
TCAD.TWO.ParametricManager.prototype._fetchPointAndLine = function(objs) {
export function pointAndLine(objs) {
var point = null;
var line = null;
@ -73,18 +73,18 @@ TCAD.TWO.ParametricManager.prototype._fetchPointAndLine = function(objs) {
}
return [point, line];
};
}
TCAD.TWO.ParametricManager.prototype._fetchLine = function(objs) {
export function line(objs) {
for (var i = 0; i < objs.length; ++i) {
if (objs[i]._class == 'TCAD.TWO.Segment') {
return objs[i];
}
}
throw "Illegal Argument. Constraint requires a line."
};
}
TCAD.TWO.ParametricManager.prototype._fetchArcCircAndLine = function(objs) {
export function arcCircAndLine(objs) {
var arc = null;
var line = null;
@ -101,9 +101,9 @@ TCAD.TWO.ParametricManager.prototype._fetchArcCircAndLine = function(objs) {
}
return [arc, line];
};
}
TCAD.TWO.ParametricManager.prototype._fetchTwoLines = function(objs) {
export function twoLines(objs) {
var lines = [];
for (var i = 0; i < objs.length; ++i) {
if (objs[i]._class == 'TCAD.TWO.Segment') {
@ -114,9 +114,9 @@ TCAD.TWO.ParametricManager.prototype._fetchTwoLines = function(objs) {
throw "Illegal Argument. Constraint requires 2 lines."
}
return lines;
};
}
TCAD.TWO.utils._fetchSketchObjects = function(objs, silent, matching) {
export function sketchObjects(objs, silent, matching) {
var fetched = [];
for (var i = 0; i < objs.length; ++i) {
for (var j = 0; j < matching.length; j++) {
@ -134,5 +134,5 @@ TCAD.TWO.utils._fetchSketchObjects = function(objs, silent, matching) {
}
}
return fetched;
};
}

View file

@ -1,22 +1,31 @@
/** @constructor */
TCAD.TWO.FilletTool = function(viewer) {
this.viewer = viewer;
};
import Vector from '../math/vector'
import {Styles} from './viewer2d'
import * as fetch from './fetchers'
import * as math from '../math/math'
import {EndPoint} from './viewer2d'
import {Arc} from './shapes/arc'
import {Constraints} from './parametric'
TCAD.TWO.FilletTool.prototype.makeFillet = function(point1, point2) {
/** @constructor */
function FilletTool(viewer) {
this.viewer = viewer;
}
FilletTool.prototype.makeFillet = function(point1, point2) {
function shrink(point1) {
var a, b;
if (point1.id === point1.parent.a.id) {
var a = point1.parent.b;
var b = point1.parent.a;
a = point1.parent.b;
b = point1.parent.a;
} else {
var a = point1.parent.a;
var b = point1.parent.b;
a = point1.parent.a;
b = point1.parent.b;
}
var d = TCAD.math.distanceAB(a, b);
var d = math.distanceAB(a, b);
var k = 4 / 5;
b.x = a.x + (b.x - a.x) * k;
b.y = a.y + (b.y - a.y) * k;
return new TCAD.Vector(a.x - b.x, a.y - b.y, 0);
return new Vector(a.x - b.x, a.y - b.y, 0);
}
var v1 = shrink(point1);
@ -28,23 +37,23 @@ TCAD.TWO.FilletTool.prototype.makeFillet = function(point1, point2) {
point2 = _;
}
var vec = new TCAD.Vector();
var vec = new Vector();
vec.setV(point2);
vec._minus(point1);
vec._multiply(0.5);
vec._plus(point1);
var arc = new TCAD.TWO.Arc(
new TCAD.TWO.EndPoint(point1.x, point1.y),
new TCAD.TWO.EndPoint(point2.x, point2.y),
new TCAD.TWO.EndPoint(vec.x, vec.y))
var arc = new Arc(
new EndPoint(point1.x, point1.y),
new EndPoint(point2.x, point2.y),
new EndPoint(vec.x, vec.y));
point1.parent.layer.objects.push(arc);
var pm = this.viewer.parametricManager;
arc.stabilize(this.viewer);
pm._add(new TCAD.TWO.Constraints.Tangent( arc, point1.parent));
pm._add(new TCAD.TWO.Constraints.Tangent( arc, point2.parent));
pm._add(new TCAD.TWO.Constraints.Coincident( arc.a, point1));
pm._add(new TCAD.TWO.Constraints.Coincident( arc.b, point2));
pm._add(new Constraints.Tangent( arc, point1.parent));
pm._add(new Constraints.Tangent( arc, point2.parent));
pm._add(new Constraints.Coincident( arc.a, point1));
pm._add(new Constraints.Coincident( arc.b, point2));
//function otherEnd(point) {
// if (point.parent.a.id === point.id) {
@ -54,8 +63,8 @@ TCAD.TWO.FilletTool.prototype.makeFillet = function(point1, point2) {
// }
//}
//
//pm._add(new TCAD.TWO.Constraints.LockConvex(arc.c, arc.a, otherEnd(point1)));
//pm._add(new TCAD.TWO.Constraints.LockConvex(otherEnd(point2), arc.b, arc.c));
//pm._add(new Constraints.LockConvex(arc.c, arc.a, otherEnd(point1)));
//pm._add(new Constraints.LockConvex(otherEnd(point2), arc.b, arc.c));
var solver = pm.solveWithLock([]);
// var solver = pm.solveWithLock([point1._x, point1._y, point2._x, point2._y]);
@ -63,7 +72,7 @@ TCAD.TWO.FilletTool.prototype.makeFillet = function(point1, point2) {
this.viewer.refresh();
};
TCAD.TWO.FilletTool.prototype.mouseup = function(e) {
FilletTool.prototype.mouseup = function(e) {
var candi = this.getCandidate(e);
if (candi == null) return;
var point1 = candi[0];
@ -86,13 +95,14 @@ TCAD.TWO.FilletTool.prototype.mouseup = function(e) {
}
};
TCAD.TWO.FilletTool.prototype.getCandidate = function(e) {
function isLine(line) {
return line != null && line._class === 'TCAD.TWO.Segment';
}
FilletTool.prototype.getCandidate = function(e) {
var picked = this.viewer.pick(e);
if (picked.length > 0) {
function isLine(line) {
return line != null && line._class === 'TCAD.TWO.Segment';
}
var res = TCAD.TWO.utils._fetchSketchObjects(picked, true, ['TCAD.TWO.EndPoint']);
var res = fetch.sketchObjects(picked, true, ['TCAD.TWO.EndPoint']);
if (res == null) return null;
var point1 = res[0];
if (!isLine(point1.parent)) return;
@ -107,12 +117,12 @@ TCAD.TWO.FilletTool.prototype.getCandidate = function(e) {
return null;
};
TCAD.TWO.FilletTool.prototype.keydown = function(e) {};
TCAD.TWO.FilletTool.prototype.keypress = function(e) {};
TCAD.TWO.FilletTool.prototype.keyup = function(e) {};
TCAD.TWO.FilletTool.prototype.cleanup = function(e) {};
FilletTool.prototype.keydown = function(e) {};
FilletTool.prototype.keypress = function(e) {};
FilletTool.prototype.keyup = function(e) {};
FilletTool.prototype.cleanup = function(e) {};
TCAD.TWO.FilletTool.prototype.mousemove = function(e) {
FilletTool.prototype.mousemove = function(e) {
var needRefresh = false;
if (this.viewer.selected.length != 0) {
this.viewer.deselectAll();
@ -120,13 +130,14 @@ TCAD.TWO.FilletTool.prototype.mousemove = function(e) {
}
var candi = this.getCandidate(e);
if (candi != null) {
this.viewer.mark(candi[0], TCAD.TWO.Styles.SNAP);
this.viewer.mark(candi[0], Styles.SNAP);
needRefresh = true;
}
if (needRefresh) {
this.viewer.refresh();
}
};
TCAD.TWO.FilletTool.prototype.mousedown = function(e) {};
TCAD.TWO.FilletTool.prototype.mousewheel = function(e) {};
FilletTool.prototype.mousedown = function(e) {};
FilletTool.prototype.mousewheel = function(e) {};
export {FilletTool}

View file

@ -1,18 +1,19 @@
import diff_match_patch from 'diff-match-patch';
/** @constructor */
TCAD.HistoryManager = function(viewer) {
function HistoryManager(viewer) {
this.viewer = viewer;
this.dmp = new diff_match_patch();
this.init(this.viewer.io.serializeSketch());
};
}
TCAD.HistoryManager.prototype.init = function(sketchData) {
HistoryManager.prototype.init = function(sketchData) {
this.lastCheckpoint = sketchData;
this.diffs = [];
this.historyPointer = -1;
};
TCAD.HistoryManager.prototype.undo = function () {
HistoryManager.prototype.undo = function () {
var currentState = this.viewer.io.serializeSketch();
if (currentState == this.lastCheckpoint) {
if (this.historyPointer != -1) {
@ -33,14 +34,14 @@ TCAD.HistoryManager.prototype.undo = function () {
}
};
TCAD.HistoryManager.prototype.lightCheckpoint = function (weight) {
HistoryManager.prototype.lightCheckpoint = function (weight) {
this._counter += weight;
if (this._counter >= 100) {
this.checkpoint();
}
};
TCAD.HistoryManager.prototype.checkpoint = function () {
HistoryManager.prototype.checkpoint = function () {
try {
this._checkpoint();
} catch(e) {
@ -48,7 +49,7 @@ TCAD.HistoryManager.prototype.checkpoint = function () {
}
};
TCAD.HistoryManager.prototype._checkpoint = function () {
HistoryManager.prototype._checkpoint = function () {
this._counter = 0;
var currentState = this.viewer.io.serializeSketch();
if (currentState == this.lastCheckpoint) {
@ -63,7 +64,7 @@ TCAD.HistoryManager.prototype._checkpoint = function () {
this.lastCheckpoint = currentState;
};
TCAD.HistoryManager.prototype.redo = function () {
HistoryManager.prototype.redo = function () {
var currentState = this.viewer.io.serializeSketch();
if (currentState != this.lastCheckpoint) {
return;
@ -77,20 +78,20 @@ TCAD.HistoryManager.prototype.redo = function () {
}
};
TCAD.HistoryManager.prototype.applyDiff = function (text1, diff) {
HistoryManager.prototype.applyDiff = function (text1, diff) {
var dmp = this.dmp;
var results = dmp.patch_apply(diff, text1);
return results[0];
};
TCAD.HistoryManager.prototype.applyDiffInv = function (text1, diff) {
HistoryManager.prototype.applyDiffInv = function (text1, diff) {
this.reversePatch(diff);
var result = this.applyDiff(text1, diff);
this.reversePatch(diff);
return result;
};
TCAD.HistoryManager.prototype.reversePatch = function (plist) {
HistoryManager.prototype.reversePatch = function (plist) {
for (var i = 0; i < plist.length; i++) {
var patch = plist[i];
for (var j = 0; j < patch.diffs.length; j++) {
@ -100,7 +101,7 @@ TCAD.HistoryManager.prototype.reversePatch = function (plist) {
}
};
TCAD.HistoryManager.prototype.getDiff = function (text1, text2) {
HistoryManager.prototype.getDiff = function (text1, text2) {
var dmp = this.dmp;
var diff = dmp.diff_main(text1, text2, true);
@ -113,3 +114,5 @@ TCAD.HistoryManager.prototype.getDiff = function (text1, text2) {
//console.log(patch_list);
return patch_list;
};
export {HistoryManager}

View file

@ -1,6 +1,11 @@
TCAD.io = {};
import {EndPoint, Layer, Styles, Segment, SketchObject} from './viewer2d'
import {Arc} from './shapes/arc'
import {Circle} from './shapes/circle'
import {HDimension, VDimension, Dimension, DiameterDimension} from './shapes/dim'
import {Constraints} from './parametric'
import Vector from '../math/vector'
TCAD.io.Types = {
var Types = {
END_POINT : 'TCAD.TWO.EndPoint',
SEGMENT : 'TCAD.TWO.Segment',
ARC : 'TCAD.TWO.Arc',
@ -12,19 +17,19 @@ TCAD.io.Types = {
};
/** @constructor */
TCAD.IO = function(viewer) {
function IO(viewer) {
this.viewer = viewer;
};
}
TCAD.IO.prototype.loadSketch = function(sketchData) {
IO.prototype.loadSketch = function(sketchData) {
return this._loadSketch(JSON.parse(sketchData));
};
TCAD.IO.prototype.serializeSketch = function() {
IO.prototype.serializeSketch = function() {
return JSON.stringify(this._serializeSketch());
};
TCAD.IO.prototype._loadSketch = function(sketch) {
IO.prototype._loadSketch = function(sketch) {
this.cleanUpData();
@ -36,7 +41,7 @@ TCAD.IO.prototype._loadSketch = function(sketch) {
if (ep !== undefined) {
return
}
ep = new TCAD.TWO.EndPoint(p[1][1], p[2][1]);
ep = new EndPoint(p[1][1], p[2][1]);
index[p[1][0]] = ep._x;
index[p[2][0]] = ep._y;
index[id] = ep;
@ -57,11 +62,11 @@ TCAD.IO.prototype._loadSketch = function(sketch) {
}
}
}
var layer = new TCAD.TWO.Layer(name, TCAD.TWO.Styles.DEFAULT);
var layer = new Layer(name, Styles.DEFAULT);
viewer.layers.push(layer);
return layer;
}
var T = TCAD.io.Types;
var T = Types;
var sketchLayers = sketch['layers'];
if (sketchLayers !== undefined) {
for (var l = 0; l < sketchLayers.length; ++l) {
@ -69,40 +74,40 @@ TCAD.IO.prototype._loadSketch = function(sketch) {
var layer = getLayer(this.viewer, ioLayer['name']);
if (!!ioLayer.style) layer.style = ioLayer.style;
var layerData = ioLayer['data'];
for (var i = 0; i < layerData.length; ++i) {
for (i = 0; i < layerData.length; ++i) {
var obj = layerData[i];
var skobj = null;
var _class = obj['_class'];
var aux = !!obj['aux'];
if (_class === T.SEGMENT) {
var points = obj['points'];
var a = endPoint(points[0]);
var b = endPoint(points[1]);
skobj = new TCAD.TWO.Segment(a, b);
const points = obj['points'];
const a = endPoint(points[0]);
const b = endPoint(points[1]);
skobj = new Segment(a, b);
} else if (_class === T.END_POINT) {
skobj = endPoint(obj['location']);
} else if (_class === T.ARC) {
var points = obj['points'];
var a = endPoint(points[0]);
var b = endPoint(points[1]);
var c = endPoint(points[2]);
skobj = new TCAD.TWO.Arc(a, b, c);
const points = obj['points'];
const a = endPoint(points[0]);
const b = endPoint(points[1]);
const c = endPoint(points[2]);
skobj = new Arc(a, b, c);
if (!aux) skobj.stabilize(this.viewer);
} else if (_class === T.CIRCLE) {
var c = endPoint(obj['c']);
skobj = new TCAD.TWO.Circle(c);
const c = endPoint(obj['c']);
skobj = new Circle(c);
skobj.r.set(obj['r']);
} else if (_class === T.HDIM) {
skobj = new TCAD.TWO.HDimension(obj['a'], obj['b']);
skobj = new HDimension(obj['a'], obj['b']);
skobj.flip = obj['flip'];
} else if (_class === T.VDIM) {
skobj = new TCAD.TWO.VDimension(obj['a'], obj['b']);
skobj = new VDimension(obj['a'], obj['b']);
skobj.flip = obj['flip'];
} else if (_class === T.DIM) {
skobj = new TCAD.TWO.Dimension(obj['a'], obj['b']);
skobj = new Dimension(obj['a'], obj['b']);
skobj.flip = obj['flip'];
} else if (_class === T.DDIM) {
skobj = new TCAD.TWO.DiameterDimension(obj['obj']);
skobj = new DiameterDimension(obj['obj']);
}
if (skobj != null) {
if (aux) skobj.accept(function(o){o.aux = true; return true;});
@ -133,7 +138,7 @@ TCAD.IO.prototype._loadSketch = function(sketch) {
if (sketchConstraints !== undefined) {
for (var i = 0; i < sketchConstraints.length; ++i) {
try {
var c = this.parseConstr(sketchConstraints[i], index);
const c = this.parseConstr(sketchConstraints[i], index);
this.viewer.parametricManager._add(c);
} catch (err) {
console.error(err);
@ -147,7 +152,7 @@ TCAD.IO.prototype._loadSketch = function(sketch) {
}
};
TCAD.IO.prototype.cleanUpData = function() {
IO.prototype.cleanUpData = function() {
for (var l = 0; l < this.viewer.layers.length; ++l) {
var layer = this.viewer.layers[l];
if (layer.objects.length != 0) {
@ -155,21 +160,21 @@ TCAD.IO.prototype.cleanUpData = function() {
}
}
this.viewer.deselectAll();
TCAD.TWO.utils.ID_COUNTER = 0;
SketchObject.resetIDGenerator(0);
if (this.viewer.parametricManager.subSystems.length != 0) {
this.viewer.parametricManager.subSystems = [];
this.viewer.parametricManager.notify();
}
};
TCAD.IO.prototype._serializeSketch = function() {
IO.prototype._serializeSketch = function() {
var sketch = {};
//sketch.boundary = boundary;
sketch['layers'] = [];
function point(p) {
return [ p.id, [p._x.id, p.x], [p._y.id, p.y] ];
}
var T = TCAD.io.Types;
var T = Types;
var toSave = [this.viewer.dimLayers, this.viewer.layers];
for (var t = 0; t < toSave.length; ++t) {
var layers = toSave[t];
@ -207,7 +212,7 @@ TCAD.IO.prototype._serializeSketch = function() {
var subSystems = this.viewer.parametricManager.subSystems;
for (var j = 0; j < subSystems.length; j++) {
var sub = subSystems[j];
for (var i = 0; i < sub.constraints.length; ++i) {
for (i = 0; i < sub.constraints.length; ++i) {
if (!sub.constraints[i].aux) {
constrs.push(this.serializeConstr(sub.constraints[i]));
}
@ -221,19 +226,19 @@ TCAD.IO.prototype._serializeSketch = function() {
return sketch;
};
TCAD.IO.prototype.setupBoundary = function(boundary) {
IO.prototype.setupBoundary = function(boundary, index) {
var boundaryLayerName = "__bounds__";
var boundaryLayer = this.viewer.findLayerByName(boundaryLayerName);
if (boundaryLayer != null) {
boundaryLayer.readOnly = true;
boundaryLayer.style = TCAD.TWO.Styles.BOUNDS;
boundaryLayer.style = Styles.BOUNDS;
}
if (boundary === undefined || boundary == null) return;
if (boundaryLayer === null) {
boundaryLayer = new TCAD.TWO.Layer(boundaryLayerName, TCAD.TWO.Styles.BOUNDS);
boundaryLayer = new Layer(boundaryLayerName, Styles.BOUNDS);
boundaryLayer.readOnly = true;
this.viewer.layers.splice(0, 0, boundaryLayer);
} else {
@ -281,17 +286,17 @@ TCAD.IO.prototype.setupBoundary = function(boundary) {
}
for (i = 0; i < boundary.arcs.length; ++i, ++id) {
var a = boundary.arcs[i];
var arc = new TCAD.TWO.Arc(
new TCAD.TWO.EndPoint(a.a.x, a.a.y),
new TCAD.TWO.EndPoint(a.b.x, a.b.y),
new TCAD.TWO.EndPoint(a.c.x, a.c.y)
var arc = new Arc(
new EndPoint(a.a.x, a.a.y),
new EndPoint(a.b.x, a.b.y),
new EndPoint(a.c.x, a.c.y)
);
boundaryLayer.objects.push(arc);
__makeAux(arc);
}
for (i = 0; i < boundary.circles.length; ++i, ++id) {
obj = boundary.circles[i];
var circle = new TCAD.TWO.Circle(new TCAD.TWO.EndPoint(obj.c.x, obj.c.y));
var circle = new Circle(new EndPoint(obj.c.x, obj.c.y));
circle.r.set(obj.r);
boundaryLayer.objects.push(circle);
__makeAux(circle);
@ -299,7 +304,7 @@ TCAD.IO.prototype.setupBoundary = function(boundary) {
}
};
TCAD.IO.prototype.parseConstr = function (c, index) {
IO.prototype.parseConstr = function (c, index) {
function find(id) {
var p = index[id];
if (!p) {
@ -309,19 +314,18 @@ TCAD.IO.prototype.parseConstr = function (c, index) {
}
var name = c[0];
var ps = c[1];
var constrCreate = TCAD.TWO.Constraints.Factory[name];
var constrCreate = Constraints.Factory[name];
if (constrCreate === undefined) {
throw "CAN'T READ SKETCH. Constraint " + name + " hasn't been registered.";
}
return constrCreate(find, ps);
};
TCAD.IO.prototype.serializeConstr = function (c) {
IO.prototype.serializeConstr = function (c) {
return c.serialize();
};
TCAD.io._format = function(str, args) {
function _format(str, args) {
if (args.length == 0) return str;
var i = 0;
return str.replace(/\$/g, function() {
@ -331,22 +335,22 @@ TCAD.io._format = function(str, args) {
i ++;
return val;
});
};
}
/** @constructor */
TCAD.io.PrettyColors = function() {
function PrettyColors() {
var colors = ["#000000", "#00008B", "#006400", "#8B0000", "#FF8C00", "#E9967A"];
var colIdx = 0;
this.next = function () {
return colors[colIdx++ % colors.length];
}
};
}
/** @constructor */
TCAD.io.TextBuilder = function() {
function TextBuilder() {
this.data = "";
this.fline = function (chunk, args) {
this.data += TCAD.io._format(chunk, args) + "\n"
this.data += _format(chunk, args) + "\n"
};
this.line = function (chunk) {
this.data += chunk + "\n"
@ -358,13 +362,13 @@ TCAD.io.TextBuilder = function() {
this.number(n)
this.data += "\n"
}
};
}
/** @constructor */
TCAD.io.BBox = function() {
function BBox() {
var bbox = [Number.MAX_VALUE, Number.MAX_VALUE, - Number.MAX_VALUE, - Number.MAX_VALUE];
var T = TCAD.io.Types;
var T = Types;
this.checkLayers = function(layers) {
for (var l = 0; l < layers.length; ++l)
@ -420,13 +424,13 @@ TCAD.io.BBox = function() {
};
this.bbox = bbox;
};
}
TCAD.IO.prototype.getWorkspaceToExport = function() {
IO.prototype.getWorkspaceToExport = function() {
return [this.viewer.layers];
};
TCAD.IO.prototype.getLayersToExport = function() {
IO.prototype.getLayersToExport = function() {
var ws = this.getWorkspaceToExport();
var toExport = [];
for (var t = 0; t < ws.length; ++t) {
@ -439,17 +443,17 @@ TCAD.IO.prototype.getLayersToExport = function() {
return toExport;
};
TCAD.IO.prototype.svgExport = function () {
IO.prototype.svgExport = function () {
var T = TCAD.io.Types;
var out = new TCAD.io.TextBuilder();
var T = Types;
var out = new TextBuilder();
var bbox = new TCAD.io.BBox();
var bbox = new BBox();
var a = new TCAD.Vector();
var b = new TCAD.Vector();
var a = new Vector();
var b = new Vector();
var prettyColors = new TCAD.io.PrettyColors();
var prettyColors = new PrettyColors();
var toExport = this.getLayersToExport();
for (var l = 0; l < toExport.length; ++l) {
var layer = toExport[l];
@ -474,14 +478,15 @@ TCAD.IO.prototype.svgExport = function () {
out.line('</g>');
}
bbox.inc(20);
return TCAD.io._format("<svg viewBox='$ $ $ $'>\n", bbox.bbox) + out.data + "</svg>"
return _format("<svg viewBox='$ $ $ $'>\n", bbox.bbox) + out.data + "</svg>"
};
TCAD.IO.prototype.dxfExport = function () {
var T = TCAD.io.Types;
var out = new TCAD.io.TextBuilder();
var bbox = new TCAD.io.BBox();
IO.prototype.dxfExport = function () {
var T = Types;
var out = new TextBuilder();
var bbox = new BBox();
var toExport = this.getLayersToExport();
var i;
bbox.checkLayers(toExport);
out.line("999");
out.line("js.parametric.sketcher");
@ -521,7 +526,7 @@ TCAD.IO.prototype.dxfExport = function () {
out.line("2");
out.line("TABLES");
for (var i = 0; i < toExport.length; i++) {
for (i = 0; i < toExport.length; i++) {
out.line("0");
out.line("LAYER");
out.line("2");
@ -551,7 +556,7 @@ TCAD.IO.prototype.dxfExport = function () {
for (var l = 0; l < toExport.length; l++) {
var lid = l + 1;
var layer = toExport[l];
for (var i = 0; i < layer.objects.length; ++i) {
for (i = 0; i < layer.objects.length; ++i) {
var obj = layer.objects[i];
if (obj._class === T.END_POINT) {
out.line("0");
@ -625,10 +630,12 @@ TCAD.IO.prototype.dxfExport = function () {
return out.data;
};
TCAD.io.exportTextData = function(data, fileName) {
IO.exportTextData = function(data, fileName) {
var link = document.getElementById("downloader");
link.href = "data:application/octet-stream;charset=utf-8;base64," + btoa(data);
link.download = fileName;
link.click();
//console.log(app.viewer.io.svgExport());
};
export {IO, BBox, Types};

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,12 @@
import * as utils from '../../utils/utils';
import * as math from '../../math/math';
import Vector from '../../math/vector'
import {SketchObject, EndPoint, Ref} from '../viewer2d'
import {Constraints} from '../parametric'
/** @constructor */
TCAD.TWO.Arc = function(a, b, c) {
TCAD.TWO.SketchObject.call(this);
function Arc(a, b, c) {
SketchObject.call(this);
this.a = a;
this.b = b;
this.c = c;
@ -8,60 +14,60 @@ TCAD.TWO.Arc = function(a, b, c) {
b.parent = this;
c.parent = this;
this.children.push(a, b, c);
this.r = new TCAD.TWO.Ref(0);
this.r = new Ref(0);
this.r.value = this.distanceA();
this.r.obj = this;
};
}
TCAD.TWO.utils.extend(TCAD.TWO.Arc, TCAD.TWO.SketchObject);
utils.extend(Arc, SketchObject);
TCAD.TWO.Arc.prototype._class = 'TCAD.TWO.Arc';
Arc.prototype._class = 'TCAD.TWO.Arc';
TCAD.TWO.Arc.prototype.collectParams = function(params) {
Arc.prototype.collectParams = function(params) {
this.a.collectParams(params);
this.b.collectParams(params);
this.c.collectParams(params);
params.push(this.r);
};
TCAD.TWO.Arc.prototype.getReferencePoint = function() {
Arc.prototype.getReferencePoint = function() {
return this.c;
};
TCAD.TWO.Arc.prototype.translateImpl = function(dx, dy) {
Arc.prototype.translateImpl = function(dx, dy) {
this.a.translate(dx, dy);
this.b.translate(dx, dy);
this.c.translate(dx, dy);
};
TCAD.TWO.Arc.prototype.radiusForDrawing = function() {
Arc.prototype.radiusForDrawing = function() {
return this.distanceA();
};
TCAD.TWO.Arc.prototype.distanceA = function() {
return TCAD.math.distance(this.a.x, this.a.y, this.c.x, this.c.y);
Arc.prototype.distanceA = function() {
return math.distance(this.a.x, this.a.y, this.c.x, this.c.y);
};
TCAD.TWO.Arc.prototype.distanceB = function() {
return TCAD.math.distance(this.b.x, this.b.y, this.c.x, this.c.y);
Arc.prototype.distanceB = function() {
return math.distance(this.b.x, this.b.y, this.c.x, this.c.y);
};
TCAD.TWO.Arc.prototype.getStartAngle = function() {
Arc.prototype.getStartAngle = function() {
return Math.atan2(this.a.y - this.c.y, this.a.x - this.c.x);
};
TCAD.TWO.Arc.prototype.getEndAngle = function() {
Arc.prototype.getEndAngle = function() {
return Math.atan2(this.b.y - this.c.y, this.b.x - this.c.x);
};
TCAD.TWO.Arc.prototype.drawImpl = function(ctx, scale) {
Arc.prototype.drawImpl = function(ctx, scale) {
ctx.beginPath();
var r = this.radiusForDrawing();
var startAngle = this.getStartAngle();
var endAngle;
if (TCAD.utils.areEqual(this.a.x, this.b.x, TCAD.TOLERANCE) &&
TCAD.utils.areEqual(this.a.y, this.b.y, TCAD.TOLERANCE)) {
if (math.areEqual(this.a.x, this.b.x, math.TOLERANCE) &&
math.areEqual(this.a.y, this.b.y, math.TOLERANCE)) {
endAngle = startAngle + 2 * Math.PI;
} else {
endAngle = this.getEndAngle();
@ -81,10 +87,10 @@ TCAD.TWO.Arc.prototype.drawImpl = function(ctx, scale) {
}
};
TCAD.TWO.Arc.prototype.isPointInsideSector = function(x, y) {
var ca = new TCAD.Vector(this.a.x - this.c.x, this.a.y - this.c.y);
var cb = new TCAD.Vector(this.b.x - this.c.x, this.b.y - this.c.y);
var ct = new TCAD.Vector(x - this.c.x, y - this.c.y);
Arc.prototype.isPointInsideSector = function(x, y) {
var ca = new Vector(this.a.x - this.c.x, this.a.y - this.c.y);
var cb = new Vector(this.b.x - this.c.x, this.b.y - this.c.y);
var ct = new Vector(x - this.c.x, y - this.c.y);
ca._normalize();
cb._normalize();
@ -105,45 +111,45 @@ TCAD.TWO.Arc.prototype.isPointInsideSector = function(x, y) {
return result;
};
TCAD.TWO.Arc.prototype.normalDistance = function(aim) {
Arc.prototype.normalDistance = function(aim) {
var isInsideSector = this.isPointInsideSector(aim.x, aim.y);
if (isInsideSector) {
return Math.abs(TCAD.math.distance(aim.x, aim.y, this.c.x, this.c.y) - this.radiusForDrawing());
return Math.abs(math.distance(aim.x, aim.y, this.c.x, this.c.y) - this.radiusForDrawing());
} else {
return Math.min(
TCAD.math.distance(aim.x, aim.y, this.a.x, this.a.y),
TCAD.math.distance(aim.x, aim.y, this.b.x, this.b.y)
math.distance(aim.x, aim.y, this.a.x, this.a.y),
math.distance(aim.x, aim.y, this.b.x, this.b.y)
);
}
};
TCAD.TWO.Arc.prototype.stabilize = function(viewer) {
Arc.prototype.stabilize = function(viewer) {
this.r.set(this.distanceA());
viewer.parametricManager._add(new TCAD.TWO.Constraints.P2PDistanceV(this.b, this.c, this.r));
viewer.parametricManager._add(new TCAD.TWO.Constraints.P2PDistanceV(this.a, this.c, this.r));
viewer.parametricManager._add(new Constraints.P2PDistanceV(this.b, this.c, this.r));
viewer.parametricManager._add(new Constraints.P2PDistanceV(this.a, this.c, this.r));
};
/** @constructor */
TCAD.TWO.AddArcTool = function(viewer) {
function AddArcTool(viewer) {
this.viewer = viewer;
this.arc = null;
this.point = null;
this._v = new TCAD.Vector(0, 0, 0);
};
this._v = new Vector(0, 0, 0);
}
TCAD.TWO.AddArcTool.prototype.keydown = function(e) {};
TCAD.TWO.AddArcTool.prototype.keypress = function(e) {};
TCAD.TWO.AddArcTool.prototype.keyup = function(e) {};
TCAD.TWO.AddArcTool.prototype.cleanup = function(e) {};
AddArcTool.prototype.keydown = function(e) {};
AddArcTool.prototype.keypress = function(e) {};
AddArcTool.prototype.keyup = function(e) {};
AddArcTool.prototype.cleanup = function(e) {};
TCAD.TWO.AddArcTool.prototype.mousemove = function(e) {
AddArcTool.prototype.mousemove = function(e) {
var p = this.viewer.screenToModel(e);
if (this.point != null) {
this.point.x = p.x;
this.point.y = p.y;
var r = TCAD.math.distance(this.arc.a.x, this.arc.a.y, this.arc.c.x, this.arc.c.y);
var r = math.distance(this.arc.a.x, this.arc.a.y, this.arc.c.x, this.arc.c.y);
if (this.point.id === this.arc.b.id) {
//force placement second point on the arc
var v = this._v;
@ -168,14 +174,14 @@ TCAD.TWO.AddArcTool.prototype.mousemove = function(e) {
}
};
TCAD.TWO.AddArcTool.prototype.mouseup = function(e) {
AddArcTool.prototype.mouseup = function(e) {
if (this.arc == null) {
this.viewer.historyManager.checkpoint();
var p = this.viewer.screenToModel(e);
this.arc = new TCAD.TWO.Arc(
new TCAD.TWO.EndPoint(p.x, p.y),
new TCAD.TWO.EndPoint(p.x, p.y),
new TCAD.TWO.EndPoint(p.x, p.y)
this.arc = new Arc(
new EndPoint(p.x, p.y),
new EndPoint(p.x, p.y),
new EndPoint(p.x, p.y)
);
this.point = this.arc.a;
this.viewer.activeLayer.objects.push(this.arc);
@ -191,7 +197,7 @@ TCAD.TWO.AddArcTool.prototype.mouseup = function(e) {
}
};
TCAD.TWO.AddArcTool.prototype.snapIfNeed = function(p) {
AddArcTool.prototype.snapIfNeed = function(p) {
if (this.viewer.snapped.length != 0) {
var snapWith = this.viewer.snapped.pop();
this.viewer.cleanSnap();
@ -200,8 +206,10 @@ TCAD.TWO.AddArcTool.prototype.snapIfNeed = function(p) {
}
};
TCAD.TWO.AddArcTool.prototype.mousedown = function(e) {
AddArcTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddArcTool.prototype.mousewheel = function(e) {
AddArcTool.prototype.mousewheel = function(e) {
};
export {Arc, AddArcTool}

View file

@ -1,64 +1,68 @@
import * as utils from '../../utils/utils';
import * as math from '../../math/math';
import {SketchObject, EndPoint, Ref} from '../viewer2d'
/** @constructor */
TCAD.TWO.Circle = function(c) {
TCAD.TWO.SketchObject.call(this);
function Circle(c) {
SketchObject.call(this);
this.c = c;
c.parent = this;
this.children.push(c);
this.r = new TCAD.TWO.Ref(0);
this.r = new Ref(0);
this.r.obj = this;
};
}
TCAD.TWO.utils.extend(TCAD.TWO.Circle, TCAD.TWO.SketchObject);
utils.extend(Circle, SketchObject);
TCAD.TWO.Circle.prototype._class = 'TCAD.TWO.Circle';
Circle.prototype._class = 'TCAD.TWO.Circle';
TCAD.TWO.Circle.prototype.collectParams = function(params) {
Circle.prototype.collectParams = function(params) {
this.c.collectParams(params);
params.push(this.r);
};
TCAD.TWO.Circle.prototype.getReferencePoint = function() {
Circle.prototype.getReferencePoint = function() {
return this.c;
};
TCAD.TWO.Circle.prototype.translateImpl = function(dx, dy) {
Circle.prototype.translateImpl = function(dx, dy) {
this.c.translate(dx, dy);
};
TCAD.TWO.Circle.prototype.drawImpl = function(ctx, scale) {
Circle.prototype.drawImpl = function(ctx, scale) {
ctx.beginPath();
ctx.arc(this.c.x, this.c.y, this.r.get(), 0, 2 * Math.PI);
ctx.stroke();
};
TCAD.TWO.Circle.prototype.normalDistance = function(aim) {
return Math.abs(TCAD.math.distance(aim.x, aim.y, this.c.x, this.c.y) - this.r.get());
Circle.prototype.normalDistance = function(aim) {
return Math.abs(math.distance(aim.x, aim.y, this.c.x, this.c.y) - this.r.get());
};
TCAD.TWO.Circle.prototype.getDefaultTool = function(viewer) {
var editTool = new TCAD.TWO.EditCircleTool(viewer, null);
Circle.prototype.getDefaultTool = function(viewer) {
var editTool = new EditCircleTool(viewer, null);
editTool.circle = this;
return editTool;
};
/** @constructor */
TCAD.TWO.EditCircleTool = function(viewer) {
function EditCircleTool(viewer) {
this.viewer = viewer;
this.circle = null;
};
}
TCAD.TWO.EditCircleTool.prototype.keydown = function(e) {};
TCAD.TWO.EditCircleTool.prototype.keypress = function(e) {};
TCAD.TWO.EditCircleTool.prototype.keyup = function(e) {};
EditCircleTool.prototype.keydown = function(e) {};
EditCircleTool.prototype.keypress = function(e) {};
EditCircleTool.prototype.keyup = function(e) {};
TCAD.TWO.EditCircleTool.prototype.cleanup = function(e) {
EditCircleTool.prototype.cleanup = function(e) {
this.viewer.cleanSnap();
};
TCAD.TWO.EditCircleTool.prototype.mousemove = function(e) {
EditCircleTool.prototype.mousemove = function(e) {
var p = this.viewer.screenToModel(e);
if (this.circle != null) {
var r = TCAD.math.distance(p.x, p.y, this.circle.c.x, this.circle.c.y);
var r = math.distance(p.x, p.y, this.circle.c.x, this.circle.c.y);
this.circle.r.set(r);
if (!e.shiftKey) {
this.solveRequest(true);
@ -69,19 +73,19 @@ TCAD.TWO.EditCircleTool.prototype.mousemove = function(e) {
this.viewer.refresh();
};
TCAD.TWO.EditCircleTool.prototype.solveRequest = function(rough) {
EditCircleTool.prototype.solveRequest = function(rough) {
this.solver = this.viewer.parametricManager.prepare([this.circle.r]);
this.solver.solve(rough, 1);
this.solver.sync();
};
TCAD.TWO.EditCircleTool.prototype.mouseup = function(e) {
EditCircleTool.prototype.mouseup = function(e) {
if (this.circle == null) {
this.viewer.historyManager.checkpoint();
var needSnap = this.viewer.snapped.length != 0;
var p = needSnap ? this.viewer.snapped.pop() : this.viewer.screenToModel(e);
this.circle = new TCAD.TWO.Circle(
new TCAD.TWO.EndPoint(p.x, p.y)
this.circle = new Circle(
new EndPoint(p.x, p.y)
);
if (needSnap) this.viewer.parametricManager.linkObjects([this.circle.c, p]);
this.viewer.activeLayer.objects.push(this.circle);
@ -93,8 +97,10 @@ TCAD.TWO.EditCircleTool.prototype.mouseup = function(e) {
}
};
TCAD.TWO.EditCircleTool.prototype.mousedown = function(e) {
EditCircleTool.prototype.mousedown = function(e) {
};
TCAD.TWO.EditCircleTool.prototype.mousewheel = function(e) {
EditCircleTool.prototype.mousewheel = function(e) {
};
export {Circle, EditCircleTool}

View file

@ -1,34 +1,39 @@
import * as utils from '../../utils/utils'
import * as math from '../../math/math'
import {SketchObject, EndPoint} from '../viewer2d'
import Vector from '../../math/vector'
/** @constructor */
TCAD.TWO.LinearDimension = function(a, b) {
TCAD.TWO.SketchObject.call(this);
function LinearDimension(a, b) {
SketchObject.call(this);
this.a = a;
this.b = b;
this.flip = false;
}
utils.extend(LinearDimension, SketchObject);
LinearDimension.prototype.collectParams = function(params) {
};
TCAD.TWO.utils.extend(TCAD.TWO.LinearDimension, TCAD.TWO.SketchObject);
TCAD.TWO.LinearDimension.prototype.collectParams = function(params) {
};
TCAD.TWO.LinearDimension.prototype.getReferencePoint = function() {
LinearDimension.prototype.getReferencePoint = function() {
return this.a;
};
TCAD.TWO.LinearDimension.prototype.translateImpl = function(dx, dy) {
LinearDimension.prototype.translateImpl = function(dx, dy) {
};
TCAD.TWO.LinearDimension.prototype.getA = function() { return this.a };
TCAD.TWO.LinearDimension.prototype.getB = function() { return this.b };
LinearDimension.prototype.getA = function() { return this.a };
LinearDimension.prototype.getB = function() { return this.b };
TCAD.TWO.LinearDimension.getTextOff = function(scale) {
LinearDimension.getTextOff = function(scale) {
return 3 * scale;
};
TCAD.TWO.LinearDimension.prototype.drawImpl = function(ctx, scale, viewer) {
LinearDimension.prototype.drawImpl = function(ctx, scale, viewer) {
var off = 30 * viewer.dimScale;
var textOff = TCAD.TWO.LinearDimension.getTextOff(viewer.dimScale);
var textOff = LinearDimension.getTextOff(viewer.dimScale);
var a, b, startA, startB;
if (this.flip) {
@ -43,7 +48,7 @@ TCAD.TWO.LinearDimension.prototype.drawImpl = function(ctx, scale, viewer) {
startB = this.b;
}
var d = TCAD.math.distanceAB(a, b);
var d = math.distanceAB(a, b);
var _vx = - (b.y - a.y);
var _vy = b.x - a.x;
@ -67,7 +72,7 @@ TCAD.TWO.LinearDimension.prototype.drawImpl = function(ctx, scale, viewer) {
function drawRef(start, x, y) {
var vec = new TCAD.Vector(x - start.x, y - start.y);
var vec = new Vector(x - start.x, y - start.y);
vec._normalize();
vec._multiply(7 * viewer.dimScale);
@ -112,66 +117,65 @@ TCAD.TWO.LinearDimension.prototype.drawImpl = function(ctx, scale, viewer) {
}
};
TCAD.TWO.LinearDimension.prototype.normalDistance = function(aim) {
LinearDimension.prototype.normalDistance = function(aim) {
return -1;
};
/** @constructor */
TCAD.TWO.Dimension = function(a, b) {
TCAD.TWO.LinearDimension.call(this, a, b);
};
function Dimension(a, b) {
LinearDimension.call(this, a, b);
}
TCAD.TWO.utils.extend(TCAD.TWO.Dimension, TCAD.TWO.LinearDimension);
utils.extend(Dimension, LinearDimension);
TCAD.TWO.Dimension.prototype._class = 'TCAD.TWO.Dimension';
Dimension.prototype._class = 'TCAD.TWO.Dimension';
/** @constructor */
TCAD.TWO.HDimension = function(a, b) {
TCAD.TWO.LinearDimension.call(this, a, b);
};
function HDimension(a, b) {
LinearDimension.call(this, a, b);
}
TCAD.TWO.utils.extend(TCAD.TWO.HDimension, TCAD.TWO.LinearDimension);
utils.extend(HDimension, LinearDimension);
TCAD.TWO.HDimension.prototype._class = 'TCAD.TWO.HDimension';
HDimension.prototype._class = 'TCAD.TWO.HDimension';
TCAD.TWO.HDimension.prototype.getA = function() { return this.a };
TCAD.TWO.HDimension.prototype.getB = function() { return {x : this.b.x, y : this.a.y} };
HDimension.prototype.getA = function() { return this.a };
HDimension.prototype.getB = function() { return {x : this.b.x, y : this.a.y} };
/** @constructor */
TCAD.TWO.VDimension = function(a, b) {
TCAD.TWO.LinearDimension.call(this, a, b);
};
function VDimension(a, b) {
LinearDimension.call(this, a, b);
}
TCAD.TWO.utils.extend(TCAD.TWO.VDimension, TCAD.TWO.LinearDimension);
utils.extend(VDimension, LinearDimension);
TCAD.TWO.VDimension.prototype._class = 'TCAD.TWO.VDimension';
VDimension.prototype._class = 'TCAD.TWO.VDimension';
TCAD.TWO.VDimension.prototype.getA = function() { return this.a };
TCAD.TWO.VDimension.prototype.getB = function() { return {x : this.a.x, y : this.b.y} };
VDimension.prototype.getA = function() { return this.a };
VDimension.prototype.getB = function() { return {x : this.a.x, y : this.b.y} };
/** @constructor */
TCAD.TWO.DiameterDimension = function(obj) {
TCAD.TWO.SketchObject.call(this);
function DiameterDimension(obj) {
SketchObject.call(this);
this.obj = obj;
this.angle = Math.PI / 4;
}
DiameterDimension.prototype._class = 'TCAD.TWO.DiameterDimension';
utils.extend(DiameterDimension, SketchObject);
DiameterDimension.prototype.collectParams = function(params) {
};
TCAD.TWO.DiameterDimension.prototype._class = 'TCAD.TWO.DiameterDimension';
TCAD.TWO.utils.extend(TCAD.TWO.DiameterDimension, TCAD.TWO.SketchObject);
TCAD.TWO.DiameterDimension.prototype.collectParams = function(params) {
DiameterDimension.prototype.getReferencePoint = function() {
};
TCAD.TWO.DiameterDimension.prototype.getReferencePoint = function() {
DiameterDimension.prototype.translateImpl = function(dx, dy) {
};
TCAD.TWO.DiameterDimension.prototype.translateImpl = function(dx, dy) {
};
TCAD.TWO.DiameterDimension.prototype.drawImpl = function(ctx, scale, viewer) {
DiameterDimension.prototype.drawImpl = function(ctx, scale, viewer) {
if (this.obj == null) return;
if (this.obj._class === 'TCAD.TWO.Circle') {
this.drawForCircle(ctx, scale, viewer);
@ -180,13 +184,13 @@ TCAD.TWO.DiameterDimension.prototype.drawImpl = function(ctx, scale, viewer) {
}
};
TCAD.TWO.DiameterDimension.prototype.drawForCircle = function(ctx, scale, viewer) {
var c = new TCAD.Vector().setV(this.obj.c);
DiameterDimension.prototype.drawForCircle = function(ctx, scale, viewer) {
var c = new Vector().setV(this.obj.c);
var r = this.obj.r.get();
var angled = new TCAD.Vector(r * Math.cos(this.angle), r * Math.sin(this.angle), 0);
var angled = new Vector(r * Math.cos(this.angle), r * Math.sin(this.angle), 0);
var a = c.minus(angled);
var b = c.plus(angled);
var textOff = TCAD.TWO.LinearDimension.getTextOff(viewer.dimScale);
var textOff = LinearDimension.getTextOff(viewer.dimScale);
var d = 2 * r;
@ -217,10 +221,11 @@ TCAD.TWO.DiameterDimension.prototype.drawForCircle = function(ctx, scale, viewer
ctx.fillText(txt, 0, 0);
ctx.restore();
}
var tx, ty;
if (h - fontSize * .3 > 0) { // take into account font size to not have circle overlap symbols
var tx = (a.x + _vxn * textOff) - (-_vyn) * h;
var ty = (a.y + _vyn * textOff) - ( _vxn) * h;
tx = (a.x + _vxn * textOff) - (-_vyn) * h;
ty = (a.y + _vyn * textOff) - ( _vxn) * h;
drawText(tx, ty);
} else {
var off = 2 * viewer.dimScale;
@ -233,13 +238,13 @@ TCAD.TWO.DiameterDimension.prototype.drawForCircle = function(ctx, scale, viewer
ctx.stroke();
angled._multiply(off);
var tx = (b.x + _vxn * textOff) + angled.x;
var ty = (b.y + _vyn * textOff) + angled.y;
tx = (b.x + _vxn * textOff) + angled.x;
ty = (b.y + _vyn * textOff) + angled.y;
drawText(tx, ty);
}
};
TCAD.TWO.DiameterDimension.prototype.drawForArc = function(ctx, scale, viewer) {
DiameterDimension.prototype.drawForArc = function(ctx, scale, viewer) {
var r = this.obj.distanceA();
@ -260,7 +265,7 @@ TCAD.TWO.DiameterDimension.prototype.drawForArc = function(ctx, scale, viewer) {
}
}
var vertOff = TCAD.TWO.LinearDimension.getTextOff(viewer.dimScale);
var vertOff = LinearDimension.getTextOff(viewer.dimScale);
var horOff = 5 * viewer.dimScale;
var fontSize = 12 * viewer.dimScale;
@ -288,25 +293,25 @@ TCAD.TWO.DiameterDimension.prototype.drawForArc = function(ctx, scale, viewer) {
ctx.restore();
};
TCAD.TWO.DiameterDimension.prototype.normalDistance = function(aim) {
DiameterDimension.prototype.normalDistance = function(aim) {
return -1;
};
/** @constructor */
TCAD.TWO.AddDimTool = function(viewer, layer, dimCreation) {
function AddDimTool(viewer, layer, dimCreation) {
this.viewer = viewer;
this.layer = layer;
this.dim = null;
this._v = new TCAD.Vector(0, 0, 0);
this._v = new Vector(0, 0, 0);
this.dimCreation = dimCreation;
};
}
TCAD.TWO.AddDimTool.prototype.keydown = function(e) {};
TCAD.TWO.AddDimTool.prototype.keypress = function(e) {};
TCAD.TWO.AddDimTool.prototype.keyup = function(e) {};
TCAD.TWO.AddDimTool.prototype.cleanup = function(e) {};
AddDimTool.prototype.keydown = function(e) {};
AddDimTool.prototype.keypress = function(e) {};
AddDimTool.prototype.keyup = function(e) {};
AddDimTool.prototype.cleanup = function(e) {};
TCAD.TWO.AddDimTool.prototype.mousemove = function(e) {
AddDimTool.prototype.mousemove = function(e) {
var p = this.viewer.screenToModel(e);
this.viewer.snap(p.x, p.y, []);
if (this.dim != null) {
@ -316,7 +321,7 @@ TCAD.TWO.AddDimTool.prototype.mousemove = function(e) {
this.viewer.refresh();
};
TCAD.TWO.AddDimTool.prototype.mouseup = function(e) {
AddDimTool.prototype.mouseup = function(e) {
if (e.button > 0 && this.dim != null) {
this.dim.flip = !this.dim.flip;
@ -333,7 +338,7 @@ TCAD.TWO.AddDimTool.prototype.mouseup = function(e) {
if (this.dim == null) {
this.viewer.historyManager.checkpoint();
this.dim = this.dimCreation(p, new TCAD.TWO.EndPoint(p.x, p.y));
this.dim = this.dimCreation(p, new EndPoint(p.x, p.y));
this.layer.objects.push(this.dim);
this.viewer.refresh();
} else {
@ -343,26 +348,26 @@ TCAD.TWO.AddDimTool.prototype.mouseup = function(e) {
}
};
TCAD.TWO.AddDimTool.prototype.mousedown = function(e) {
AddDimTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddDimTool.prototype.mousewheel = function(e) {
AddDimTool.prototype.mousewheel = function(e) {
};
/** @constructor */
TCAD.TWO.AddCircleDimTool = function(viewer, layer) {
function AddCircleDimTool(viewer, layer) {
this.viewer = viewer;
this.layer = layer;
this.dim = new TCAD.TWO.DiameterDimension(null);
this.dim = new DiameterDimension(null);
this.viewer.add(this.dim, this.layer);
};
}
TCAD.TWO.AddCircleDimTool.prototype.keydown = function(e) {};
TCAD.TWO.AddCircleDimTool.prototype.keypress = function(e) {};
TCAD.TWO.AddCircleDimTool.prototype.keyup = function(e) {};
TCAD.TWO.AddCircleDimTool.prototype.cleanup = function(e) {};
AddCircleDimTool.prototype.keydown = function(e) {};
AddCircleDimTool.prototype.keypress = function(e) {};
AddCircleDimTool.prototype.keyup = function(e) {};
AddCircleDimTool.prototype.cleanup = function(e) {};
TCAD.TWO.AddCircleDimTool.prototype.mousemove = function(e) {
AddCircleDimTool.prototype.mousemove = function(e) {
var p = this.viewer.screenToModel(e);
var objects = this.viewer.search(p.x, p.y, 20 / this.viewer.scale, true, false, []).filter(function(o) {
return o._class === 'TCAD.TWO.Circle' || o._class === 'TCAD.TWO.Arc';
@ -379,7 +384,7 @@ TCAD.TWO.AddCircleDimTool.prototype.mousemove = function(e) {
this.viewer.refresh();
};
TCAD.TWO.AddCircleDimTool.prototype.mouseup = function(e) {
AddCircleDimTool.prototype.mouseup = function(e) {
if (this.dim.obj !== null) {
this.viewer.historyManager.checkpoint();
} else {
@ -388,8 +393,10 @@ TCAD.TWO.AddCircleDimTool.prototype.mouseup = function(e) {
this.viewer.toolManager.releaseControl();
};
TCAD.TWO.AddCircleDimTool.prototype.mousedown = function(e) {
AddCircleDimTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddCircleDimTool.prototype.mousewheel = function(e) {
AddCircleDimTool.prototype.mousewheel = function(e) {
};
export {AddDimTool, AddCircleDimTool, HDimension, VDimension, Dimension, DiameterDimension}

View file

@ -1,11 +1,13 @@
import {EndPoint} from '../viewer2d'
/** @constructor */
TCAD.TWO.AddSegmentTool = function(viewer, multi) {
function AddSegmentTool(viewer, multi) {
this.viewer = viewer;
this.line = null;
this.multi = multi;
};
}
TCAD.TWO.AddSegmentTool.prototype.mousemove = function(e) {
AddSegmentTool.prototype.mousemove = function(e) {
var p = this.viewer.screenToModel(e);
if (this.line != null) {
this.viewer.snap(p.x, p.y, [this.line.a, this.line.b]);
@ -18,18 +20,18 @@ TCAD.TWO.AddSegmentTool.prototype.mousemove = function(e) {
}
};
TCAD.TWO.AddSegmentTool.prototype.cleanup = function(e) {
AddSegmentTool.prototype.cleanup = function(e) {
this.viewer.cleanSnap();
this.line = null;
};
TCAD.TWO.AddSegmentTool.prototype.mousedown = function(e) {
AddSegmentTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddSegmentTool.prototype.mouseup = function(e) {
AddSegmentTool.prototype.mouseup = function(e) {
if (this.line == null) {
var b = this.viewer.screenToModel(e);
const b = this.viewer.screenToModel(e);
var a = b;
var needSnap = false;
if (this.viewer.snapped.length != 0) {
@ -52,7 +54,7 @@ TCAD.TWO.AddSegmentTool.prototype.mouseup = function(e) {
this.viewer.refresh();
}
if (this.multi) {
var b = this.line.b;
const b = this.line.b;
this.line = this.viewer.addSegment(b.x, b.y, b.x, b.y, this.viewer.activeLayer);
this.viewer.parametricManager.linkObjects([this.line.a, b]);
} else {
@ -61,20 +63,20 @@ TCAD.TWO.AddSegmentTool.prototype.mouseup = function(e) {
}
};
TCAD.TWO.AddSegmentTool.prototype.dblclick = function(e) {
AddSegmentTool.prototype.dblclick = function(e) {
this.cancelSegment();
};
TCAD.TWO.AddSegmentTool.prototype.mousewheel = function(e) {
AddSegmentTool.prototype.mousewheel = function(e) {
};
TCAD.TWO.AddSegmentTool.prototype.keydown = function(e) {
AddSegmentTool.prototype.keydown = function(e) {
if (e.keyCode == 27) {
this.cancelSegment();
}
};
TCAD.TWO.AddSegmentTool.prototype.cancelSegment = function() {
AddSegmentTool.prototype.cancelSegment = function() {
if (this.multi && this.line != null) {
this.viewer.remove(this.line);
this.viewer.refresh();
@ -82,38 +84,40 @@ TCAD.TWO.AddSegmentTool.prototype.cancelSegment = function() {
}
};
TCAD.TWO.AddSegmentTool.prototype.keypress = function(e) {};
TCAD.TWO.AddSegmentTool.prototype.keyup = function(e) {};
AddSegmentTool.prototype.keypress = function(e) {};
AddSegmentTool.prototype.keyup = function(e) {};
/** @constructor */
TCAD.TWO.AddPointTool = function(viewer) {
function AddPointTool(viewer) {
this.viewer = viewer;
}
AddPointTool.prototype.mousemove = function(e) {
};
TCAD.TWO.AddPointTool.prototype.mousemove = function(e) {
AddPointTool.prototype.cleanup = function(e) {
};
TCAD.TWO.AddPointTool.prototype.cleanup = function(e) {
AddPointTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddPointTool.prototype.mousedown = function(e) {
};
TCAD.TWO.AddPointTool.prototype.mouseup = function(e) {
AddPointTool.prototype.mouseup = function(e) {
this.viewer.historyManager.checkpoint();
var a = this.viewer.screenToModel(e);
var p = new TCAD.TWO.EndPoint(a.x, a.y);
var p = new EndPoint(a.x, a.y);
var layer = this.viewer.activeLayer;
layer.objects.push(p);
p.layer = layer;
this.viewer.refresh();
};
TCAD.TWO.AddPointTool.prototype.mousewheel = function(e) {
AddPointTool.prototype.mousewheel = function(e) {
};
TCAD.TWO.AddPointTool.prototype.keydown = function(e) {
AddPointTool.prototype.keydown = function(e) {
};
TCAD.TWO.AddSegmentTool.prototype.keypress = function(e) {};
TCAD.TWO.AddSegmentTool.prototype.keyup = function(e) {};
AddSegmentTool.prototype.keypress = function(e) {};
AddSegmentTool.prototype.keyup = function(e) {};
export {AddSegmentTool, AddPointTool}

View file

@ -1,16 +1,24 @@
TCAD.STORAGE_PREFIX = "TCAD.projects.";
import {Viewer} from './viewer2d.js'
import * as ui from '../ui/ui'
import {IO, BBox} from './io'
import {AddDimTool, AddCircleDimTool, HDimension, VDimension, Dimension, DiameterDimension} from './shapes/dim'
import {AddPointTool, AddSegmentTool} from './shapes/segment'
import {AddArcTool} from './shapes/arc'
import {EditCircleTool} from './shapes/circle'
import {FilletTool} from './helpers'
import $ from '../../lib/jquery-2.1.0.min'
/** @constructor */
TCAD.App2D = function() {
function App2D() {
var app = this;
this.viewer = new TCAD.TWO.Viewer(document.getElementById('viewer'));
this.winManager = new TCAD.ui.WinManager();
this.viewer = new Viewer(document.getElementById('viewer'), IO);
this.winManager = new ui.WinManager();
this.initSketchManager();
this._exportWin = new TCAD.ui.Window($('#exportManager'), app.winManager);
this._exportWin = new ui.Window($('#exportManager'), app.winManager);
$('#exportManager li').click(function() {TCAD.ui.closeWin(app._exportWin);});
$('#exportManager li').click(function() {ui.closeWin(app._exportWin);});
this.constraintFilter = {};
this.actions = {};
@ -20,21 +28,21 @@ TCAD.App2D = function() {
var dockEl = $('#dock');
var statusEl = $('#status');
this.dock = new TCAD.ui.Dock(dockEl, statusEl, TCAD.App2D.views);
this.dock = new ui.Dock(dockEl, statusEl, App2D.views);
this.dock.show('Constraints');
var consoleBtn = TCAD.ui.dockBtn('Commands', 'list');
var consoleBtn = ui.dockBtn('Commands', 'list');
statusEl.append(consoleBtn);
var commandsWin = new TCAD.ui.Window($('#commands'), this.winManager);
var commandsWin = new ui.Window($('#commands'), this.winManager);
commandsWin.tileUpRelative = $('#viewer');
consoleBtn.click(function() {
commandsWin.toggle();
});
new TCAD.ui.Terminal(commandsWin, function(command) {
new ui.Terminal(commandsWin, function(command) {
return "Command " + command + " executed";
});
this.winManager.registerResize(dockEl, TCAD.ui.DIRECTIONS.EAST, function() {$('body').trigger('layout'); });
this.winManager.registerResize(dockEl, ui.DIRECTIONS.EAST, function() {$('body').trigger('layout'); });
$('body').on('layout', this.viewer.onWindowResize);
this.registerAction = function(id, desc, action) {
@ -48,7 +56,7 @@ TCAD.App2D = function() {
this.registerAction('open', "Open Sketch", function (e) {
app._sketchesList.refresh();
TCAD.ui.openWin(app._sketchesWin, e);
ui.openWin(app._sketchesWin, e);
});
this.registerAction('clone', "Clone Sketch", function () {
@ -56,15 +64,15 @@ TCAD.App2D = function() {
});
this.registerAction('export', "Export", function (e) {
TCAD.ui.openWin(app._exportWin, e);
ui.openWin(app._exportWin, e);
});
this.registerAction('exportSVG', "Export To SVG", function () {
TCAD.io.exportTextData(app.viewer.io.svgExport(), app.getSketchId() + ".svg");
IO.exportTextData(app.viewer.io.svgExport(), app.getSketchId() + ".svg");
});
this.registerAction('exportDXF', "Export To DXF", function () {
TCAD.io.exportTextData(app.viewer.io.dxfExport(), app.getSketchId() + ".dxf");
IO.exportTextData(app.viewer.io.dxfExport(), app.getSketchId() + ".dxf");
});
this.registerAction('undo', "Undo", function () {
@ -80,23 +88,23 @@ TCAD.App2D = function() {
});
this.registerAction('addPoint', "Add Point", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddPointTool(app.viewer));
app.viewer.toolManager.takeControl(new AddPointTool(app.viewer));
});
this.registerAction('addSegment', "Add Segment", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddSegmentTool(app.viewer, false));
app.viewer.toolManager.takeControl(new AddSegmentTool(app.viewer, false));
});
this.registerAction('addMultiSegment', "Add Multi Segment", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddSegmentTool(app.viewer, true));
app.viewer.toolManager.takeControl(new AddSegmentTool(app.viewer, true));
});
this.registerAction('addArc', "Add Arc", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddArcTool(app.viewer));
app.viewer.toolManager.takeControl(new AddArcTool(app.viewer));
});
this.registerAction('addCircle', "Add Circle", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.EditCircleTool(app.viewer));
app.viewer.toolManager.takeControl(new EditCircleTool(app.viewer));
});
this.registerAction('pan', "Pan", function () {
@ -104,23 +112,23 @@ TCAD.App2D = function() {
});
this.registerAction('addFillet', "Add Fillet", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.FilletTool(app.viewer));
app.viewer.toolManager.takeControl(new FilletTool(app.viewer));
});
this.registerAction('addDim', "Add Dimension", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new TCAD.TWO.Dimension(a,b)} ));
app.viewer.toolManager.takeControl(new AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new Dimension(a,b)} ));
});
this.registerAction('addHDim', "Add Horizontal Dimension", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new TCAD.TWO.HDimension(a,b)} ));
app.viewer.toolManager.takeControl(new AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new HDimension(a,b)} ));
});
this.registerAction('addVDim', "Add Vertical Dimension", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new TCAD.TWO.VDimension(a,b)} ));
app.viewer.toolManager.takeControl(new AddDimTool(app.viewer, app.viewer.dimLayer, function(a,b) {return new VDimension(a,b)} ));
});
this.registerAction('addCircleDim', "Add Circle Dimension", function () {
app.viewer.toolManager.takeControl(new TCAD.TWO.AddCircleDimTool(app.viewer, app.viewer.dimLayer));
app.viewer.toolManager.takeControl(new AddCircleDimTool(app.viewer, app.viewer.dimLayer));
});
this.registerAction('save', "Save", function () {
@ -215,9 +223,9 @@ TCAD.App2D = function() {
app.fit();
app.viewer.refresh();
});
};
}
TCAD.App2D.views = [
App2D.views = [
{
name: 'Dimensions',
icon: 'arrows-v'
@ -232,20 +240,16 @@ TCAD.App2D.views = [
}
];
TCAD.App2D.bottomViews = [
App2D.bottomViews = [
{
name: 'Commands',
icon: 'desktop'
}
];
TCAD.App2D.faBtn = function(iconName) {
return $('<i>', {'class' : 'fa fa-'+iconName});
};
App2D.prototype.fit = function() {
TCAD.App2D.prototype.fit = function() {
var bbox = new TCAD.io.BBox();
var bbox = new BBox();
for (var l = 0; l < this.viewer.layers.length; ++l) {
var layer = this.viewer.layers[l];
@ -263,23 +267,23 @@ TCAD.App2D.prototype.fit = function() {
this.viewer.showBounds(bounds[0], bounds[1], bounds[2], bounds[3]);
};
TCAD.App2D.prototype.cloneSketch = function() {
App2D.prototype.cloneSketch = function() {
var name = prompt("Name for sketch clone");
if (name != null) {
if (this.isSketchExists(name)) {
alert("Sorry, a sketch with the name '" + name + "' already exists. Won't override it.");
return;
}
localStorage.setItem(TCAD.STORAGE_PREFIX + name, this.viewer.io.serializeSketch())
localStorage.setItem(App2D.STORAGE_PREFIX + name, this.viewer.io.serializeSketch())
this.openSketch(name);
}
};
TCAD.App2D.prototype.isSketchExists = function(name) {
return localStorage.getItem(TCAD.STORAGE_PREFIX + name) != null;
App2D.prototype.isSketchExists = function(name) {
return localStorage.getItem(App2D.STORAGE_PREFIX + name) != null;
};
TCAD.App2D.prototype.openSketch = function(name) {
App2D.prototype.openSketch = function(name) {
var uri = window.location.href.split("#")[0];
if (name !== "untitled") {
uri += "#" + name;
@ -288,7 +292,7 @@ TCAD.App2D.prototype.openSketch = function(name) {
win.focus();
};
TCAD.App2D.prototype.newSketch = function() {
App2D.prototype.newSketch = function() {
var name = prompt("Name for sketch");
if (name != null) {
if (this.isSketchExists(name)) {
@ -299,18 +303,18 @@ TCAD.App2D.prototype.newSketch = function() {
}
};
TCAD.App2D.prototype.initSketchManager = function(data, ext) {
this._sketchesWin = new TCAD.ui.Window($('#sketchManager'), this.winManager);
App2D.prototype.initSketchManager = function(data, ext) {
this._sketchesWin = new ui.Window($('#sketchManager'), this.winManager);
var app = this;
var sketchesList = new TCAD.ui.List('sketchList', {
var sketchesList = new ui.List('sketchList', {
items : function() {
var theItems = [];
for (var name in localStorage) {
if (!localStorage.hasOwnProperty(name)) {
continue;
}
if (name.indexOf(TCAD.STORAGE_PREFIX) === 0) {
name = name.substring(TCAD.STORAGE_PREFIX.length);
if (name.indexOf(App2D.STORAGE_PREFIX) === 0) {
name = name.substring(App2D.STORAGE_PREFIX.length);
}
theItems.push({name : name});
}
@ -319,7 +323,7 @@ TCAD.App2D.prototype.initSketchManager = function(data, ext) {
remove : function(item) {
if (confirm("Selected sketch will be REMOVED! Are you sure?")) {
localStorage.removeItem(TCAD.STORAGE_PREFIX + item.name);
localStorage.removeItem(App2D.STORAGE_PREFIX + item.name);
sketchesList.refresh();
}
},
@ -336,7 +340,7 @@ TCAD.App2D.prototype.initSketchManager = function(data, ext) {
this._sketchesList = sketchesList;
};
TCAD.App2D.prototype.loadFromLocalStorage = function() {
App2D.prototype.loadFromLocalStorage = function() {
var sketchId = this.getSketchId();
var sketchData = localStorage.getItem(sketchId);
if (sketchData != null) {
@ -346,10 +350,14 @@ TCAD.App2D.prototype.loadFromLocalStorage = function() {
this.viewer.repaint();
};
TCAD.App2D.prototype.getSketchId = function() {
App2D.prototype.getSketchId = function() {
var id = window.location.hash.substring(1);
if (!id) {
id = "untitled";
}
return TCAD.STORAGE_PREFIX + id;
return App2D.STORAGE_PREFIX + id;
};
App2D.STORAGE_PREFIX = "TCAD.projects.";
export default App2D;

View file

@ -1,8 +1,12 @@
TCAD = {
TWO : {}
};
import {Parameters, Bus} from '../ui/toolkit'
import {ParametricManager} from './parametric'
import {HistoryManager} from './history'
import Vector from '../math/vector'
import {optim} from '../math/optim'
import * as utils from '../utils/utils'
import * as math from '../math/math'
TCAD.TWO.Styles = {
var Styles = {
DEFAULT : {
lineWidth : 2,
strokeStyle : "#ffffff",
@ -46,40 +50,30 @@ TCAD.TWO.Styles = {
}
};
TCAD.TWO.utils = {};
TCAD.TWO.utils.extend = function(func, parent) {
for(var prop in parent.prototype) {
if(parent.prototype.hasOwnProperty(prop))
func.prototype[prop] = parent.prototype[prop];
}
};
TCAD.TWO.utils.point = function(x, y){ return {x: x, y: y} };
TCAD.TWO.utils.drawPoint = function (ctx, x, y, rad, scale) {
function _drawPoint(ctx, x, y, rad, scale) {
ctx.beginPath();
ctx.arc(x, y, rad / scale, 0, 2 * Math.PI, false);
ctx.fill();
};
}
TCAD.TWO.utils.setStyle = function(style, ctx, scale) {
function setStyle(style, ctx, scale) {
ctx.lineWidth = style.lineWidth / scale;
ctx.strokeStyle = style.strokeStyle;
ctx.fillStyle = style.fillStyle;
};
}
/** @constructor */
TCAD.TWO.Viewer = function(canvas) {
function Viewer(canvas, IO) {
this.canvas = canvas;
this.params = new TCAD.Parameters();
this.io = new TCAD.IO(this);
this.params = new Parameters();
this.io = new IO(this);
var viewer = this;
this.retinaPxielRatio = window.devicePixelRatio > 1 ? window.devicePixelRatio : 1;
function updateCanvasSize() {
var canvasWidth = canvas.parentNode.offsetWidth;;
var canvasHeight = canvas.parentNode.offsetHeight;;
var canvasWidth = canvas.parentNode.offsetWidth;
var canvasHeight = canvas.parentNode.offsetHeight;
canvas.width = canvasWidth * viewer.retinaPxielRatio;
canvas.height = canvasHeight * viewer.retinaPxielRatio;
@ -100,19 +94,19 @@ TCAD.TWO.Viewer = function(canvas) {
set: viewer.setActiveLayer
});
this.bus = new TCAD.Bus();
this.bus = new Bus();
this.ctx = this.canvas.getContext("2d");
this._activeLayer = null;
this.layers = [];
this._serviceLayers = [];
this.dimLayer = new TCAD.TWO.Layer("_dim", TCAD.TWO.Styles.DIM);
this.dimLayer = new Layer("_dim", Styles.DIM);
this.dimLayers = [this.dimLayer];
this.bus.defineObservable(this, 'dimScale', 'dimScale', 1);
this.bus.subscribe('dimScale', function(){ viewer.refresh(); });
this._workspace = [this.dimLayers, this.layers, this._serviceLayers];
this.toolManager = new TCAD.TWO.ToolManager(this, new TCAD.TWO.PanTool(this));
this.parametricManager = new TCAD.TWO.ParametricManager(this);
this.toolManager = new ToolManager(this, new PanTool(this));
this.parametricManager = new ParametricManager(this);
this.translate = {x : 0.0, y : 0.0};
this.scale = 1.0;
@ -122,11 +116,11 @@ TCAD.TWO.Viewer = function(canvas) {
this._setupServiceLayer();
this.historyManager = new TCAD.HistoryManager(this);
this.historyManager = new HistoryManager(this);
this.refresh();
};
}
TCAD.TWO.Viewer.prototype.validateGeom = function() {
Viewer.prototype.validateGeom = function() {
for (var i = 0; i < this.layers.length; i++) {
var objs = this.layers[i].objects;
for (var j = 0; j < objs.length; j++) {
@ -138,16 +132,16 @@ TCAD.TWO.Viewer.prototype.validateGeom = function() {
return true;
};
TCAD.TWO.Viewer.prototype.addSegment = function(x1, y1, x2, y2, layer) {
var a = new TCAD.TWO.EndPoint(x1, y1);
var b = new TCAD.TWO.EndPoint(x2, y2);
var line = new TCAD.TWO.Segment(a, b);
Viewer.prototype.addSegment = function(x1, y1, x2, y2, layer) {
var a = new EndPoint(x1, y1);
var b = new EndPoint(x2, y2);
var line = new Segment(a, b);
layer.objects.push(line);
line.layer = layer;
return line;
};
TCAD.TWO.Viewer.prototype.remove = function(obj) {
Viewer.prototype.remove = function(obj) {
if (obj.layer != null) {
var idx = obj.layer.objects.indexOf(obj);
if (idx != -1) {
@ -157,17 +151,17 @@ TCAD.TWO.Viewer.prototype.remove = function(obj) {
}
};
TCAD.TWO.Viewer.prototype.add = function(obj, layer) {
Viewer.prototype.add = function(obj, layer) {
layer.objects.push(obj);
obj.layer = layer;
};
TCAD.TWO.Viewer.prototype.search = function(x, y, buffer, deep, onlyPoints, filter) {
Viewer.prototype.search = function(x, y, buffer, deep, onlyPoints, filter) {
buffer *= 0.5;
var pickResult = [];
var aim = new TCAD.Vector(x, y);
var aim = new Vector(x, y);
var heroIdx = 0;
var unreachable = buffer * 2;
@ -214,26 +208,26 @@ TCAD.TWO.Viewer.prototype.search = function(x, y, buffer, deep, onlyPoints, filt
return pickResult;
};
TCAD.TWO.Viewer.prototype._setupServiceLayer = function() {
var layer = new TCAD.TWO.Layer("_service", TCAD.TWO.Styles.SERVICE);
// layer.objects.push(new TCAD.TWO.CrossHair(0, 0, 20));
layer.objects.push(new TCAD.TWO.BasisOrigin(null, this));
layer.objects.push(new TCAD.TWO.Point(0, 0, 2));
Viewer.prototype._setupServiceLayer = function() {
var layer = new Layer("_service", Styles.SERVICE);
// layer.objects.push(new CrossHair(0, 0, 20));
layer.objects.push(new BasisOrigin(null, this));
layer.objects.push(new Point(0, 0, 2));
this._serviceLayers.push(layer);
layer = new TCAD.TWO.Layer("_selection", TCAD.TWO.Styles.DEFAULT);
layer = new Layer("_selection", Styles.DEFAULT);
layer.objects = this.selected;
this._serviceLayers.push(layer);
};
TCAD.TWO.Viewer.prototype.refresh = function() {
Viewer.prototype.refresh = function() {
var viewer = this;
window.requestAnimationFrame( function() {
viewer.repaint();
});
};
TCAD.TWO.Viewer.prototype.repaint = function() {
Viewer.prototype.repaint = function() {
var ctx = this.ctx;
ctx.setTransform(1, 0, 0, 1, 0, 0);
@ -255,32 +249,32 @@ TCAD.TWO.Viewer.prototype.repaint = function() {
for (var o = 0; o < layer.objects.length; o++) {
var obj = layer.objects[o];
style = obj.style != null ? obj.style : layer.style;
if (style != prevStyle) TCAD.TWO.utils.setStyle(style, ctx, this.scale / this.retinaPxielRatio);
if (style != prevStyle) setStyle(style, ctx, this.scale / this.retinaPxielRatio);
obj.draw(ctx, this.scale / this.retinaPxielRatio, this);
}
}
}
};
TCAD.TWO.Viewer.prototype.snap = function(x, y, excl) {
Viewer.prototype.snap = function(x, y, excl) {
this.cleanSnap();
var snapTo = this.search(x, y, 20 / this.scale, true, true, excl);
if (snapTo.length > 0) {
snapTo = snapTo[0];
this.mark(snapTo, TCAD.TWO.Styles.SNAP);
this.mark(snapTo, Styles.SNAP);
this.snapped.push(snapTo);
return snapTo;
}
return null;
};
TCAD.TWO.Viewer.prototype.cleanSnap = function() {
Viewer.prototype.cleanSnap = function() {
while(this.snapped.length > 0) {
this.snapped.pop().marked = null;
}
};
TCAD.TWO.Viewer.prototype.showBounds = function(x1, y1, x2, y2, offset) {
Viewer.prototype.showBounds = function(x1, y1, x2, y2, offset) {
var dx = x2 - x1;
var dy = y2 - y1;
if (this.canvas.width > this.canvas.height) {
@ -292,7 +286,7 @@ TCAD.TWO.Viewer.prototype.showBounds = function(x1, y1, x2, y2, offset) {
this.translate.y = -y1 * this.scale;
};
TCAD.TWO.Viewer.prototype.screenToModel2 = function(x, y, out) {
Viewer.prototype.screenToModel2 = function(x, y, out) {
out.x = x * this.retinaPxielRatio;
out.y = this.canvas.height - y * this.retinaPxielRatio;
@ -304,17 +298,17 @@ TCAD.TWO.Viewer.prototype.screenToModel2 = function(x, y, out) {
out.y /= this.scale;
};
TCAD.TWO.Viewer.prototype.screenToModel = function(e) {
Viewer.prototype.screenToModel = function(e) {
return this._screenToModel(e.offsetX, e.offsetY);
};
TCAD.TWO.Viewer.prototype._screenToModel = function(x, y) {
Viewer.prototype._screenToModel = function(x, y) {
var out = {x: 0, y: 0};
this.screenToModel2(x, y, out);
return out;
};
TCAD.TWO.Viewer.prototype.accept = function(visitor) {
Viewer.prototype.accept = function(visitor) {
for (var i = 0; i < this.layers.length; i++) {
var objs = this.layers[i].objects;
var result = null;
@ -326,7 +320,7 @@ TCAD.TWO.Viewer.prototype.accept = function(visitor) {
}
};
TCAD.TWO.Viewer.prototype.findLayerByName = function(name) {
Viewer.prototype.findLayerByName = function(name) {
for (var i = 0; i < this.layers.length; i++) {
if (this.layers[i].name == name) {
return this.layers[i];
@ -335,7 +329,7 @@ TCAD.TWO.Viewer.prototype.findLayerByName = function(name) {
return null;
};
TCAD.TWO.Viewer.prototype.findById = function(id) {
Viewer.prototype.findById = function(id) {
var result = null;
this.accept(function(o) {
if (o.id === id) {
@ -347,27 +341,27 @@ TCAD.TWO.Viewer.prototype.findById = function(id) {
return result;
};
TCAD.TWO.Viewer.prototype.select = function(objs, exclusive) {
Viewer.prototype.select = function(objs, exclusive) {
if (exclusive) this.deselectAll();
for (var i = 0; i < objs.length; i++) {
this.mark(objs[i]);
}
};
TCAD.TWO.Viewer.prototype.pick = function(e) {
Viewer.prototype.pick = function(e) {
var m = this.screenToModel(e);
return this.search(m.x, m.y, 20 / this.scale, true, false, []);
};
TCAD.TWO.Viewer.prototype.mark = function(obj, style) {
Viewer.prototype.mark = function(obj, style) {
if (style === undefined) {
style = TCAD.TWO.Styles.MARK;
style = Styles.MARK;
}
obj.marked = style;
this.selected.push(obj);
};
TCAD.TWO.Viewer.prototype.getActiveLayer = function() {
Viewer.prototype.getActiveLayer = function() {
var layer = this._activeLayer;
if (layer == null || layer.readOnly) {
layer = null;
@ -380,20 +374,20 @@ TCAD.TWO.Viewer.prototype.getActiveLayer = function() {
}
}
if (layer == null) {
layer = new TCAD.TWO.Layer("JustALayer", TCAD.TWO.Styles.DEFAULT);
layer = new Layer("JustALayer", Styles.DEFAULT);
this.layers.push(layer);
}
return layer;
};
TCAD.TWO.Viewer.prototype.setActiveLayer = function(layer) {
Viewer.prototype.setActiveLayer = function(layer) {
if (!layer.readOnly) {
this._activeLayer = layer;
this.bus.notify("activeLayer");
}
};
TCAD.TWO.Viewer.prototype.deselect = function(obj) {
Viewer.prototype.deselect = function(obj) {
for (var i = 0; i < this.selected.length; i++) {
if (obj.id == this.selected[i].id) {
this.selected.splice(i, 1)[0].marked = null;
@ -402,7 +396,7 @@ TCAD.TWO.Viewer.prototype.deselect = function(obj) {
}
};
TCAD.TWO.Viewer.prototype.deselectAll = function() {
Viewer.prototype.deselectAll = function() {
for (var i = 0; i < this.selected.length; i++) {
this.selected[i].marked = null;
}
@ -410,25 +404,25 @@ TCAD.TWO.Viewer.prototype.deselectAll = function() {
};
/** @constructor */
TCAD.TWO.Layer = function(name, style) {
function Layer(name, style) {
this.name = name;
this.style = style;
this.objects = [];
this.readOnly = false; // This is actually a mark for boundary layers coming from 3D
};
}
TCAD.TWO.Viewer.prototype.fullHeavyUIRefresh = function() {
Viewer.prototype.fullHeavyUIRefresh = function() {
this.refresh();
this.parametricManager.notify();
};
/** @constructor */
TCAD.TWO.Polygon = function(points) {
function Polygon(points) {
this.points = points;
this.style = null;
};
}
TCAD.TWO.Polygon.prototype.draw = function(ctx) {
Polygon.prototype.draw = function(ctx) {
if (this.points.length < 3) {
return;
@ -446,12 +440,12 @@ TCAD.TWO.Polygon.prototype.draw = function(ctx) {
};
/** @constructor */
TCAD.TWO.Polyline = function(points) {
function Polyline(points) {
this.points = points;
this.style = null;
};
}
TCAD.TWO.Polyline.prototype.draw = function(ctx) {
Polyline.prototype.draw = function(ctx) {
if (this.points.length < 2) {
return;
@ -466,28 +460,32 @@ TCAD.TWO.Polyline.prototype.draw = function(ctx) {
ctx.stroke();
};
TCAD.TWO.utils.ID_COUNTER = 0;
TCAD.TWO.utils.genID = function() {
return TCAD.TWO.utils.ID_COUNTER ++;
};
var ID_COUNTER = 0;
/** @constructor */
TCAD.TWO.SketchObject = function() {
this.id = TCAD.TWO.utils.genID();
function SketchObject() {
this.id = SketchObject.genID();
this.aux = false;
this.marked = null;
this.visible = true;
this.children = [];
this.linked = [];
this.layer = null;
}
SketchObject.genID = function() {
return ID_COUNTER ++;
};
TCAD.TWO.SketchObject.prototype.accept = function(visitor) {
SketchObject.resetIDGenerator = function(value) {
ID_COUNTER = value;
};
SketchObject.prototype.accept = function(visitor) {
return this.acceptV(false, visitor);
};
TCAD.TWO.SketchObject.prototype.acceptV = function(onlyVisible, visitor) {
SketchObject.prototype.acceptV = function(onlyVisible, visitor) {
if (onlyVisible && !this.visible) return true;
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
@ -498,18 +496,18 @@ TCAD.TWO.SketchObject.prototype.acceptV = function(onlyVisible, visitor) {
return visitor(this);
};
TCAD.TWO.SketchObject.prototype.validate = function() {
SketchObject.prototype.validate = function() {
return true;
};
TCAD.TWO.SketchObject.prototype.recover = function() {
SketchObject.prototype.recover = function() {
};
TCAD.TWO.SketchObject.prototype.getDefaultTool = function(viewer) {
return new TCAD.TWO.DragTool(this, viewer);
SketchObject.prototype.getDefaultTool = function(viewer) {
return new DragTool(this, viewer);
};
TCAD.TWO.SketchObject.prototype.isAuxOrLinkedTo = function() {
SketchObject.prototype.isAuxOrLinkedTo = function() {
if (!!this.aux) {
return true;
}
@ -521,7 +519,7 @@ TCAD.TWO.SketchObject.prototype.isAuxOrLinkedTo = function() {
return false;
};
TCAD.TWO.SketchObject.prototype._translate = function(dx, dy, translated) {
SketchObject.prototype._translate = function(dx, dy, translated) {
translated[this.id] = 'x';
for (var i = 0; i < this.linked.length; ++i) {
if (translated[this.linked[i].id] != 'x') {
@ -531,7 +529,7 @@ TCAD.TWO.SketchObject.prototype._translate = function(dx, dy, translated) {
this.translateImpl(dx, dy);
};
TCAD.TWO.SketchObject.prototype.translate = function(dx, dy) {
SketchObject.prototype.translate = function(dx, dy) {
// this.translateImpl(dx, dy);
if (this.isAuxOrLinkedTo()) {
return;
@ -539,11 +537,11 @@ TCAD.TWO.SketchObject.prototype.translate = function(dx, dy) {
this._translate(dx, dy, {});
};
TCAD.TWO.SketchObject.prototype.draw = function(ctx, scale, viewer) {
SketchObject.prototype.draw = function(ctx, scale, viewer) {
if (!this.visible) return;
if (this.marked != null) {
ctx.save();
TCAD.TWO.utils.setStyle(this.marked, ctx, scale);
setStyle(this.marked, ctx, scale);
}
this.drawImpl(ctx, scale, viewer);
if (this.marked != null) ctx.restore();
@ -553,89 +551,89 @@ TCAD.TWO.SketchObject.prototype.draw = function(ctx, scale, viewer) {
};
/** @constructor */
TCAD.TWO.Ref = function(value) {
this.id = TCAD.TWO.utils.genID();
function Ref(value) {
this.id = SketchObject.genID();
this.value = value;
}
Ref.prototype.set = function(value) {
this.value = value;
};
TCAD.TWO.Ref.prototype.set = function(value) {
this.value = value;
};
TCAD.TWO.Ref.prototype.get = function() {
Ref.prototype.get = function() {
return this.value;
};
/** @constructor */
TCAD.TWO.Param = function(obj, prop) {
this.id = TCAD.TWO.utils.genID();
function Param(obj, prop) {
this.id = SketchObject.genID();
this.obj = obj;
this.prop = prop;
};
}
TCAD.TWO.Param.prototype.set = function(value) {
Param.prototype.set = function(value) {
this.obj[this.prop] = value;
};
TCAD.TWO.Param.prototype.get = function() {
Param.prototype.get = function() {
return this.obj[this.prop];
};
/** @constructor */
TCAD.TWO.EndPoint = function(x, y) {
TCAD.TWO.SketchObject.call(this);
function EndPoint(x, y) {
SketchObject.call(this);
this.x = x;
this.y = y;
this.parent = null;
this._x = new TCAD.TWO.Param(this, 'x');
this._y = new TCAD.TWO.Param(this, 'y');
};
this._x = new Param(this, 'x');
this._y = new Param(this, 'y');
}
TCAD.TWO.utils.extend(TCAD.TWO.EndPoint, TCAD.TWO.SketchObject);
utils.extend(EndPoint, SketchObject);
TCAD.TWO.EndPoint.prototype._class = 'TCAD.TWO.EndPoint';
EndPoint.prototype._class = 'TCAD.TWO.EndPoint';
TCAD.TWO.EndPoint.prototype.collectParams = function(params) {
EndPoint.prototype.collectParams = function(params) {
params.push(this._x);
params.push(this._y);
};
TCAD.TWO.EndPoint.prototype.normalDistance = function(aim) {
return aim.minus(new TCAD.Vector(this.x, this.y)).length();
EndPoint.prototype.normalDistance = function(aim) {
return aim.minus(new Vector(this.x, this.y)).length();
};
TCAD.TWO.EndPoint.prototype.getReferencePoint = function() {
EndPoint.prototype.getReferencePoint = function() {
return this;
};
TCAD.TWO.EndPoint.prototype.translateImpl = function(dx, dy) {
EndPoint.prototype.translateImpl = function(dx, dy) {
this.x += dx;
this.y += dy;
};
TCAD.TWO.EndPoint.prototype.drawImpl = function(ctx, scale) {
TCAD.TWO.utils.drawPoint(ctx, this.x, this.y, 3, scale)
EndPoint.prototype.drawImpl = function(ctx, scale) {
_drawPoint(ctx, this.x, this.y, 3, scale)
};
/** @constructor */
TCAD.TWO.Segment = function(a, b) {
TCAD.TWO.SketchObject.call(this);
function Segment(a, b) {
SketchObject.call(this);
this.a = a;
this.b = b;
a.parent = this;
b.parent = this;
this.children.push(a, b);
}
utils.extend(Segment, SketchObject);
Segment.prototype._class = 'TCAD.TWO.Segment';
Segment.prototype.validate = function() {
return math.distanceAB(this.a, this.b) > math.TOLERANCE;
};
TCAD.TWO.utils.extend(TCAD.TWO.Segment, TCAD.TWO.SketchObject);
TCAD.TWO.Segment.prototype._class = 'TCAD.TWO.Segment';
TCAD.TWO.Segment.prototype.validate = function() {
return TCAD.math.distanceAB(this.a, this.b) > TCAD.TOLERANCE;
};
TCAD.TWO.Segment.prototype.recover = function() {
Segment.prototype.recover = function() {
var recoverLength = 100;
this.a.x -= recoverLength;
this.a.y -= recoverLength;
@ -643,18 +641,18 @@ TCAD.TWO.Segment.prototype.recover = function() {
this.b.y += recoverLength;
};
TCAD.TWO.Segment.prototype.collectParams = function(params) {
Segment.prototype.collectParams = function(params) {
this.a.collectParams(params);
this.b.collectParams(params);
};
TCAD.TWO.Segment.prototype.normalDistance = function(aim) {
Segment.prototype.normalDistance = function(aim) {
var x = aim.x;
var y = aim.y;
var ab = new TCAD.Vector(this.b.x - this.a.x, this.b.y - this.a.y)
var ab = new Vector(this.b.x - this.a.x, this.b.y - this.a.y)
var e = ab.normalize();
var a = new TCAD.Vector(aim.x - this.a.x, aim.y - this.a.y);
var a = new Vector(aim.x - this.a.x, aim.y - this.a.y);
var b = e.multiply(a.dot(e));
var n = a.minus(b);
@ -670,16 +668,16 @@ TCAD.TWO.Segment.prototype.normalDistance = function(aim) {
return n.length();
};
TCAD.TWO.Segment.prototype.getReferencePoint = function() {
Segment.prototype.getReferencePoint = function() {
return this.a;
};
TCAD.TWO.Segment.prototype.translateImpl = function(dx, dy) {
Segment.prototype.translateImpl = function(dx, dy) {
this.a.translate(dx, dy);
this.b.translate(dx, dy);
};
TCAD.TWO.Segment.prototype.drawImpl = function(ctx, scale) {
Segment.prototype.drawImpl = function(ctx, scale) {
ctx.beginPath();
ctx.moveTo(this.a.x, this.a.y);
ctx.lineTo(this.b.x, this.b.y);
@ -690,26 +688,26 @@ TCAD.TWO.Segment.prototype.drawImpl = function(ctx, scale) {
};
/** @constructor */
TCAD.TWO.Point = function(x, y, rad) {
function Point(x, y, rad) {
this.x = x;
this.y = y;
this.rad = rad;
this.style = null;
};
}
TCAD.TWO.Point.prototype.draw = function(ctx, scale) {
TCAD.TWO.utils.drawPoint(ctx, this.x, this.y, this.rad, scale);
Point.prototype.draw = function(ctx, scale) {
_drawPoint(ctx, this.x, this.y, this.rad, scale);
};
/** @constructor */
TCAD.TWO.CrossHair = function(x, y, rad) {
function CrossHair(x, y, rad) {
this.x = x;
this.y = y;
this.rad = rad;
this.style = null;
};
}
TCAD.TWO.CrossHair.prototype.draw = function(ctx, scale) {
CrossHair.prototype.draw = function(ctx, scale) {
ctx.beginPath();
var rad = this.rad / scale;
ctx.moveTo(this.x - rad, this.y);
@ -726,16 +724,16 @@ TCAD.TWO.CrossHair.prototype.draw = function(ctx, scale) {
};
/** @constructor */
TCAD.TWO.BasisOrigin = function(basis, viewer) {
function BasisOrigin(basis, viewer) {
this.viewer = viewer;
this.inverseX = false;
this.inverseY = false;
this.lineWidth = 100;
this.xColor = '#FF0000';
this.yColor = '#00FF00';
};
}
TCAD.TWO.BasisOrigin.prototype.draw = function(ctx, scale) {
BasisOrigin.prototype.draw = function(ctx, scale) {
ctx.save();
if (this.inverseX) {
this.xScale = -1;
@ -789,7 +787,7 @@ TCAD.TWO.BasisOrigin.prototype.draw = function(ctx, scale) {
};
/** @constructor */
TCAD.TWO.ToolManager = function(viewer, defaultTool) {
function ToolManager(viewer, defaultTool) {
this.defaultTool = defaultTool;
this.tool = defaultTool;
var canvas = viewer.canvas;
@ -841,35 +839,35 @@ TCAD.TWO.ToolManager = function(viewer, defaultTool) {
window.addEventListener("keyup", function (e) {
tm.getTool().keydown(e);
}, false);
};
}
TCAD.TWO.ToolManager.prototype.takeControl = function(tool) {
ToolManager.prototype.takeControl = function(tool) {
this.tool = tool;
};
TCAD.TWO.ToolManager.prototype.releaseControl = function() {
ToolManager.prototype.releaseControl = function() {
this.tool.cleanup();
this.tool = this.defaultTool;
};
TCAD.TWO.ToolManager.prototype.getTool = function() {
ToolManager.prototype.getTool = function() {
return this.tool;
};
/** @constructor */
TCAD.TWO.PanTool = function(viewer) {
function PanTool(viewer) {
this.viewer = viewer;
this.dragging = false;
this.x = 0.0;
this.y = 0.0;
};
}
TCAD.TWO.PanTool.prototype.keydown = function(e) {};
TCAD.TWO.PanTool.prototype.keypress = function(e) {};
TCAD.TWO.PanTool.prototype.keyup = function(e) {};
TCAD.TWO.PanTool.prototype.cleanup = function(e) {};
PanTool.prototype.keydown = function(e) {};
PanTool.prototype.keypress = function(e) {};
PanTool.prototype.keyup = function(e) {};
PanTool.prototype.cleanup = function(e) {};
TCAD.TWO.PanTool.prototype.mousemove = function(e) {
PanTool.prototype.mousemove = function(e) {
if (!this.dragging) {
return;
}
@ -886,14 +884,16 @@ TCAD.TWO.PanTool.prototype.mousemove = function(e) {
this.viewer.refresh();
};
TCAD.TWO.PanTool.prototype.mousedown = function(e) {
PanTool.prototype.mousedown = function(e) {
if (e.button == 0) {
var picked = this.viewer.pick(e);
var i;
if (picked.length > 0) {
var toSelect;
if (e.shiftKey) {
var toSelect = picked[0];
toSelect = picked[0];
var ids = this.viewer.selected.map(function(s){return s.id});
for (var i = 0; i < picked.length; i++) {
for (i = 0; i < picked.length; i++) {
if (ids.indexOf(picked[i].id) != -1) {
this.viewer.deselect(picked[i]);
} else {
@ -903,9 +903,9 @@ TCAD.TWO.PanTool.prototype.mousedown = function(e) {
this.viewer.select([toSelect], false);
this.deselectOnUp = false;
} else {
var toSelect = picked[0];
toSelect = picked[0];
if (this.viewer.selected.length === 1) {
for (var i = 0; i < picked.length - 1; i++) {
for (i = 0; i < picked.length - 1; i++) {
if (picked[i].id == this.viewer.selected[0].id) {
toSelect = picked[i + 1];
break;
@ -930,7 +930,7 @@ TCAD.TWO.PanTool.prototype.mousedown = function(e) {
this.y = e.pageY;
};
TCAD.TWO.PanTool.prototype.mouseup = function(e) {
PanTool.prototype.mouseup = function(e) {
this.dragging = false;
if (this.deselectOnUp) {
this.viewer.deselectAll();
@ -939,7 +939,7 @@ TCAD.TWO.PanTool.prototype.mouseup = function(e) {
this.deselectOnUp = false;
};
TCAD.TWO.PanTool.prototype.mousewheel = function(e) {
PanTool.prototype.mousewheel = function(e) {
var delta = 0;
@ -967,21 +967,21 @@ TCAD.TWO.PanTool.prototype.mousewheel = function(e) {
};
/** @constructor */
TCAD.TWO.DragTool = function(obj, viewer) {
function DragTool(obj, viewer) {
this.obj = obj;
this.viewer = viewer;
this._point = {x: 0, y: 0};
this.origin = {x: 0, y: 0};
this.ref = this.obj.getReferencePoint();
this.solver = null;
};
TCAD.TWO.DragTool.prototype.snapshots = []
TCAD.TWO.DragTool.prototype.keydown = function(e) {};
TCAD.TWO.DragTool.prototype.keypress = function(e) {};
TCAD.TWO.DragTool.prototype.keyup = function(e) {};
TCAD.TWO.DragTool.prototype.cleanup = function(e) {};
}
DragTool.prototype.snapshots = []
DragTool.prototype.keydown = function(e) {};
DragTool.prototype.keypress = function(e) {};
DragTool.prototype.keyup = function(e) {};
DragTool.prototype.cleanup = function(e) {};
TCAD.TWO.DragTool.prototype.mousemove = function(e) {
DragTool.prototype.mousemove = function(e) {
var x = this._point.x;
var y = this._point.y;
this.viewer.screenToModel2(e.offsetX, e.offsetY, this._point);
@ -993,7 +993,7 @@ TCAD.TWO.DragTool.prototype.mousemove = function(e) {
}
this.solver.updateLock(this.lockedValues);
if (!e.altKey && !e.ctrlKey) {
this.solveRequest(true);
this.solveRequest(true);
} else {
this.obj.translate(dx, dy);
}
@ -1001,28 +1001,28 @@ TCAD.TWO.DragTool.prototype.mousemove = function(e) {
this.viewer.refresh();
};
TCAD.TWO.DragTool.prototype.mousedown = function(e) {
DragTool.prototype.mousedown = function(e) {
this.origin.x = e.offsetX;
this.origin.y = e.offsetY;
this.viewer.screenToModel2(e.offsetX, e.offsetY, this._point);
this.prepareSolver([]);
};
TCAD.TWO.DragTool.prototype.mouseup = function(e) {
DragTool.prototype.mouseup = function(e) {
this.solveRequest(false);
this.viewer.refresh();
this.viewer.toolManager.releaseControl();
var traveled = TCAD.math.distance(this.origin.x, this.origin.y, e.offsetX, e.offsetY);
var traveled = math.distance(this.origin.x, this.origin.y, e.offsetX, e.offsetY);
if (traveled >= 10) {
this.viewer.historyManager.lightCheckpoint(10);
}
//this.animateSolution();
};
TCAD.TWO.DragTool.prototype.mousewheel = function(e) {
DragTool.prototype.mousewheel = function(e) {
};
TCAD.TWO.DragTool.prototype.solveRequest = function(rough) {
DragTool.prototype.solveRequest = function(rough) {
this.solver.solve(rough, 1);
this.solver.sync();
@ -1044,10 +1044,10 @@ TCAD.TWO.DragTool.prototype.solveRequest = function(rough) {
}
};
TCAD.TWO.DragTool.prototype.getParamsToLock = function() {
DragTool.prototype.getParamsToLock = function() {
var params = [];
this.obj.accept(function(obj) {
if (obj._class === 'TCAD.TWO.EndPoint') {
if (obj._class === 'TCAD.TWO.EndPoint' && !obj.isAuxOrLinkedTo()) {
params.push(obj._x);
params.push(obj._y);
}
@ -1056,7 +1056,7 @@ TCAD.TWO.DragTool.prototype.getParamsToLock = function() {
return params;
};
TCAD.TWO.DragTool.prototype.prepareSolver = function(extraConstraints) {
DragTool.prototype.prepareSolver = function(extraConstraints) {
var locked = this.getParamsToLock();
this.lockedShifts = [];
this.lockedValues = [];
@ -1068,7 +1068,7 @@ TCAD.TWO.DragTool.prototype.prepareSolver = function(extraConstraints) {
//this.enableRecording();
};
TCAD.TWO.DragTool.prototype.enableRecording = function() {
DragTool.prototype.enableRecording = function() {
var solver = this.solver;
var snapshots = this.snapshots = [];
optim.DEBUG_HANDLER = function() {
@ -1080,7 +1080,7 @@ TCAD.TWO.DragTool.prototype.enableRecording = function() {
};
};
TCAD.TWO.DragTool.prototype.animateSolution = function() {
DragTool.prototype.animateSolution = function() {
if (this.snapshots.length === 0) return;
var stepNum = 0;
var scope = this;
@ -1110,4 +1110,6 @@ TCAD.TWO.DragTool.prototype.animateSolution = function() {
}
}
window.requestAnimationFrame(step);
};
};
export {Styles, Viewer, Layer, SketchObject, EndPoint, Point, Segment, ToolManager, PanTool, DragTool, Ref}

View file

@ -1,2 +0,0 @@
TCAD.test.fixtures = {};
TCAD.test.fixtures.RoundRect = {"layers":[{"name":"_dim","data":[]},{"name":"default","data":[{"id":6,"_class":"TCAD.TWO.Segment","points":[[0,[1,266.5634479999531],[2,794.5807272294047]],[3,[4,776.6236240728185],[5,794.5807272294039]]]},{"id":13,"_class":"TCAD.TWO.Segment","points":[[7,[8,927.2879843119589],[9,643.9224734815724]],[10,[11,927.2879843120583],[12,174.51664392112346]]]},{"id":20,"_class":"TCAD.TWO.Segment","points":[[14,[15,266.5475645170609],[16,23.8639268074262]],[17,[18,776.6354356426971],[19,23.863926807460135]]]},{"id":27,"_class":"TCAD.TWO.Segment","points":[[21,[22,115.90857396213624],[23,643.9003106222236]],[24,[25,115.90857396213619],[26,174.4837595347564]]]},{"id":37,"_class":"TCAD.TWO.Arc","points":[[28,[29,927.2879843119588],[30,643.9224734815724]],[31,[32,776.6236240728185],[33,794.5807272294043]],[34,[35,776.6353054124875],[36,643.9280483299306]]]},{"id":48,"_class":"TCAD.TWO.Arc","points":[[39,[40,266.5634479999531],[41,794.5807272294056]],[42,[43,115.90857396213616],[44,643.9003106222236]],[45,[46,266.5612528616091],[47,643.9280483299286]]]},{"id":59,"_class":"TCAD.TWO.Arc","points":[[50,[51,115.90857396213627],[52,174.4837595347564]],[53,[54,266.5475645170609],[55,23.86392680742626]],[56,[57,266.56125286160903],[58,174.5166057068994]]]},{"id":70,"_class":"TCAD.TWO.Arc","points":[[61,[62,776.6354356426971],[63,23.863926807393575]],[64,[65,927.2879843118895],[66,174.51664392112346]],[67,[68,776.635305412442],[69,174.5166057068957]]]}]}],"constraints":[["coi",[0,39]],["coi",[42,21]],["coi",[24,50]],["coi",[53,14]],["coi",[17,61]],["coi",[64,10]],["coi",[28,7]],["coi",[31,3]],["Horizontal",[6]],["Horizontal",[20]],["Vertical",[13]],["Vertical",[27]],["Tangent",[48,6]],["Tangent",[37,6]],["Tangent",[37,13]],["Tangent",[70,13]],["Tangent",[70,20]],["Tangent",[59,20]],["Tangent",[59,27]],["Tangent",[48,27]],["RR",[37,48]],["RR",[48,59]],["RR",[59,70]]]}

View file

@ -1,53 +0,0 @@
TCAD.test = {};
TCAD.test.cases = {};
TCAD.test.runSuite = function() {
for (var p in TCAD.test.cases) {
_log("... Run test " + p);
try {
TCAD.test.cases[p].apply();
} catch (e) {
_log("<b class='err'>ERROR: </b>" + e);
_log((e.stack+"").replace('\n', '<br />'));
}
}
_log("DONE.");
};
_loadFixture = function(name) {
APP._loadSketch(TCAD.test.fixtures[name]);
};
_loadFixturesToLocalStorage = function() {
for (var p in TCAD.test.fixtures) {
var key = "test:" + p;
console.log("Storing: " + key);
localStorage.setItem("TCAD.projects." + key, JSON.stringify(TCAD.test.fixtures[p]));
}
};
TCAD.test._ERROR_TITLE = "<b class='err'>*</b> Assertion Error.";
function _log(text) {
$('#testOutput').append("<div>"+text+"</div>");
}
function _logAssert(msg) {
_log(TCAD.test._ERROR_TITLE + " " + msg + "<br/>&nbsp;&nbsp;&nbsp;" + new Error("").stack.split('\n')[3]);
}
_assertEq = function(expected, actual, msg) {
if (expected !== actual) {
_logAssert("Expected [" + expected + "], but was [" + actual + "]");
if (!!msg) _log(msg);
}
};
_assertEqD = function(expected, actual, precision, msg) {
if (Math.abs(expected - actual) > precision) {
_logAssert("Expected [" + expected + "] with precision " + precision + " but was [" + actual + "]");
if (!!msg) _log(msg);
}
};

View file

@ -1,22 +0,0 @@
TCAD.test.cases.roundRect = function() {
_loadFixture("RoundRect");
_assertEq(1, APP.viewer.parametricManager.subSystems.length);
_assertEq(31, APP.viewer.parametricManager.subSystems[0].constraints.length);
var ep = APP.viewer.findById(28);
var pm = APP.viewer.parametricManager;
_assertEqD(0.00002047865, pm.prepare([]).solvers[0].error(), 1e-12);
ep.x += 30;
var solver = pm.prepare([]).solvers[0];
_assertEqD(60, solver.error(), 0.01);
var status = solver.solve(true);
_assertEqD(0.000005, solver.error(), 1e-8);
_assertEq(12, status.evalCount);
_assertEq(1, status.returnCode);
var status = solver.solve(false);
_assertEqD(1.4575007867279055e-10, solver.error(), 1e-12);
_assertEq(20, status.evalCount);
_assertEq(1, status.returnCode);
};

View file

@ -1,47 +1,47 @@
TCAD.toolkit = {};
import $ from '../../lib/jquery-2.1.0.min'
TCAD.toolkit.add = function(parent, child) {
export function add(parent, child) {
parent.content.append(child.root);
};
}
TCAD.toolkit.methodRef = function(_this, methodName, args) {
export function methodRef(_this, methodName, args) {
return function() {
_this[methodName].apply(_this, args);
};
};
}
TCAD.toolkit.Box = function() {
export function Box() {
this.root = this.content = $('<div class="tc-box" />');
this.root.addClass('tc-box tc-scroll');
this.root.appendTo('body');
};
}
TCAD.toolkit.Box.prototype.close = function() {
Box.prototype.close = function() {
this.root.remove();
};
TCAD.toolkit.Folder = function(title) {
export function Folder(title) {
this.root = $('<div/>', {'class': 'tc-folder'});
this.content = $('<div/>');
this.root.append($('<div/>', {text: title, 'class': 'tc-row tc-title'}));
this.root.append(this.content);
};
}
TCAD.toolkit.Button = function(title) {
export function Button(title) {
this.root = $('<div/>',
{'class': 'tc-row tc-ctrl tc-ctrl-btn', text: title});
};
}
TCAD.toolkit.CheckBox = function(title, checked) {
export function CheckBox(title, checked) {
this.root = $('<div/>',
{'class': 'tc-row tc-ctrl'});
this.root.append('<label><input type="checkbox">' + title + '</label>')
this.input = this.root.find("input");
this.input.prop('checked', !!checked);
};
}
TCAD.toolkit.InlineRadio = function(choiceLabels, choiceValues, checkedIndex) {
var name = 'TCAD.toolkit.InlineRadio_' + (TCAD.toolkit.InlineRadio.COUNTER++)
export function InlineRadio(choiceLabels, choiceValues, checkedIndex) {
var name = 'TCAD.toolkit.InlineRadio_' + (InlineRadio.COUNTER++)
this.root = $('<div/>',
{'class': 'tc-row tc-ctrl tc-inline-radio'});
this.inputs = [];
@ -52,9 +52,9 @@ TCAD.toolkit.InlineRadio = function(choiceLabels, choiceValues, checkedIndex) {
this.root.append(label);
}
this.inputs[checkedIndex].prop('checked', true);
};
}
TCAD.toolkit.InlineRadio.prototype.getValue = function() {
InlineRadio.prototype.getValue = function() {
for (var i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].prop('checked')) {
return this.inputs[i].attr('value');
@ -63,15 +63,15 @@ TCAD.toolkit.InlineRadio.prototype.getValue = function() {
return null;
};
TCAD.toolkit.InlineRadio.COUNTER = 0;
InlineRadio.COUNTER = 0;
TCAD.toolkit.propLayout = function(root, name, valueEl) {
export function propLayout(root, name, valueEl) {
root.append($('<span/>', {'class': 'tc-prop-name', text: name}))
.append($('<div/>', {'class': 'tc-prop-value'})
.append(valueEl));
};
}
TCAD.toolkit.Number = function(name, initValue, baseStep, round) {
export function Number(name, initValue, baseStep, round) {
this.root = $('<div/>', {'class': 'tc-row tc-ctrl tc-ctrl-number'});
this.input = $("<input type='text' value='"+initValue+"' />");
this.slide = false;
@ -121,23 +121,23 @@ TCAD.toolkit.Number = function(name, initValue, baseStep, round) {
e.stopPropagation();
trigger.call(this);
}, false);
TCAD.toolkit.propLayout(this.root, name, this.input);
};
propLayout(this.root, name, this.input);
}
TCAD.toolkit.Combo = function(id, label) {
export function Combo(id, labelText) {
this.root = $('<div/>', {'class': 'tc-row tc-ctrl tc-ctrl-combo'});
var label = $('<span/>', {'class': 'tc-prop-name', text: label});
var label = $('<span/>', {'class': 'tc-prop-name', text: labelText});
this.select = $('<select>', {id : id});
this.root.append(label)
.append($('<div/>', {'class': 'tc-prop-value'}).append(this.select));
};
}
TCAD.toolkit.Text = function(name) {
export function Text(name) {
this.root = $('<div/>', {'class': 'tc-row tc-ctrl tc-ctrl-text'});
TCAD.toolkit.propLayout(this.root, name, $('<input type="text"/>'));
};
propLayout(this.root, name, $('<input type="text"/>'));
}
TCAD.toolkit.ButtonRow = function(captions, actions) {
export function ButtonRow(captions, actions) {
this.root = $('<div/>',
{'class': 'tc-row tc-ctrl tc-buttons-block'});
@ -156,13 +156,13 @@ TCAD.toolkit.ButtonRow = function(captions, actions) {
withAction(btn, actions[i]);
this.root.append(btn);
}
};
}
TCAD.toolkit.List = function() {
export function List() {
this.root = $('<div/>', {'class': 'tc-tree'});
};
}
TCAD.toolkit.List.prototype.addRow = function(name) {
List.prototype.addRow = function(name) {
var row = $('<div/>', {
text: name, 'class': 'tc-row tc-pseudo-btn',
css: {'margin-left': '10px'}
@ -171,16 +171,16 @@ TCAD.toolkit.List.prototype.addRow = function(name) {
return row;
};
TCAD.toolkit.Tree = function() {
export function Tree() {
this.root = $('<div/>', {'class': 'tc-tree'});
};
}
TCAD.toolkit.Tree.prototype.set = function(data) {
Tree.prototype.set = function(data) {
this.root.empty();
this._fill(data, 0);
};
TCAD.toolkit.Tree.prototype._fill = function(data, level) {
Tree.prototype._fill = function(data, level) {
var notLeaf = data.children !== undefined && data.children.length !== 0;
if (data.name !== undefined) {
this.root.append($('<div/>', {
@ -196,11 +196,11 @@ TCAD.toolkit.Tree.prototype._fill = function(data, level) {
}
};
TCAD.Parameters = function() {
export function Parameters() {
this.listeners = {};
};
}
TCAD.Parameters.prototype.define = function(name, initValue) {
Parameters.prototype.define = function(name, initValue) {
function fn(name) {
return '___' + name;
}
@ -215,7 +215,7 @@ TCAD.Parameters.prototype.define = function(name, initValue) {
});
};
TCAD.Parameters.prototype.subscribe = function(name, listenerId, callback, scope) {
Parameters.prototype.subscribe = function(name, listenerId, callback, scope) {
var listenerList = this.listeners[name];
if (listenerList === undefined) {
listenerList = [];
@ -229,7 +229,7 @@ TCAD.Parameters.prototype.subscribe = function(name, listenerId, callback, scope
return (function () { callbackFunc(params[name], undefined, null) }); // return init function
};
TCAD.Parameters.prototype.notify = function(name, newValue, oldValue) {
Parameters.prototype.notify = function(name, newValue, oldValue) {
var listenerList = this.listeners[name];
if (listenerList !== undefined) {
for (var i = 0; i < listenerList.length; i++) {
@ -243,16 +243,16 @@ TCAD.Parameters.prototype.notify = function(name, newValue, oldValue) {
this.__currentSender = null;
};
TCAD.Parameters.prototype.set = function(name, value, sender) {
Parameters.prototype.set = function(name, value, sender) {
this.__currentSender = sender;
this[name] = value;
};
TCAD.Bus = function() {
export function Bus() {
this.listeners = {};
};
}
TCAD.Bus.prototype.subscribe = function(event, callback) {
Bus.prototype.subscribe = function(event, callback) {
var listenerList = this.listeners[event];
if (listenerList === undefined) {
listenerList = [];
@ -261,7 +261,7 @@ TCAD.Bus.prototype.subscribe = function(event, callback) {
listenerList.push(callback);
};
TCAD.Bus.prototype.notify = function(event, data) {
Bus.prototype.notify = function(event, data) {
var listenerList = this.listeners[event];
if (listenerList !== undefined) {
for (var i = 0; i < listenerList.length; i++) {
@ -270,12 +270,12 @@ TCAD.Bus.prototype.notify = function(event, data) {
}
};
TCAD.Bus.Observable = function(initValue) {
Bus.Observable = function(initValue) {
this.value = initValue;
};
TCAD.Bus.prototype.defineObservable = function(scope, name, eventName, initValue) {
var observable = new TCAD.Bus.Observable(initValue);
Bus.prototype.defineObservable = function(scope, name, eventName, initValue) {
var observable = new Bus.Observable(initValue);
var bus = this;
return Object.defineProperty(scope, name, {
get: function() { return observable.value;},
@ -284,4 +284,4 @@ TCAD.Bus.prototype.defineObservable = function(scope, name, eventName, initValue
bus.notify(eventName, value);
}
});
};
};

View file

@ -1,7 +1,7 @@
TCAD.ui = {};
import $ from '../../lib/jquery-2.1.0.min'
/** @constructor */
TCAD.ui.Window = function(el, winManager) {
function Window(el, winManager) {
this.root = el;
this.neverOpened = !this.root.is(':visible');
this.tileUpRelative = $('body');
@ -15,12 +15,12 @@ TCAD.ui.Window = function(el, winManager) {
this.root.find('.tool-caption .rm').click(function() {
root.hide();
});
var DIRS = TCAD.ui.DIRECTIONS;
var DIRS = DIRECTIONS;
winManager.registerResize(this.root, DIRS.NORTH | DIRS.SOUTH | DIRS.WEST | DIRS.EAST);
winManager.registerDrag(this.root, caption);
};
}
TCAD.ui.Window.prototype.toggle = function() {
Window.prototype.toggle = function() {
var aboutToShow = !this.root.is(':visible');
if (aboutToShow) {
this.tileUpPolicy(this.neverOpened, this.tileUpRelative);
@ -32,7 +32,7 @@ TCAD.ui.Window.prototype.toggle = function() {
}
};
TCAD.ui.Window.prototype.tileUpPolicy = function(firstTime, relativeEl) {
Window.prototype.tileUpPolicy = function(firstTime, relativeEl) {
var span = 20;
var relOff = relativeEl.offset();
var off = this.root.offset();
@ -84,7 +84,7 @@ TCAD.ui.Window.prototype.tileUpPolicy = function(firstTime, relativeEl) {
//}
};
TCAD.ui.WinManager = function() {
function WinManager() {
this.moveHandler = null;
var wm = this;
$('body').mousemove(function(e) {
@ -96,9 +96,9 @@ TCAD.ui.WinManager = function() {
$('body').mouseup(function(e) {
wm.moveHandler = null;
});
};
}
TCAD.ui.WinManager.prototype.captureDrag = function(el, e) {
WinManager.prototype.captureDrag = function(el, e) {
var origin = {x : e.pageX, y : e.pageY};
var originLocation = el.offset();
this.moveHandler = function(e) {
@ -108,15 +108,15 @@ TCAD.ui.WinManager.prototype.captureDrag = function(el, e) {
};
};
TCAD.ui.WinManager.prototype.captureResize = function(el, dirMask, e, onResize) {
WinManager.prototype.captureResize = function(el, dirMask, e, onResize) {
var origin = {x : e.pageX, y : e.pageY};
var originSize = {x : el.width(), y : el.height()};
var originLocation = el.offset();
var north = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.NORTH);
var south = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.SOUTH);
var west = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.WEST);
var east = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.EAST);
var north = _maskTest(dirMask, DIRECTIONS.NORTH);
var south = _maskTest(dirMask, DIRECTIONS.SOUTH);
var west = _maskTest(dirMask, DIRECTIONS.WEST);
var east = _maskTest(dirMask, DIRECTIONS.EAST);
this.moveHandler = function(e) {
var dx = e.pageX - origin.x;
@ -149,19 +149,19 @@ TCAD.ui.WinManager.prototype.captureResize = function(el, dirMask, e, onResize)
}
};
TCAD.ui.DIRECTIONS = {
var DIRECTIONS = {
NORTH : 0x0001,
SOUTH : 0x0010,
WEST : 0x0100,
EAST : 0x1000,
};
TCAD.ui.WinManager.prototype.registerResize = function(el, dirMask, onResize) {
WinManager.prototype.registerResize = function(el, dirMask, onResize) {
var wm = this;
var north = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.NORTH);
var south = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.SOUTH);
var west = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.WEST);
var east = TCAD.ui._maskTest(dirMask, TCAD.ui.DIRECTIONS.EAST);
var north = _maskTest(dirMask, DIRECTIONS.NORTH);
var south = _maskTest(dirMask, DIRECTIONS.SOUTH);
var west = _maskTest(dirMask, DIRECTIONS.WEST);
var east = _maskTest(dirMask, DIRECTIONS.EAST);
var borderTop = parseInt(el.css('borderTopWidth'), 10);
var borderLeft = parseInt(el.css('borderLeftWidth'), 10);
@ -192,21 +192,21 @@ TCAD.ui.WinManager.prototype.registerResize = function(el, dirMask, onResize) {
el.mousedown(function(e) {
var $this = $(this);
if (north && east && onNorthEdge(e, $this) && onEastEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.NORTH | TCAD.ui.DIRECTIONS.EAST, e, onResize);
wm.captureResize(el, DIRECTIONS.NORTH | DIRECTIONS.EAST, e, onResize);
} else if (north && west && onNorthEdge(e, $this) && onWestEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.NORTH | TCAD.ui.DIRECTIONS.WEST, e, onResize);
wm.captureResize(el, DIRECTIONS.NORTH | DIRECTIONS.WEST, e, onResize);
} else if (south && east && onSouthEdge(e, $this) && onEastEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.SOUTH | TCAD.ui.DIRECTIONS.EAST, e, onResize);
wm.captureResize(el, DIRECTIONS.SOUTH | DIRECTIONS.EAST, e, onResize);
} else if (south && west && onSouthEdge(e, $this) && onWestEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.SOUTH | TCAD.ui.DIRECTIONS.WEST, e, onResize);
wm.captureResize(el, DIRECTIONS.SOUTH | DIRECTIONS.WEST, e, onResize);
} else if (north && onNorthEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.NORTH, e, onResize);
wm.captureResize(el, DIRECTIONS.NORTH, e, onResize);
} else if (south && onSouthEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.SOUTH, e, onResize);
wm.captureResize(el, DIRECTIONS.SOUTH, e, onResize);
} else if (west && onWestEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.WEST, e, onResize);
wm.captureResize(el, DIRECTIONS.WEST, e, onResize);
} else if (east && onEastEdge(e, $this)) {
wm.captureResize(el, TCAD.ui.DIRECTIONS.EAST, e, onResize);
wm.captureResize(el, DIRECTIONS.EAST, e, onResize);
}
});
el.mousemove(function(e) {
@ -234,21 +234,20 @@ TCAD.ui.WinManager.prototype.registerResize = function(el, dirMask, onResize) {
});
};
TCAD.ui.WinManager.prototype.registerDrag = function(el, dragger) {
WinManager.prototype.registerDrag = function(el, dragger) {
var wm = this;
dragger.mousedown(function(e) {
wm.captureDrag(el, e);
});
};
TCAD.ui.bindOpening = function(btn, win) {
btn.click(function(e) {
TCAD.ui.openWin(win, e);
function bindOpening(btn, win) {
btn.click(function(e) {
openWin(win, e);
});
};
}
TCAD.ui.createActionsWinBuilder = function(win) {
function createActionsWinBuilder(win) {
var content = win.root.find('.content');
var template = content.html();
content.empty();
@ -256,13 +255,13 @@ TCAD.ui.createActionsWinBuilder = function(win) {
content.append(template.replace("$value$", name));
content.find('div:last input').click(action);
};
};
}
TCAD.ui.closeWin = function(win) {
function closeWin(win) {
win.root.hide();
};
}
TCAD.ui.openWin = function(win, mouseEvent) {
function openWin(win, mouseEvent) {
var x = mouseEvent.pageX;
var y = mouseEvent.pageY;
@ -277,16 +276,16 @@ TCAD.ui.openWin = function(win, mouseEvent) {
win.root.show();
win.root.offset({top : top, left : left});
};
}
/** @constructor */
TCAD.ui.List = function(id, model) {
function List(id, model) {
this.ul = $('<ul>', { 'class' : 'tlist', id : id});
this.model = model;
this.template = '<li>$name$<span class="btn rm" style="float: right;"><i class="fa fa-remove"></i></span></li>';
};
}
TCAD.ui.List.prototype.refresh = function() {
List.prototype.refresh = function() {
this.ul.empty();
var items = this.model.items();
var model = this.model;
@ -310,14 +309,18 @@ TCAD.ui.List.prototype.refresh = function() {
}
};
TCAD.ui.dockBtn = function(name, icon) {
function dockBtn(name, icon) {
var btn = $('<span>', {'class': 'dock-btn'});
btn.append(TCAD.App2D.faBtn(icon));
btn.append(faBtn(icon));
btn.append($('<span>', {'class': 'txt'}).text(name));
return btn;
};
}
TCAD.ui.Dock = function(dockEl, switcherEl, viewDefinitions) {
function faBtn (iconName) {
return $('<i>', {'class' : 'fa fa-'+iconName});
}
function Dock(dockEl, switcherEl, viewDefinitions) {
this.views = {};
this.dockEl = dockEl;
function bindClick(dock, switchEl, viewName) {
@ -336,17 +339,17 @@ TCAD.ui.Dock = function(dockEl, switcherEl, viewDefinitions) {
view.node = $('<div>', {'class': 'dock-node'});
var caption = $('<div>', {'class': 'tool-caption'});
caption.append($('<span>', {'class': 'txt'}).text(viewDef.name.toUpperCase()));
caption.append(TCAD.App2D.faBtn(viewDef.icon));
caption.append(faBtn(viewDef.icon));
view.node.append(caption);
view.node.hide();
this.dockEl.append(view.node);
view.switchBtn = TCAD.ui.dockBtn(viewDef.name, viewDef.icon);
view.switchBtn = dockBtn(viewDef.name, viewDef.icon);
bindClick(this, view.switchBtn, viewDef.name);
switcherEl.append(view.switchBtn);
}
};
}
TCAD.ui.Dock.prototype.show = function(viewName) {
Dock.prototype.show = function(viewName) {
var view = this.views[viewName];
if (view.switchBtn.hasClass('selected')) {
return;
@ -359,7 +362,7 @@ TCAD.ui.Dock.prototype.show = function(viewName) {
view.switchBtn.addClass('selected');
};
TCAD.ui.Dock.prototype.hide = function(viewName) {
Dock.prototype.hide = function(viewName) {
var view = this.views[viewName];
if (!view.switchBtn.hasClass('selected')) {
return;
@ -372,16 +375,15 @@ TCAD.ui.Dock.prototype.hide = function(viewName) {
}
};
TCAD.ui.Dock.prototype.isVisible = function(viewName) {
Dock.prototype.isVisible = function(viewName) {
return this.views[viewName].switchBtn.hasClass('selected');
};
TCAD.ui._maskTest = function (mask, value) {
function _maskTest(mask, value) {
return (mask & value) === value;
};
}
TCAD.ui.Terminal = function(win, commandProcessor) {
function Terminal(win, commandProcessor) {
this.win = win;
win.onShowCallback = function() {
win.root.find('.terminal-input input').focus();
@ -401,4 +403,6 @@ TCAD.ui.Terminal = function(win, commandProcessor) {
out.parent().scrollTop(out.height());
}
});
};
}
export { WinManager, Window, List, Dock, Terminal, dockBtn, faBtn, openWin, closeWin, bindOpening, createActionsWinBuilder, DIRECTIONS };

View file

@ -1,60 +1,58 @@
import Vector from '../math/vector'
import {HashTable} from '../utils/hashmap'
import {Graph} from '../math/graph'
import * as math from '../math/math'
import {Matrix3, AXIS, ORIGIN} from '../math/l3space'
import {reconstructSketchBounds} from '../3d/workbench' //FIXME
TCAD.utils = {};
export const DPR = (window.devicePixelRatio) ? window.devicePixelRatio : 1;
export const FACE_COLOR = 0xB0C4DE;
TCAD.utils.createSquare = function(width) {
export var Counters = {
solid : 0,
shared : 0
};
export function createSquare(width) {
width /= 2;
return [
new TCAD.Vector(-width, -width, 0),
new TCAD.Vector( width, -width, 0),
new TCAD.Vector( width, width, 0),
new TCAD.Vector(-width, width, 0)
new Vector(-width, -width, 0),
new Vector( width, -width, 0),
new Vector( width, width, 0),
new Vector(-width, width, 0)
];
};
}
TCAD.utils.csgVec = function(v) {
export function csgVec(v) {
return new CSG.Vector3D(v.x, v.y, v.z);
};
}
TCAD.utils.vec = function(v) {
return new TCAD.Vector(v.x, v.y, v.z);
};
export function vec(v) {
return new Vector(v.x, v.y, v.z);
}
TCAD.utils.createBox = function(width) {
var square = TCAD.utils.createSquare(width);
var rot = TCAD.math.rotateMatrix(3/4, TCAD.math.AXIS.Z, TCAD.math.ORIGIN);
export function createBox(width) {
var square = createSquare(width);
var rot = Matrix3.rotateMatrix(3/4, AXIS.Z, ORIGIN);
square.forEach(function(v) { rot._apply(v) } );
var normal = TCAD.geom.normalOfCCWSeq(square);
return TCAD.geom.extrude(square, normal, normal.multiply(width), 1);
};
var normal = normalOfCCWSeq(square);
return extrude(square, normal, normal.multiply(width), 1);
}
TCAD.utils.createCSGBox = function(width) {
var csg = CSG.fromPolygons(TCAD.utils.createBox(width));
return TCAD.utils.createSolid(csg);
};
export function createCSGBox(width) {
var csg = CSG.fromPolygons(createBox(width));
return createSolid(csg);
}
TCAD.utils.toCsgGroups = function(polygons) {
var groups = [];
for (var i = 0; i < polygons.length; i++) {
var p = polygons[i];
if (p.holes.length === 0) {
groups.push( new TCAD.CSGGroup([new TCAD.SimplePolygon(p.shell, p.normal)], p.normal) );
} else {
// TODO: triangulation needed
groups.push( new TCAD.CSGGroup([new TCAD.SimplePolygon(p.shell, p.normal)], p.normal) );
}
}
return groups;
};
TCAD.utils.checkPolygon = function(poly) {
export function checkPolygon(poly) {
if (poly.length < 3) {
throw new Error('Polygon should contain at least 3 point');
}
};
}
TCAD.utils.createPoint = function(x, y, z) {
export function createPoint0(x, y, z) {
// var g = new THREE.PlaneGeometry(0.05, 0.05);
// var m = new THREE.MeshBasicMaterial({color: 0x0000ff, side: THREE.DoubleSide});
// return new THREE.Mesh(g, m);
@ -92,9 +90,19 @@ TCAD.utils.createPoint = function(x, y, z) {
var sprite = new THREE.Sprite( material );
sprite.position.set( x, y, z );
return sprite;
};
}
TCAD.utils.createLine = function (a, b, color) {
export function createPoint1(x, y, z) {
var geometry = new THREE.SphereGeometry( 5, 16, 16 );
var material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
var sphere = new THREE.Mesh(geometry, material);
sphere.position.x = x;
sphere.position.y = y;
sphere.position.z = z;
return sphere;
}
export function createLine(a, b, color) {
var material = new THREE.LineBasicMaterial({
color: color,
linewidth: 1
@ -103,91 +111,79 @@ TCAD.utils.createLine = function (a, b, color) {
geometry.vertices.push(new THREE.Vector3(a.x, a.y, a.z));
geometry.vertices.push(new THREE.Vector3(b.x, b.y, b.z));
return new THREE.Line(geometry, material);
};
}
TCAD.utils.createPoint = function (x, y, z) {
var geometry = new THREE.SphereGeometry( 5, 16, 16 );
var material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
var sphere = new THREE.Mesh(geometry, material);
sphere.position.x = x;
sphere.position.y = y;
sphere.position.z = z;
return sphere;
};
TCAD.utils.createSolidMaterial = function() {
export function createSolidMaterial() {
return new THREE.MeshPhongMaterial({
vertexColors: THREE.FaceColors,
color: TCAD.view.FACE_COLOR,
color: FACE_COLOR,
shininess: 0,
polygonOffset : true,
polygonOffsetFactor : 1,
polygonOffsetUnits : 2,
side : THREE.DoubleSide
});
};
}
TCAD.utils.createSolid = function(csg) {
var material = TCAD.utils.createSolidMaterial();
return new TCAD.Solid(csg, material);
};
export function createSolid(csg) {
var material = createSolidMaterial();
return new Solid(csg, material);
}
TCAD.utils.intercept = function(obj, methodName, aspect) {
export function intercept(obj, methodName, aspect) {
var originFunc = obj[methodName];
obj[methodName] = function() {
var $this = this;
aspect(function() {originFunc.apply($this, arguments)}, arguments);
}
};
TCAD.utils.createPlane = function(basis, depth) {
var tu = TCAD.utils;
}
export function createPlane(basis, depth) {
var initWidth = 1;
var boundingPolygon = [
new TCAD.Vector(0, 0, 0),
new TCAD.Vector(initWidth, 0, 0),
new TCAD.Vector(initWidth, initWidth, 0),
new TCAD.Vector(0, initWidth, 0)
new Vector(0, 0, 0),
new Vector(initWidth, 0, 0),
new Vector(initWidth, initWidth, 0),
new Vector(0, initWidth, 0)
];
var shared = tu.createShared();
var shared = createShared();
var material = tu.createSolidMaterial();
var material = createSolidMaterial();
material.transparent = true;
material.opacity = 0.5;
material.side = THREE.DoubleSide;
var tr = new TCAD.Matrix().setBasis(basis);
var currentBounds = new TCAD.BBox();
var tr = new Matrix3().setBasis(basis);
var currentBounds = new BBox();
var points = boundingPolygon.map(function(p) { p.z = depth; return tr._apply(p); });
var polygon = new CSG.Polygon(points.map(function(p){return new CSG.Vertex(TCAD.utils.csgVec(p))}), shared);
var plane = new TCAD.Solid(CSG.fromPolygons([polygon]), material, 'PLANE');
var polygon = new CSG.Polygon(points.map(function(p){return new CSG.Vertex(csgVec(p))}), shared);
var plane = new Solid(CSG.fromPolygons([polygon]), material, 'PLANE');
plane.wireframeGroup.visible = false;
plane.mergeable = false;
var _3d = tr.invert();
function setBounds(bbox) {
var corner = new TCAD.Vector(bbox.minX, bbox.minY, 0);
var size = new TCAD.Vector(bbox.width(), bbox.height(), 1);
var corner = new Vector(bbox.minX, bbox.minY, 0);
var size = new Vector(bbox.width(), bbox.height(), 1);
_3d._apply(size);
_3d._apply(corner);
plane.mesh.scale.set(size.x, size.y, size.z);
plane.mesh.position.set(corner.x, corner.y, corner.z);
currentBounds = bbox;
var poly = new CSG.Polygon(bbox.toPolygon().map(function(p){return new CSG.Vertex(TCAD.utils.csgVec( _3d._apply(p) ))}), shared);
var poly = new CSG.Polygon(bbox.toPolygon().map(function(p){return new CSG.Vertex(csgVec( _3d._apply(p) ))}), shared);
plane.csg = CSG.fromPolygons([poly]);
}
var bb = new TCAD.BBox();
var bb = new BBox();
bb.checkBounds(-400, -400);
bb.checkBounds( 400, 400);
setBounds(bb);
var sketchFace = plane.polyFaces[0];
tu.intercept(sketchFace, 'syncSketches', function(invocation, args) {
intercept(sketchFace, 'syncSketches', function(invocation, args) {
var geom = args[0];
invocation(geom);
var bbox = new TCAD.BBox();
var connections = geom.connections.concat(TCAD.utils.arrFlatten1L(geom.loops));
var bbox = new BBox();
var connections = geom.connections.concat(arrFlatten1L(geom.loops));
for (var i = 0; i < connections.length; ++i) {
var l = connections[i];
bbox.checkBounds(l.a.x, l.a.y);
@ -200,49 +196,24 @@ TCAD.utils.createPlane = function(basis, depth) {
});
return plane;
};
}
TCAD.utils.fixCCW = function(path, normal) {
var _2DTransformation = new TCAD.Matrix().setBasis(TCAD.geom.someBasis(path, normal)).invert();
export function fixCCW(path, normal) {
var _2DTransformation = new Matrix3().setBasis(someBasis(path, normal)).invert();
var path2D = [];
for (var i = 0; i < path.length; ++i) {
path2D[i] = _2DTransformation.apply(path[i]);
}
if (!TCAD.geom.isCCW(path2D)) {
if (!isCCW(path2D)) {
path = path.slice(0);
path.reverse();
}
return path;
};
}
TCAD.TOLERANCE = 1E-6;
TCAD.utils.areEqual = function(v1, v2, tolerance) {
return Math.abs(v1 - v2) < tolerance;
};
TCAD.utils.areVectorsEqual = function(v1, v2, tolerance) {
return TCAD.utils.areEqual(v1.x, v2.x, tolerance) &&
TCAD.utils.areEqual(v1.y, v2.y, tolerance) &&
TCAD.utils.areEqual(v1.z, v2.z, tolerance);
};
TCAD.utils.vectorsEqual = function(v1, v2) {
return TCAD.utils.areVectorsEqual(v1, v2, TCAD.TOLERANCE);
};
TCAD.utils.equal = function(v1, v2) {
return TCAD.utils.areEqual(v1, v2, TCAD.TOLERANCE);
};
TCAD.utils.strictEqual = function(a, b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
};
TCAD.utils.isPointInsidePolygon = function( inPt, inPolygon ) {
var EPSILON = TCAD.TOLERANCE;
export function isPointInsidePolygon( inPt, inPolygon ) {
var EPSILON = math.TOLERANCE;
var polyLen = inPolygon.length;
@ -284,12 +255,12 @@ TCAD.utils.isPointInsidePolygon = function( inPt, inPolygon ) {
}
return inside;
};
}
TCAD.utils.sketchToPolygons = function(geom) {
export function sketchToPolygons(geom) {
var dict = TCAD.struct.hashTable.forVector2d();
var edges = TCAD.struct.hashTable.forDoubleArray();
var dict = HashTable.forVector2d();
var edges = HashTable.forDoubleArray();
var lines = geom.connections;
@ -334,12 +305,13 @@ TCAD.utils.sketchToPolygons = function(geom) {
}
};
var loops = TCAD.graph.findAllLoops(graph, dict.hashCodeF, dict.equalsF);
var loops = Graph.findAllLoops(graph, dict.hashCodeF, dict.equalsF);
var polygons = [];
for (var li = 0; li < loops.length; ++li) {
var loop = loops[li];
if (!TCAD.geom.isCCW(loop)) loop.reverse();
var polyPoints = [];
var li, loop, polyPoints;
for (li = 0; li < loops.length; ++li) {
loop = loops[li];
if (!isCCW(loop)) loop.reverse();
polyPoints = [];
for (var pi = 0; pi < loop.length; ++pi) {
var point = loop[pi];
var next = loop[(pi + 1) % loop.length];
@ -357,9 +329,9 @@ TCAD.utils.sketchToPolygons = function(geom) {
console.warn("Points count < 3!");
}
}
for (var li = 0; li < geom.loops.length; ++li) {
var loop = geom.loops[li];
var polyPoints = loop.slice(0);
for (li = 0; li < geom.loops.length; ++li) {
loop = geom.loops[li];
polyPoints = loop.slice(0);
for (var si = 0; si < polyPoints.length; si++) {
var conn = polyPoints[si];
//reuse a point and ignore b point since it's a guaranteed loop
@ -367,23 +339,21 @@ TCAD.utils.sketchToPolygons = function(geom) {
polyPoints[si] = conn.a;
}
// we assume that connection object is the same al other the loop. That's why reverse is safe.
if (!TCAD.geom.isCCW(polyPoints)) polyPoints.reverse();
if (!isCCW(polyPoints)) polyPoints.reverse();
if (polyPoints.length >= 3) {
polygons.push(polyPoints);
}
}
return polygons;
};
}
TCAD.geom = {};
TCAD.geom.someBasis2 = function(normal) {
export function someBasis2(normal) {
var x = normal.cross(normal.randomNonParallelVector());
var y = normal.cross(x).unit();
return [x, y, normal];
};
}
TCAD.geom.someBasis = function(twoPointsOnPlane, normal) {
export function someBasis(twoPointsOnPlane, normal) {
var a = twoPointsOnPlane[0];
var b = twoPointsOnPlane[1];
@ -391,40 +361,40 @@ TCAD.geom.someBasis = function(twoPointsOnPlane, normal) {
var y = normal.cross(x).normalize();
return [x, y, normal];
};
}
TCAD.geom.normalOfCCWSeq = function(ccwSequence) {
export function normalOfCCWSeq(ccwSequence) {
var a = ccwSequence[0];
var b = ccwSequence[1];
var c = ccwSequence[2];
return b.minus(a).cross(c.minus(a)).normalize();
};
}
TCAD.geom.normalOfCCWSeqTHREE = function(ccwSequence) {
export function normalOfCCWSeqTHREE(ccwSequence) {
var a = ccwSequence[0];
var b = ccwSequence[1].clone();
var c = ccwSequence[2].clone();
return b.sub(a).cross(c.sub(a)).normalize();
};
}
// http://en.wikipedia.org/wiki/Shoelace_formula
TCAD.geom.area = function (contour) {
export function area(contour) {
var n = contour.length;
var a = 0.0;
for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
}
return a * 0.5;
};
}
TCAD.geom.isCCW = function(path2D) {
return TCAD.geom.area(path2D) >= 0;
};
export function isCCW(path2D) {
return area(path2D) >= 0;
}
TCAD.BBox = function() {
export function BBox() {
this.minX = Number.MAX_VALUE;
this.minY = Number.MAX_VALUE;
this.maxX = -Number.MAX_VALUE;
@ -437,7 +407,7 @@ TCAD.BBox = function() {
};
this.center = function() {
return new TCAD.Vector(this.minX + (this.maxX - this.minX) / 2, this.minY + (this.maxY - this.minY) / 2, 0)
return new Vector(this.minX + (this.maxX - this.minX) / 2, this.minY + (this.maxY - this.minY) / 2, 0)
};
this.width = function() {
@ -457,15 +427,15 @@ TCAD.BBox = function() {
this.toPolygon = function() {
return [
new TCAD.Vector(this.minX, this.minY, 0),
new TCAD.Vector(this.maxX, this.minY, 0),
new TCAD.Vector(this.maxX, this.maxY, 0),
new TCAD.Vector(this.minX, this.maxY, 0)
new Vector(this.minX, this.minY, 0),
new Vector(this.maxX, this.minY, 0),
new Vector(this.maxX, this.maxY, 0),
new Vector(this.minX, this.maxY, 0)
];
}
};
}
TCAD.geom.calculateExtrudedLid = function(sourcePolygon, normal, direction, expansionFactor) {
export function calculateExtrudedLid(sourcePolygon, normal, direction, expansionFactor) {
var lid = [];
var length = sourcePolygon.length;
var work;
@ -474,10 +444,10 @@ TCAD.geom.calculateExtrudedLid = function(sourcePolygon, normal, direction, expa
var source2d = [];
work = [];
var _3dTr = new TCAD.Matrix().setBasis(TCAD.geom.someBasis2(new CSG.Vector3D(normal))); // use passed basis
var _3dTr = new Matrix3().setBasis(someBasis2(new CSG.Vector3D(normal))); // use passed basis
var _2dTr = _3dTr.invert();
var sourceBBox = new TCAD.BBox();
var workBBox = new TCAD.BBox();
var sourceBBox = new BBox();
var workBBox = new BBox();
for (si = 0; si < length; ++si) {
var sourcePoint = _2dTr.apply(sourcePolygon[si]);
source2d[si] = sourcePoint;
@ -502,9 +472,9 @@ TCAD.geom.calculateExtrudedLid = function(sourcePolygon, normal, direction, expa
}
return lid;
};
}
TCAD.geom.extrude = function(source, sourceNormal, target, expansionFactor) {
export function extrude(source, sourceNormal, target, expansionFactor) {
var extrudeDistance = target.normalize().dot(sourceNormal);
if (extrudeDistance == 0) {
@ -513,7 +483,7 @@ TCAD.geom.extrude = function(source, sourceNormal, target, expansionFactor) {
var negate = extrudeDistance < 0;
var poly = [null, null];
var lid = TCAD.geom.calculateExtrudedLid(source, sourceNormal, target, expansionFactor);
var lid = calculateExtrudedLid(source, sourceNormal, target, expansionFactor);
var bottom, top;
if (negate) {
@ -526,13 +496,13 @@ TCAD.geom.extrude = function(source, sourceNormal, target, expansionFactor) {
var n = source.length;
for ( var p = n - 1, i = 0; i < n; p = i ++ ) {
var shared = TCAD.utils.createShared();
var shared = createShared();
shared.__tcad.csgInfo = {derivedFrom: source[p].sketchConnectionObject};
var face = new CSG.Polygon([
new CSG.Vertex(TCAD.utils.csgVec(bottom[p])),
new CSG.Vertex(TCAD.utils.csgVec(bottom[i])),
new CSG.Vertex(TCAD.utils.csgVec(top[i])),
new CSG.Vertex(TCAD.utils.csgVec(top[p]))
new CSG.Vertex(csgVec(bottom[p])),
new CSG.Vertex(csgVec(bottom[i])),
new CSG.Vertex(csgVec(top[i])),
new CSG.Vertex(csgVec(top[p]))
], shared);
poly.push(face);
}
@ -550,21 +520,19 @@ TCAD.geom.extrude = function(source, sourceNormal, target, expansionFactor) {
}
function vecToVertex(v) {
return new CSG.Vertex(TCAD.utils.csgVec(v));
return new CSG.Vertex(csgVec(v));
}
var sourcePlane = new CSG.Plane(bottomNormal.csg(), bottomNormal.dot(source[0]));
var lidPlane = new CSG.Plane(topNormal.csg(), topNormal.dot(lid[0]));
poly[0] = new CSG.Polygon(source.map(vecToVertex), TCAD.utils.createShared(), sourcePlane);
poly[1] = new CSG.Polygon(lid.map(vecToVertex), TCAD.utils.createShared(), lidPlane);
poly[0] = new CSG.Polygon(source.map(vecToVertex), createShared(), sourcePlane);
poly[1] = new CSG.Polygon(lid.map(vecToVertex), createShared(), lidPlane);
return poly;
};
}
TCAD.geom.SOLID_COUNTER = 0;
TCAD.geom.triangulate = function(path, normal) {
var _3dTransformation = new TCAD.Matrix().setBasis(TCAD.geom.someBasis2(normal));
export function triangulate(path, normal) {
var _3dTransformation = new Matrix3().setBasis(someBasis2(normal));
var _2dTransformation = _3dTransformation.invert();
var i;
var shell = [];
@ -574,9 +542,9 @@ TCAD.geom.triangulate = function(path, normal) {
var myTriangulator = new PNLTRI.Triangulator();
return myTriangulator.triangulate_polygon( [ shell ] );
// return THREE.Shape.utils.triangulateShape( f2d.shell, f2d.holes );
};
}
TCAD.utils.groupCSG = function(csg) {
export function groupCSG(csg) {
var csgPolygons = csg.toPolygons();
var groups = {};
for (var i = 0; i < csgPolygons.length; i++) {
@ -593,38 +561,37 @@ TCAD.utils.groupCSG = function(csg) {
groups[tag].polygons.push(p);
}
return groups;
};
}
TCAD.utils.SHARED_COUNTER = 0;
TCAD.utils.createShared = function() {
var id = TCAD.utils.SHARED_COUNTER ++;
export function createShared() {
var id = Counters.shared ++;
var shared = new CSG.Polygon.Shared([id, id, id, id]);
shared.__tcad = {};
return shared;
};
}
TCAD.utils.isSmoothPiece = function(shared) {
export function isSmoothPiece(shared) {
return shared.__tcad && !!shared.__tcad.csgInfo && !!shared.__tcad.csgInfo.derivedFrom &&
(shared.__tcad.csgInfo.derivedFrom._class === 'TCAD.TWO.Arc' || shared.__tcad.csgInfo.derivedFrom._class === 'TCAD.TWO.Circle');
};
}
TCAD.utils.sameID = function(id1, id2) {
export function sameID(id1, id2) {
if (id1 === null || id2 === null) {
return false;
}
return id1 === id2;
};
}
TCAD.utils.getDerivedID = function(shared) {
export function getDerivedID(shared) {
return shared.__tcad && !!shared.__tcad.csgInfo && !!shared.__tcad.csgInfo.derivedFrom ? shared.__tcad.csgInfo.derivedFrom.id : null;
};
}
TCAD.utils.getDerivedFrom = function(shared) {
export function getDerivedFrom(shared) {
return shared.__tcad && !!shared.__tcad.csgInfo && !!shared.__tcad.csgInfo.derivedFrom ? shared.__tcad.csgInfo.derivedFrom : null;
};
}
/** @constructor */
TCAD.Solid = function(csg, material, type) {
export function Solid(csg, material, type) {
csg = csg.reTesselated().canonicalized();
this.tCadType = type || 'SOLID';
this.csg = csg;
@ -637,30 +604,30 @@ TCAD.Solid = function(csg, material, type) {
this.mesh = new THREE.Mesh(geometry, material);
this.cadGroup.add(this.mesh);
this.tCadId = TCAD.geom.SOLID_COUNTER ++;
this.tCadId = Counters.solid ++;
this.faceCounter = 0;
this.wireframeGroup = new THREE.Object3D();
this.cadGroup.add(this.wireframeGroup);
this.polyFaces = [];
this.wires = TCAD.struct.hashTable.forEdge();
this.wires = HashTable.forEdge();
this.curvedSurfaces = {};
this.mergeable = true;
this.setupGeometry();
};
}
TCAD.Solid.prototype.setupGeometry = function() {
Solid.prototype.setupGeometry = function() {
function threeV(v) {return new THREE.Vector3( v.x, v.y, v.z )}
var off = 0;
var groups = TCAD.utils.groupCSG(this.csg);
var groups = groupCSG(this.csg);
var geom = this.mesh.geometry;
for (var gIdx in groups) {
var group = groups[gIdx];
if (group.shared.__tcad === undefined) group.shared.__tcad = {};
var polyFace = new TCAD.SketchFace(this, group);
var polyFace = new SketchFace(this, group);
this.polyFaces.push(polyFace);
for (var p = 0; p < group.polygons.length; ++p) {
var poly = group.polygons[p];
@ -684,7 +651,7 @@ TCAD.Solid.prototype.setupGeometry = function() {
geom.faces.push(face);
//face.color.set(new THREE.Color().setRGB( Math.random(), Math.random(), Math.random()));
}
//TCAD.view.setFaceColor(polyFace, TCAD.utils.isSmoothPiece(group.shared) ? 0xFF0000 : null);
//view.setFaceColor(polyFace, utils.isSmoothPiece(group.shared) ? 0xFF0000 : null);
off = geom.vertices.length;
}
this.collectCurvedSurface(polyFace);
@ -696,14 +663,14 @@ TCAD.Solid.prototype.setupGeometry = function() {
this.processWires();
};
TCAD.Solid.prototype.vanish = function() {
Solid.prototype.vanish = function() {
this.cadGroup.parent.remove( this.cadGroup );
this.mesh.material.dispose();
this.mesh.geometry.dispose();
};
TCAD.Solid.prototype.collectCurvedSurface = function(face) {
var derivedFrom = TCAD.utils.getDerivedFrom(face.csgGroup.shared);
Solid.prototype.collectCurvedSurface = function(face) {
var derivedFrom = getDerivedFrom(face.csgGroup.shared);
if (derivedFrom === null || derivedFrom._class !== "TCAD.TWO.Arc" && derivedFrom._class !== "TCAD.TWO.Circle" ) return;
var surfaces = this.curvedSurfaces[derivedFrom.id];
if (surfaces === undefined) {
@ -714,7 +681,7 @@ TCAD.Solid.prototype.collectCurvedSurface = function(face) {
face.curvedSurfaces = surfaces;
};
TCAD.Solid.prototype.collectWires = function(face) {
Solid.prototype.collectWires = function(face) {
function contains(planes, plane) {
for (var j = 0; j < planes.length; j++) {
@ -724,7 +691,7 @@ TCAD.Solid.prototype.collectWires = function(face) {
}
return false;
}
var paths = TCAD.craft.reconstructSketchBounds(this.csg, face, true);
var paths = reconstructSketchBounds(this.csg, face, true);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var p, q, n = path.vertices.length;
@ -748,17 +715,16 @@ TCAD.Solid.prototype.collectWires = function(face) {
}
};
TCAD.Solid.SMOOTH_LIMIT = 10 * Math.PI / 180;
Solid.SMOOTH_LIMIT = 10 * Math.PI / 180;
TCAD.Solid.prototype.processWires = function() {
Solid.prototype.processWires = function() {
var solid = this;
this.wires.entries(function(edge, data) {
var u = TCAD.utils;
if (data.sharedPlanes.length > 1) {
var plane0 = data.sharedPlanes[0];
var plane1 = data.sharedPlanes[1];
var angle = Math.acos(plane0.normal.dot(plane1.normal));
if (angle < TCAD.Solid.SMOOTH_LIMIT) {
if (angle < Solid.SMOOTH_LIMIT) {
return;
}
}
@ -766,7 +732,7 @@ TCAD.Solid.prototype.processWires = function() {
for (var j = i + 1; j < data.sharedFaces.length; ++j) {
var face0 = data.sharedFaces[0];
var face1 = data.sharedFaces[1];
if (u.sameID(u.getDerivedID(face0.csgGroup.shared), u.getDerivedID(face1.csgGroup.shared))) {
if (sameID(getDerivedID(face0.csgGroup.shared), getDerivedID(face1.csgGroup.shared))) {
return;
}
}
@ -776,16 +742,16 @@ TCAD.Solid.prototype.processWires = function() {
});
};
TCAD.Solid.prototype.addLineToScene = function(a, b) {
Solid.prototype.addLineToScene = function(a, b) {
var lg = new THREE.Geometry();
lg.vertices.push(a);
lg.vertices.push(b);
var line = new THREE.Line(lg, TCAD.SketchFace.prototype.WIREFRAME_MATERIAL);
var line = new THREE.Line(lg, SketchFace.prototype.WIREFRAME_MATERIAL);
this.wireframeGroup.add(line);
};
/** @constructor */
TCAD.SketchFace = function(solid, csgGroup) {
function SketchFace(solid, csgGroup) {
csgGroup.__face = this;
if (csgGroup.shared.__tcad.faceId === undefined) {
this.id = solid.tCadId + ":" + (solid.faceCounter++);
@ -799,44 +765,43 @@ TCAD.SketchFace = function(solid, csgGroup) {
this.faces = [];
this.sketch3DGroup = null;
this.curvedSurfaces = null;
};
if (typeof THREE !== "undefined") {
TCAD.SketchFace.prototype.SKETCH_MATERIAL = new THREE.LineBasicMaterial({
color: 0xFFFFFF, linewidth: 3/TCAD.DPR});
TCAD.SketchFace.prototype.WIREFRAME_MATERIAL = new THREE.LineBasicMaterial({
color: 0x2B3856, linewidth: 3/TCAD.DPR});
}
TCAD.SketchFace.prototype.calcBasis = function() {
var vec = TCAD.utils.vec;
if (typeof THREE !== "undefined") {
SketchFace.prototype.SKETCH_MATERIAL = new THREE.LineBasicMaterial({
color: 0xFFFFFF, linewidth: 3/DPR});
SketchFace.prototype.WIREFRAME_MATERIAL = new THREE.LineBasicMaterial({
color: 0x2B3856, linewidth: 3/DPR});
}
SketchFace.prototype.calcBasis = function() {
var normal = vec(this.csgGroup.plane.normal);
var alignPlane, x, y;
if (Math.abs(normal.dot(TCAD.math.AXIS.Y)) < 0.5) {
alignPlane = normal.cross(TCAD.math.AXIS.Y);
if (Math.abs(normal.dot(AXIS.Y)) < 0.5) {
alignPlane = normal.cross(AXIS.Y);
} else {
alignPlane = normal.cross(TCAD.math.AXIS.Z);
alignPlane = normal.cross(AXIS.Z);
}
y = alignPlane.cross(normal);
x = y.cross(normal);
return [x, y, normal];
};
TCAD.SketchFace.prototype.basis = function() {
SketchFace.prototype.basis = function() {
if (!this._basis) {
this._basis = this.calcBasis();
}
return this._basis;
//return TCAD.geom.someBasis(this.csgGroup.polygons[0].vertices.map(function (v) {
//return someBasis(this.csgGroup.polygons[0].vertices.map(function (v) {
// return vec(v.pos)
//}), vec(this.csgGroup.plane.normal));
};
TCAD.SketchFace.prototype.depth = function() {
SketchFace.prototype.depth = function() {
return this.csgGroup.plane.w;
};
TCAD.SketchFace.prototype.syncSketches = function(geom) {
SketchFace.prototype.syncSketches = function(geom) {
var i;
var normal = this.csgGroup.plane.normal;
var offVector = normal.scale(0); // disable it. use polygon offset feature of material
@ -851,10 +816,10 @@ TCAD.SketchFace.prototype.syncSketches = function(geom) {
}
var basis = this.basis();
var _3dTransformation = new TCAD.Matrix().setBasis(basis);
var _3dTransformation = new Matrix3().setBasis(basis);
//we lost depth or z off in 2d sketch, calculate it again
var depth = this.csgGroup.plane.w;
var connections = geom.connections.concat(TCAD.utils.arrFlatten1L(geom.loops));
var connections = geom.connections.concat(arrFlatten1L(geom.loops));
for (i = 0; i < connections.length; ++i) {
var l = connections[i];
var lg = new THREE.Geometry();
@ -869,26 +834,27 @@ TCAD.SketchFace.prototype.syncSketches = function(geom) {
}
};
TCAD.POLYGON_COUNTER = 0;
var POLYGON_COUNTER = 0;
/** @constructor */
TCAD.Polygon = function(shell, holes, normal) {
this.id = TCAD.POLYGON_COUNTER ++;
export function Polygon(shell, holes, normal) {
this.id = POLYGON_COUNTER ++;
if (!holes) {
holes = [];
}
TCAD.utils.checkPolygon(shell);
for (var h = 0; h < holes.length; ++h) {
TCAD.utils.checkPolygon(holes[h]);
var h;
checkPolygon(shell);
for (h = 0; h < holes.length; ++h) {
checkPolygon(holes[h]);
}
if (normal === undefined) {
normal = TCAD.geom.normalOfCCWSeq(shell);
normal = normalOfCCWSeq(shell);
} else {
shell = TCAD.utils.fixCCW(shell, normal);
shell = fixCCW(shell, normal);
if (holes.length > 0) {
var neg = normal.negate();
for (var h = 0; h < holes.length; ++h) {
holes[h] = TCAD.utils.fixCCW(holes[h], neg);
for (h = 0; h < holes.length; ++h) {
holes[h] = fixCCW(holes[h], neg);
}
}
@ -897,19 +863,19 @@ TCAD.Polygon = function(shell, holes, normal) {
this.normal = normal;
this.shell = shell;
this.holes = holes;
};
}
TCAD.Polygon.prototype.reverse = function(triangle) {
Polygon.prototype.reverse = function(triangle) {
var first = triangle[0];
triangle[0] = triangle[2];
triangle[2] = first;
};
TCAD.Polygon.prototype.flip = function() {
return new TCAD.Polygon(this.shell, this.holes, this.normal.negate());
Polygon.prototype.flip = function() {
return new Polygon(this.shell, this.holes, this.normal.negate());
};
TCAD.Polygon.prototype.shift = function(target) {
Polygon.prototype.shift = function(target) {
var shell = [];
var i;
for (i = 0; i < this.shell.length; ++i) {
@ -922,16 +888,16 @@ TCAD.Polygon.prototype.shift = function(target) {
holes[h][i] = this.holes[h][i].plus(target);
}
}
return new TCAD.Polygon(shell, holes, this.normal);
return new Polygon(shell, holes, this.normal);
};
TCAD.Polygon.prototype.get2DTransformation = function() {
var _3dTransformation = new TCAD.Matrix().setBasis(TCAD.geom.someBasis(this.shell, this.normal));
Polygon.prototype.get2DTransformation = function() {
var _3dTransformation = new Matrix3().setBasis(someBasis(this.shell, this.normal));
var _2dTransformation = _3dTransformation.invert();
return _2dTransformation;
};
TCAD.Polygon.prototype.to2D = function() {
Polygon.prototype.to2D = function() {
var _2dTransformation = this.get2DTransformation();
@ -950,12 +916,12 @@ TCAD.Polygon.prototype.to2D = function() {
return {shell: shell, holes: holes};
};
TCAD.Polygon.prototype.collectPaths = function(paths) {
Polygon.prototype.collectPaths = function(paths) {
paths.push(this.shell);
paths.push.apply(paths, this.holes);
};
TCAD.Polygon.prototype.triangulate = function() {
Polygon.prototype.triangulate = function() {
function triangulateShape( contour, holes ) {
var myTriangulator = new PNLTRI.Triangulator();
@ -977,7 +943,7 @@ TCAD.Polygon.prototype.triangulate = function() {
// return THREE.Shape.utils.triangulateShape( f2d.shell, f2d.holes );
};
TCAD.Polygon.prototype.eachVertex = function(handler) {
Polygon.prototype.eachVertex = function(handler) {
var i, h;
for (i = 0; i < this.shell.length; ++i) {
if (handler(this.shell, i) === true) return;
@ -990,11 +956,11 @@ TCAD.Polygon.prototype.eachVertex = function(handler) {
};
/** @constructor */
TCAD.Sketch = function() {
export function Sketch() {
this.group = new THREE.Object3D();
};
}
TCAD.utils.iteratePath = function(path, shift, callback) {
export function iteratePath(path, shift, callback) {
var p, q, n = path.length;
for (p = n - 1,q = 0;q < n; p = q++) {
var ai = (p + shift) % n;
@ -1003,18 +969,18 @@ TCAD.utils.iteratePath = function(path, shift, callback) {
break
}
}
};
}
TCAD.utils.addAll = function(arr, arrToAdd) {
export function addAll(arr, arrToAdd) {
for (var i = 0; i < arrToAdd.length; i++) {
arr.push(arrToAdd[i]);
}
};
}
TCAD.utils.arrFlatten1L = function(arr) {
export function arrFlatten1L(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
TCAD.utils.addAll(result, arr[i]);
addAll(result, arr[i]);
}
return result;
};
}

View file

@ -1,30 +1,28 @@
TCAD.struct = {};
TCAD.struct.HashTable = function(hashCodeF, equalsF) {
function HashTable(hashCodeF, equalsF) {
this.hashCodeF = hashCodeF;
this.equalsF = equalsF;
this.setTableSize(8);
this.size = 0;
};
}
TCAD.struct.HashTable.prototype.hash = function(key) {
HashTable.prototype.hash = function(key) {
return Math.abs(this.hashCodeF(key) % this.table.length);
};
TCAD.struct.HashTable.prototype.get = function(key) {
HashTable.prototype.get = function(key) {
var entry = this._findEntry(key, this._findBucket(key));
if (entry == null) return null;
return entry[1];
};
TCAD.struct.HashTable.prototype.put = function(key, value) {
HashTable.prototype.put = function(key, value) {
if (this.size >= 0.75 * this.table.length) {
this.rebuild();
}
this._put(key, value);
};
TCAD.struct.HashTable.prototype._findBucket = function(key) {
HashTable.prototype._findBucket = function(key) {
var hash = this.hash(key);
var bucket = this.table[hash];
if (bucket === null) {
@ -34,7 +32,7 @@ TCAD.struct.HashTable.prototype._findBucket = function(key) {
return bucket;
};
TCAD.struct.HashTable.prototype._findEntry = function(key, bucket) {
HashTable.prototype._findEntry = function(key, bucket) {
for (var i = 0; i < bucket.length; i++) {
if (this.equalsF(bucket[i][0], key)) {
return bucket[i];
@ -43,7 +41,7 @@ TCAD.struct.HashTable.prototype._findEntry = function(key, bucket) {
return null;
};
TCAD.struct.HashTable.prototype._put = function(key, value) {
HashTable.prototype._put = function(key, value) {
var bucket = this._findBucket(key);
var entry = this._findEntry(key, bucket);
if (entry == null) {
@ -54,7 +52,7 @@ TCAD.struct.HashTable.prototype._put = function(key, value) {
this.size++;
};
TCAD.struct.HashTable.prototype.rebuild = function() {
HashTable.prototype.rebuild = function() {
this.size = 0;
var oldTable = this.table;
this.setTableSize(this.table.length * 2);
@ -69,7 +67,7 @@ TCAD.struct.HashTable.prototype.rebuild = function() {
}
};
TCAD.struct.HashTable.prototype.getKeys = function() {
HashTable.prototype.getKeys = function() {
var keys = [];
this.entries(function(k) {
keys.push(k)
@ -77,7 +75,7 @@ TCAD.struct.HashTable.prototype.getKeys = function() {
return keys;
};
TCAD.struct.HashTable.prototype.entries = function(callback) {
HashTable.prototype.entries = function(callback) {
for (var i = 0; i < this.table.length; i++) {
var e = this.table[i];
if (e != null) {
@ -89,38 +87,35 @@ TCAD.struct.HashTable.prototype.entries = function(callback) {
}
};
TCAD.struct.HashTable.prototype.setTableSize = function(newSize) {
HashTable.prototype.setTableSize = function(newSize) {
this.table = [];
for (var i = 0; i < newSize; i++) {
this.table[i] = null;
}
};
TCAD.struct.hashTable = {};
TCAD.struct.hashTable.DoubleHelper = function() {
function DoubleHelper() {
this.dv = new DataView(new ArrayBuffer(8));
};
}
TCAD.struct.hashTable.DoubleHelper.prototype.hash = function(v) {
DoubleHelper.prototype.hash = function(v) {
this.dv.setFloat64(0, v);
return this.dv.getInt32(0) ^ this.dv.getInt32(4);
};
TCAD.struct.hashTable.vectorEquals = function(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z;
};
TCAD.struct.hashTable.forVector3d = function() {
var doubleHelper = new TCAD.struct.hashTable.DoubleHelper();
HashTable.forVector3d = function() {
var doubleHelper = new DoubleHelper();
function hash(v) {
return doubleHelper.hash(v.x) ^ doubleHelper.hash(v.y) ^ doubleHelper.hash(v.z);
}
return new TCAD.struct.HashTable(hash, TCAD.struct.hashTable.vectorEquals);
function eq(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z;
}
return new HashTable(hash, eq);
};
TCAD.struct.hashTable.forEdge = function() {
var doubleHelper = new TCAD.struct.hashTable.DoubleHelper();
HashTable.forEdge = function() {
var doubleHelper = new DoubleHelper();
function hash(v) {
return doubleHelper.hash(v[0].x) ^ doubleHelper.hash(v[0].y) ^ doubleHelper.hash(v[0].z)
^doubleHelper.hash(v[1].x) ^ doubleHelper.hash(v[1].y) ^ doubleHelper.hash(v[1].z);
@ -135,22 +130,22 @@ TCAD.struct.hashTable.forEdge = function() {
var b2 = e2[1];
return (veq(a1, a2) && veq(b1, b2)) || (veq(a1, b2) && veq(b1, a2));
}
return new TCAD.struct.HashTable(hash, eq);
return new HashTable(hash, eq);
};
TCAD.struct.hashTable.forVector2d = function() {
var doubleHelper = new TCAD.struct.hashTable.DoubleHelper();
HashTable.forVector2d = function() {
var doubleHelper = new DoubleHelper();
function hash(v) {
return doubleHelper.hash(v.x) ^ doubleHelper.hash(v.y) ;
}
function eq(a, b) {
return a.x === b.x && a.y === b.y;
}
return new TCAD.struct.HashTable(hash, eq);
return new HashTable(hash, eq);
};
TCAD.struct.hashTable.forDoubleArray = function() {
var doubleHelper = new TCAD.struct.hashTable.DoubleHelper();
HashTable.forDoubleArray = function() {
var doubleHelper = new DoubleHelper();
function hash(v) {
var hash = 0;
for (var i = 0; i < v.length; i++) {
@ -164,5 +159,7 @@ TCAD.struct.hashTable.forDoubleArray = function() {
}
return true;
}
return new TCAD.struct.HashTable(hash, eq);
return new HashTable(hash, eq);
};
export {HashTable, DoubleHelper}

36
web/app/utils/utils.js Normal file
View file

@ -0,0 +1,36 @@
export function askNumber(promptText, initValue, promptCallback, resolver) {
var promptValueStr = promptCallback(promptText, initValue);
if (promptValueStr != null) {
var promptValue = Number(promptValueStr);
if (promptValue == promptValue) { // check for NaN
return promptValue;
} else {
if (!!resolver) {
promptValue = resolver(promptValueStr);
if (promptValue == promptValue) {
return promptValueStr;
}
}
}
}
return null;
}
export const extend = function(func, parent) {
for(var prop in parent.prototype) {
if(parent.prototype.hasOwnProperty(prop))
func.prototype[prop] = parent.prototype[prop];
}
};
export function fillArray(a, fromIndex, toIndex,val) {
for (var i = fromIndex; i < toIndex; i++)
a[i] = val;
}
export function constRef(value) {
return function() {
return value;
};
}

View file

@ -21,22 +21,7 @@
<script src="lib/csg.js"></script>
<script src="lib/formats.js"></script>
<script src="lib/pnltri.js"></script>
<script src="app/3d/main.js"></script>
<script src="app/3d/ctrl.js"></script>
<script src="app/3d/viewer.js"></script>
<script src="app/engine.js"></script>
<script src="app/math/vector.js"></script>
<script src="app/math/math.js"></script>
<script src="app/workbench.js"></script>
<script src="app/math/graph.js"></script>
<script src="app/3d/hashmap.js"></script>
<script src="app/ui/toolkit.js"></script>
<script src="app/3d/wizards/wizards.js"></script>
<script src="app/sketcher/io.js"></script>
<script>window.onload = function() {
window._TCAD_APP = new TCAD.App();
}</script>
<script src="/static/index.bundle.js"></script>
</head>
<body>
<a id="downloader" style="display: none;" ></a>

View file

@ -7,39 +7,6 @@
<link rel="stylesheet" href="css/toolkit.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.min.css">
<script src="lib/jquery-2.1.0.min.js"></script>
<script src="lib/numeric-1.2.6.js"></script>
<script src="lib/diff_match_patch.js"></script>
<!--$$$javascript_start$$$-->
<script src="app/sketcher/canvas.js"></script>
<script src="app/sketcher/io.js"></script>
<script src="app/sketcher/history.js"></script>
<script src="app/sketcher/shapes/arc.js"></script>
<script src="app/sketcher/shapes/circle.js"></script>
<script src="app/sketcher/shapes/segment.js"></script>
<script src="app/sketcher/shapes/dim.js"></script>
<script src="app/sketcher/helpers.js"></script>
<script src="app/math/vector.js"></script>
<script src="app/math/math.js"></script>
<script src="app/math/qr.js"></script>
<script src="app/math/matrix.js"></script>
<script src="app/math/optim.js"></script>
<script src="app/math/lm.js"></script>
<script src="app/sketcher/constr/constraints.js"></script>
<script src="app/sketcher/constr/solver.js"></script>
<script src="app/sketcher/parametric.js"></script>
<script src="app/sketcher/fetchers.js"></script>
<script src="app/engine.js"></script>
<script src="app/sketcher/main2d.js"></script>
<script src="app/ui.js"></script>
<script src="app/ui/toolkit.js"></script>
<script src="app/math/graph.js"></script>
<script src="app/app-init.js"></script>
<!--$$$javascript_end$$$-->
</head>
<body>
<a id="downloader" style="display: none;" ></a>
@ -143,5 +110,6 @@
</div>
<!--<div id="log" style="position:absolute; width: 500px; height: 300px; top:500px; pxleft:0; overflow: scroll;background-color: salmon;">-->
<script src="/static/sketcher.bundle.js"></script>
</body>
</html>

View file

@ -1,66 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<html>
<head>
<title>Sketcher Tests</title>
<style>
body {
font-family: Monospace;
color: white;
overflow: hidden;
}
html, body {
background: gray;
height: 100%;
}
.err {color: red;}
</style>
<script src="lib/jquery-2.1.0.min.js"></script>
<script src="lib/three/three.js"></script>
<script src="lib/numeric-1.2.6.js"></script>
<script src="app/sketcher/canvas.js"></script>
<script src="app/sketcher/shapes/arc.js"></script>
<script src="app/sketcher/shapes/circle.js"></script>
<script src="app/sketcher/shapes/segment.js"></script>
<script src="app/sketcher/shapes/dim.js"></script>
<script src="app/math/vector.js"></script>
<script src="app/math/math.js"></script>
<script src="app/math/qr.js"></script>
<script src="app/math/matrix.js"></script>
<script src="app/math/optim.js"></script>
<script src="app/math/lm.js"></script>
<script src="app/sketcher/constr/constraints.js"></script>
<script src="app/sketcher/constr/solver.js"></script>
<script src="app/sketcher/parametric.js"></script>
<script src="app/sketcher/fetchers.js"></script>
<script src="app/engine.js"></script>
<script src="app/sketcher/main2d.js"></script>
<script src="app/workbench.js"></script>
<script src="app/ui.js"></script>
<script src="app/math/graph.js"></script>
<script src="app/test/suite.js"></script>
<script src="app/test/fixtures.js"></script>
<script src="app/test/testCases.js"></script>
<script>
function start() {
APP = new TCAD.App2D();
TCAD.test.runSuite();
}
window.onload = function() {
setTimeout(start, 0);
};
</script>
</head>
<body>
<canvas width="300" height="300" style="height: 301px;" id="viewer"></canvas>
<h3>TEST RESULTS</h3>
<div id="testOutput"></div>
</body>
</html>

0
web/app/test/viz.sh → web/test/viz.sh Executable file → Normal file
View file

29
webpack.config.js Normal file
View file

@ -0,0 +1,29 @@
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: {
index: ['./web/app/index', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server' ],
sketcher: ['./web/app/sketcher', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server' ]
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'web/app')
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}]
}
};