use three as modules

This commit is contained in:
casperlamboo 2017-12-06 11:54:09 +01:00
parent 5f1e628952
commit 6b84572931
14 changed files with 94 additions and 61 deletions

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import * as THREE from 'three'; import { JSONLoader } from 'three/src/loaders/JSONLoader.js';
import { Interface } from 'doodle3d-slicer'; import { Interface } from 'doodle3d-slicer';
import fileURL from '!url-loader!./models/shape.json'; import fileURL from '!url-loader!./models/shape.json';
import { render } from 'react-dom'; import { render } from 'react-dom';
@ -20,7 +20,7 @@ const downloadGCode = ({ gcode: { gcode } }) => {
fileSaver.saveAs(file); fileSaver.saveAs(file);
}; };
const jsonLoader = new THREE.JSONLoader(); const jsonLoader = new JSONLoader();
jsonLoader.load(fileURL, geometry => { jsonLoader.load(fileURL, geometry => {
render(( render((
<MuiThemeProvider> <MuiThemeProvider>

12
package-lock.json generated
View File

@ -5677,6 +5677,12 @@
"unpipe": "1.0.0" "unpipe": "1.0.0"
} }
}, },
"raw-loader": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-0.5.1.tgz",
"integrity": "sha1-DD0L6u2KAclm2Xh793goElKpeao=",
"dev": true
},
"react": { "react": {
"version": "16.1.0", "version": "16.1.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.1.0.tgz", "resolved": "https://registry.npmjs.org/react/-/react-16.1.0.tgz",
@ -6478,9 +6484,9 @@
} }
}, },
"three": { "three": {
"version": "0.83.0", "version": "0.88.0",
"resolved": "https://registry.npmjs.org/three/-/three-0.83.0.tgz", "resolved": "https://registry.npmjs.org/three/-/three-0.88.0.tgz",
"integrity": "sha1-O3+UeQrz4CHawfRKJhdWnKIDKws=" "integrity": "sha1-QlbC/Djk+yOg0j66K2zOTfjkZtU="
}, },
"thunky": { "thunky": {
"version": "0.1.0", "version": "0.1.0",

View File

@ -23,9 +23,10 @@
"react-dom": "^16.0.0", "react-dom": "^16.0.0",
"react-jss": "^7.2.0", "react-jss": "^7.2.0",
"react-resize-detector": "^1.1.0", "react-resize-detector": "^1.1.0",
"three": "^0.83.0" "three": "^0.88.0"
}, },
"devDependencies": { "devDependencies": {
"raw-loader": "^0.5.1",
"babel-plugin-inline-import": "^2.0.6", "babel-plugin-inline-import": "^2.0.6",
"babel-preset-stage-0": "^6.24.1", "babel-preset-stage-0": "^6.24.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0", "babel-plugin-syntax-dynamic-import": "^6.18.0",

View File

@ -1,6 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
import React from 'react'; import React from 'react';
import * as THREE from 'three'; import { Quaternion } from 'three/src/math/Quaternion.js';
import { Vector3 } from 'three/src/math/Vector3.js';
import PropTypes from 'proptypes'; import PropTypes from 'proptypes';
import { placeOnGround, createScene, fetchProgress, slice, TabTemplate } from './utils.js'; import { placeOnGround, createScene, fetchProgress, slice, TabTemplate } from './utils.js';
import injectSheet from 'react-jss'; import injectSheet from 'react-jss';
@ -161,16 +162,13 @@ class Interface extends React.Component {
} }
}; };
rotateX = () => this.rotate(new THREE.Vector3(0, 0, 1), Math.PI / 2.0); rotateX = () => this.rotate(new Vector3(0, 0, 1), Math.PI / 2.0);
rotateY = () => this.rotate(new THREE.Vector3(1, 0, 0), Math.PI / 2.0); rotateY = () => this.rotate(new Vector3(1, 0, 0), Math.PI / 2.0);
rotateZ = () => this.rotate(new THREE.Vector3(0, 1, 0), Math.PI / 2.0); rotateZ = () => this.rotate(new Vector3(0, 1, 0), Math.PI / 2.0);
rotate = (axis, angle) => { rotate = (axis, angle) => {
const { mesh, render } = this.state; const { mesh, render } = this.state;
if (mesh) { if (mesh) {
const quaternion = new THREE.Quaternion(); mesh.rotateOnWorldAxis(axis, angle);
quaternion.setFromAxisAngle(axis, angle);
mesh.quaternion.premultiply(quaternion);
mesh.updateMatrix();
placeOnGround(mesh); placeOnGround(mesh);
render(); render();
} }

View File

@ -1,4 +1,16 @@
import * as THREE from 'three'; import * as THREE from 'three';
import { Box3 } from 'three/src/math/Box3.js';
import { Matrix4 } from 'three/src/math/Matrix4.js';
import { Scene } from 'three/src/scenes/Scene.js';
import { PerspectiveCamera } from 'three/src/cameras/PerspectiveCamera.js';
import { AmbientLight } from 'three/src/lights/AmbientLight.js';
import { DirectionalLight } from 'three/src/lights/DirectionalLight.js';
import { MeshPhongMaterial } from 'three/src/materials/MeshPhongMaterial.js';
import { BoxGeometry } from 'three/src/geometries/BoxGeometry.js';
import { Mesh } from 'three/src/objects/Mesh.js';
import { BoxHelper } from 'three/src/helpers/BoxHelper.js';
import { WebGLRenderer } from 'three/src/renderers/WebGLRenderer.js';
import { DoubleSide } from 'three/src/constants.js';
import 'three/examples/js/controls/EditorControls'; import 'three/examples/js/controls/EditorControls';
import printerSettings from '../settings/printer.yml'; import printerSettings from '../settings/printer.yml';
import materialSettings from '../settings/material.yml'; import materialSettings from '../settings/material.yml';
@ -8,7 +20,7 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
export function placeOnGround(mesh) { export function placeOnGround(mesh) {
const boundingBox = new THREE.Box3().setFromObject(mesh); const boundingBox = new Box3().setFromObject(mesh);
mesh.position.y -= boundingBox.min.y; mesh.position.y -= boundingBox.min.y;
mesh.updateMatrix(); mesh.updateMatrix();
@ -21,30 +33,30 @@ export function createScene(canvas, props, state) {
// center geometry // center geometry
geometry.computeBoundingBox(); geometry.computeBoundingBox();
const center = geometry.boundingBox.getCenter(); const center = geometry.boundingBox.getCenter();
geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z)); geometry.applyMatrix(new Matrix4().makeTranslation(-center.x, -center.y, -center.z));
const scene = new THREE.Scene(); const scene = new Scene();
const camera = new THREE.PerspectiveCamera(50, 1, 1, 10000); const camera = new PerspectiveCamera(50, 1, 1, 10000);
camera.position.set(0, 400, 300); camera.position.set(0, 400, 300);
const directionalLightA = new THREE.DirectionalLight(0xa2a2a2); const directionalLightA = new DirectionalLight(0xa2a2a2);
directionalLightA.position.set(1, 1, 1); directionalLightA.position.set(1, 1, 1);
scene.add(directionalLightA); scene.add(directionalLightA);
const directionalLightB = new THREE.DirectionalLight(0xa2a2a2); const directionalLightB = new DirectionalLight(0xa2a2a2);
directionalLightB.position.set(-1, 1, -1); directionalLightB.position.set(-1, 1, -1);
scene.add(directionalLightB); scene.add(directionalLightB);
const light = new THREE.AmbientLight(0x656565); const light = new AmbientLight(0x656565);
scene.add(light); scene.add(light);
const material = new THREE.MeshPhongMaterial({ color: 0x2194ce, side: THREE.DoubleSide, specular: 0xc5c5c5, shininess: 5 }); const material = new MeshPhongMaterial({ color: 0x2194ce, side: DoubleSide, specular: 0xc5c5c5, shininess: 5 });
const mesh = new THREE.Mesh(geometry, material); const mesh = new Mesh(geometry, material);
placeOnGround(mesh); placeOnGround(mesh);
scene.add(mesh); scene.add(mesh);
const box = new THREE.BoxHelper(new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1).applyMatrix(new THREE.Matrix4().makeTranslation(0, 0.5, 0))), 0x72bcd4); const box = new BoxHelper(new Mesh(new BoxGeometry(1, 1, 1).applyMatrix(new Matrix4().makeTranslation(0, 0.5, 0))), 0x72bcd4);
scene.add(box); scene.add(box);
const { dimensions } = settings; const { dimensions } = settings;
@ -66,7 +78,7 @@ export function createScene(canvas, props, state) {
const updateCanvas = (canvas) => { const updateCanvas = (canvas) => {
if (!renderer || renderer.domElement !== canvas) { if (!renderer || renderer.domElement !== canvas) {
if (renderer) renderer.dispose(); if (renderer) renderer.dispose();
renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true }); renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
renderer.setClearColor(0xffffff, 0); renderer.setClearColor(0xffffff, 0);
} }
if (!editorControls || editorControls.domElement !== canvas) { if (!editorControls || editorControls.domElement !== canvas) {
@ -106,6 +118,8 @@ const GCODE_SERVER_URL = 'https://gcodeserver.doodle3d.com';
const CONNECT_URL = 'http://connect.doodle3d.com/'; const CONNECT_URL = 'http://connect.doodle3d.com/';
export async function slice(name, mesh, settings, printers, quality, material, updateProgress) { export async function slice(name, mesh, settings, printers, quality, material, updateProgress) {
if (!printers) throw new Error('Please select a printer');
const { dimensions } = settings; const { dimensions } = settings;
const centerX = dimensions.x / 2; const centerX = dimensions.x / 2;
const centerY = dimensions.y / 2; const centerY = dimensions.y / 2;
@ -113,7 +127,7 @@ export async function slice(name, mesh, settings, printers, quality, material, u
const geometry = mesh.geometry.clone(); const geometry = mesh.geometry.clone();
mesh.updateMatrix(); mesh.updateMatrix();
const matrix = new THREE.Matrix4().makeTranslation(centerY, 0, centerX).multiply(mesh.matrix); const matrix = new Matrix4().makeTranslation(centerY, 0, centerX).multiply(mesh.matrix);
const { gcode } = await sliceGeometry(settings, geometry, matrix, false, false, ({ progress }) => { const { gcode } = await sliceGeometry(settings, geometry, matrix, false, false, ({ progress }) => {
updateProgress({ updateProgress({
action: progress.action, action: progress.action,

View File

@ -1,4 +1,4 @@
import * as THREE from 'three'; import { Vector2 } from 'three/src/math/Vector2.js';
export default function calculateLayersIntersections(lines, settings) { export default function calculateLayersIntersections(lines, settings) {
const { const {
@ -38,7 +38,7 @@ export default function calculateLayersIntersections(lines, settings) {
z = line.end.z * alpha + line.start.z * alpha1; z = line.end.z * alpha + line.start.z * alpha1;
} }
layerIntersectionPoints[layerIndex][lineIndex] = new THREE.Vector2(z, x); layerIntersectionPoints[layerIndex][lineIndex] = new Vector2(z, x);
} }
} }
} }

View File

@ -1,11 +1,12 @@
import * as THREE from 'three'; import { Line3 } from 'three/src/math/Line3.js';
import { Vector2 } from 'three/src/math/Vector2.js';
function addLine(geometry, lineLookup, lines, a, b, isFlat) { function addLine(geometry, lineLookup, lines, a, b, isFlat) {
const index = lines.length; const index = lines.length;
lineLookup[`${a}_${b}`] = index; lineLookup[`${a}_${b}`] = index;
lines.push({ lines.push({
line: new THREE.Line3(geometry.vertices[a], geometry.vertices[b]), line: new Line3(geometry.vertices[a], geometry.vertices[b]),
connects: [], connects: [],
normals: [], normals: [],
isFlat isFlat
@ -38,7 +39,7 @@ export default function createLines(geometry, settings) {
lines[lineIndexB].connects.push(lineIndexC, lineIndexA); lines[lineIndexB].connects.push(lineIndexC, lineIndexA);
lines[lineIndexC].connects.push(lineIndexA, lineIndexB); lines[lineIndexC].connects.push(lineIndexA, lineIndexB);
const normal = new THREE.Vector2(face.normal.z, face.normal.x).normalize(); const normal = new Vector2(face.normal.z, face.normal.x).normalize();
lines[lineIndexA].normals.push(normal); lines[lineIndexA].normals.push(normal);
lines[lineIndexB].normals.push(normal); lines[lineIndexB].normals.push(normal);
lines[lineIndexC].normals.push(normal); lines[lineIndexC].normals.push(normal);

View File

@ -1,4 +1,4 @@
import * as THREE from 'three'; import { Vector2 } from 'three/src/math/Vector2.js';
import { PRECISION } from '../../constants.js'; import { PRECISION } from '../../constants.js';
export const MOVE = 'G'; export const MOVE = 'G';
@ -16,7 +16,7 @@ export default class {
this._gcode = []; this._gcode = [];
this._currentValues = {}; this._currentValues = {};
this._nozzlePosition = new THREE.Vector2(0, 0); this._nozzlePosition = new Vector2(0, 0);
this._extruder = 0.0; this._extruder = 0.0;
this._duration = 0.0; this._duration = 0.0;
this._isRetracted = false; this._isRetracted = false;
@ -47,7 +47,7 @@ export default class {
} }
moveTo(x, y, z, { speed }) { moveTo(x, y, z, { speed }) {
const newNozzlePosition = new THREE.Vector2(x, y).multiplyScalar(PRECISION); const newNozzlePosition = new Vector2(x, y).multiplyScalar(PRECISION);
const lineLength = this._nozzlePosition.distanceTo(newNozzlePosition); const lineLength = this._nozzlePosition.distanceTo(newNozzlePosition);
this._duration += lineLength / speed; this._duration += lineLength / speed;
@ -66,7 +66,7 @@ export default class {
} }
lineTo(x, y, z, { speed, flowRate }) { lineTo(x, y, z, { speed, flowRate }) {
const newNozzlePosition = new THREE.Vector2(x, y).multiplyScalar(PRECISION); const newNozzlePosition = new Vector2(x, y).multiplyScalar(PRECISION);
const lineLength = this._nozzlePosition.distanceTo(newNozzlePosition); const lineLength = this._nozzlePosition.distanceTo(newNozzlePosition);
this._extruder += this._nozzleToFilamentRatio * lineLength * flowRate; this._extruder += this._nozzleToFilamentRatio * lineLength * flowRate;

View File

@ -1,4 +1,4 @@
import * as THREE from 'three'; import { Vector2 } from 'three/src/math/Vector2.js';
import Shape from 'clipper-js'; import Shape from 'clipper-js';
export default function intersectionsToShapes(layerIntersectionIndexes, layerIntersectionPoints, lines, settings) { export default function intersectionsToShapes(layerIntersectionIndexes, layerIntersectionPoints, lines, settings) {
@ -48,8 +48,8 @@ export default function intersectionsToShapes(layerIntersectionIndexes, layerInt
if (typeof intersectionPoints[index] !== 'undefined') { if (typeof intersectionPoints[index] !== 'undefined') {
const faceNormal = faceNormals[Math.floor(i / 2)]; const faceNormal = faceNormals[Math.floor(i / 2)];
const a = new THREE.Vector2(intersection.x, intersection.y); const a = new Vector2(intersection.x, intersection.y);
const b = new THREE.Vector2(intersectionPoints[index].x, intersectionPoints[index].y); const b = new Vector2(intersectionPoints[index].x, intersectionPoints[index].y);
// can't calculate normal between points if distance is smaller as 0.0001 // can't calculate normal between points if distance is smaller as 0.0001
if ((faceNormal.x === 0 && faceNormal.y === 0) || a.distanceTo(b) < 0.0001) { if ((faceNormal.x === 0 && faceNormal.y === 0) || a.distanceTo(b) < 0.0001) {
@ -64,7 +64,7 @@ export default function intersectionsToShapes(layerIntersectionIndexes, layerInt
index = -1; index = -1;
} else { } else {
// make sure the path goes the right direction // make sure the path goes the right direction
// THREE.Vector2.normal is not yet implimented // Vector2.normal is not yet implimented
// const normal = a.sub(b).normal().normalize(); // const normal = a.sub(b).normal().normalize();
const normal = a.sub(b); const normal = a.sub(b);
normal.set(-normal.y, normal.x).normalize(); normal.set(-normal.y, normal.x).normalize();
@ -111,7 +111,7 @@ export default function intersectionsToShapes(layerIntersectionIndexes, layerInt
if (openShape) { if (openShape) {
lineShapesOpen.push(shape); lineShapesOpen.push(shape);
} else { } else {
lineShapesClosed.push(shape); lineShapesClosed.push(shape);
} }
} else { } else {
fillShapes.push(shape); fillShapes.push(shape);

View File

@ -1,8 +1,8 @@
import * as THREE from 'three'; import { Vector2 } from 'three/src/math/Vector2.js';
import Shape from 'clipper-js'; import Shape from 'clipper-js';
export default function optimizePaths(slices, settings) { export default function optimizePaths(slices, settings) {
const start = new THREE.Vector2(0, 0); const start = new Vector2(0, 0);
for (let layer = 0; layer < slices.length; layer ++) { for (let layer = 0; layer < slices.length; layer ++) {
const slice = slices[layer]; const slice = slices[layer];
@ -102,7 +102,7 @@ function optimizeShape(shape, start) {
if (shape.closed) { if (shape.closed) {
for (let j = 0; j < path.length; j += 1) { for (let j = 0; j < path.length; j += 1) {
const point = new THREE.Vector2().copy(path[j]); const point = new Vector2().copy(path[j]);
const length = point.sub(start).length(); const length = point.sub(start).length();
if (minLength === false || length < minLength) { if (minLength === false || length < minLength) {
minPath = path; minPath = path;
@ -112,7 +112,7 @@ function optimizeShape(shape, start) {
} }
} }
} else { } else {
const startPoint = new THREE.Vector2().copy(path[0]); const startPoint = new Vector2().copy(path[0]);
const lengthToStart = startPoint.sub(start).length(); const lengthToStart = startPoint.sub(start).length();
if (minLength === false || lengthToStart < minLength) { if (minLength === false || lengthToStart < minLength) {
minPath = path; minPath = path;
@ -121,7 +121,7 @@ function optimizeShape(shape, start) {
pathIndex = i; pathIndex = i;
} }
const endPoint = new THREE.Vector2().copy(path[path.length - 1]); const endPoint = new Vector2().copy(path[path.length - 1]);
const lengthToEnd = endPoint.sub(start).length(); const lengthToEnd = endPoint.sub(start).length();
if (lengthToEnd < minLength) { if (lengthToEnd < minLength) {
minPath = path; minPath = path;

View File

@ -1,4 +1,9 @@
import * as THREE from 'three'; import { Color } from 'three/src/math/Color.js';
import { BufferGeometry } from 'three/src/core/BufferGeometry.js';
import { BufferAttribute } from 'three/src/core/BufferAttribute.js';
import { LineBasicMaterial } from 'three/src/materials/LineBasicMaterial.js';
import { VertexColors } from 'three/src/constants.js';
import { LineSegments } from 'three/src/objects/LineSegments.js';
import calculateLayersIntersections from './calculateLayersIntersections.js'; import calculateLayersIntersections from './calculateLayersIntersections.js';
import createLines from './createLines.js'; import createLines from './createLines.js';
import generateInfills from './generateInfills.js'; import generateInfills from './generateInfills.js';
@ -99,7 +104,7 @@ function gcodeToString(gcode) {
} }
const MAX_SPEED = 100 * 60; const MAX_SPEED = 100 * 60;
const COLOR = new THREE.Color(); const COLOR = new Color();
function createGcodeGeometry(gcode) { function createGcodeGeometry(gcode) {
const positions = []; const positions = [];
const colors = []; const colors = [];
@ -121,13 +126,13 @@ function createGcodeGeometry(gcode) {
} }
} }
const geometry = new THREE.BufferGeometry(); const geometry = new BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), 3)); geometry.addAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3)); geometry.addAttribute('color', new BufferAttribute(new Float32Array(colors), 3));
const material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors }); const material = new LineBasicMaterial({ vertexColors: VertexColors });
const linePreview = new THREE.LineSegments(geometry, material); const linePreview = new LineSegments(geometry, material);
return linePreview; return linePreview;
} }

View File

@ -1,4 +1,9 @@
import * as THREE from 'three'; import { Geometry } from 'three/src/core/Geometry.js';
import { BufferGeometry } from 'three/src/core/BufferGeometry.js';
import { VertexColors } from 'three/src/constants.js';
import { BufferAttribute } from 'three/src/core/BufferAttribute.js';
import { LineBasicMaterial } from 'three/src/materials/LineBasicMaterial.js';
import { LineSegments } from 'three/src/objects/LineSegments.js';
import slice from './sliceActions/slice.js'; import slice from './sliceActions/slice.js';
import SlicerWorker from './slicer.worker.js'; import SlicerWorker from './slicer.worker.js';
@ -16,7 +21,7 @@ export function sliceGeometry(settings, geometry, matrix, sync = false, construc
if (!geometry) { if (!geometry) {
throw new Error('Missing required geometry argument'); throw new Error('Missing required geometry argument');
} else if (geometry.isBufferGeometry) { } else if (geometry.isBufferGeometry) {
geometry = new THREE.Geometry().fromBufferGeometry(geometry); geometry = new Geometry().fromBufferGeometry(geometry);
} else if (geometry.isGeometry) { } else if (geometry.isGeometry) {
geometry = geometry.clone(); geometry = geometry.clone();
} else { } else {
@ -60,14 +65,14 @@ function sliceAsync(settings, geometry, constructLinePreview, onProgress) {
slicerWorker.terminate(); slicerWorker.terminate();
if (data.gcode.linePreview) { if (data.gcode.linePreview) {
const geometry = new THREE.BufferGeometry(); const geometry = new BufferGeometry();
const { position, color } = data.gcode.linePreview; const { position, color } = data.gcode.linePreview;
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(position), 3)); geometry.addAttribute('position', new BufferAttribute(new Float32Array(position), 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(color), 3)); geometry.addAttribute('color', new BufferAttribute(new Float32Array(color), 3));
const material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors }); const material = new LineBasicMaterial({ vertexColors: VertexColors });
const linePreview = new THREE.LineSegments(geometry, material); const linePreview = new LineSegments(geometry, material);
data.gcode.linePreview = linePreview; data.gcode.linePreview = linePreview;
} }

View File

@ -1,8 +1,8 @@
import 'core-js'; // polyfills import 'core-js'; // polyfills
import slice from './sliceActions/slice.js'; import slice from './sliceActions/slice.js';
import * as THREE from 'three'; import { JSONLoader } from 'three/src/loaders/JSONLoader.js';
const loader = new THREE.JSONLoader(); const loader = new JSONLoader();
const onProgress = progress => { const onProgress = progress => {
self.postMessage({ self.postMessage({

View File

@ -46,6 +46,9 @@ module.exports = {
}, { }, {
test: /\.worker\.js$/, test: /\.worker\.js$/,
use: ['worker-loader', babelLoader] use: ['worker-loader', babelLoader]
}, {
test: /\.glsl$/,
use: ['raw-loader']
} }
] ]
}, },