before refactor sketcher

master
howard 2021-03-31 15:03:35 -07:00
parent f3de6bff7d
commit 505cd64cb5
11 changed files with 132 additions and 81 deletions

View File

@ -1,7 +1,8 @@
import * as THREE from 'three/src/Three'; // import * as THREE from 'three/src/Three';
import * as THREE from '../node_modules/three/src/Three';
// import { OrbitControls } from './utils/OrbitControls' // import { OrbitControls } from './utils/OrbitControls'
import { TrackballControls } from './utils/trackball' import { TrackballControls } from './utils/trackball'
import { Sketcher } from './sketcher/Sketcher' import { Sketcher } from './sketcher/Sketcher'
@ -23,13 +24,13 @@ const eq = (a1, a2) => {
return true return true
} }
window.nid = 0
export class Scene extends THREE.Scene { export class Scene extends THREE.Scene {
constructor(store) { constructor(store) {
super() super()
this.name = 'Scene'
this.store = store;
this.store = store;
this.canvas = document.querySelector('#c'); this.canvas = document.querySelector('#c');
this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas }); this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas });
@ -57,7 +58,7 @@ export class Scene extends THREE.Scene {
const pxy = new THREE.Mesh( const pxy = new THREE.Mesh(
new THREE.PlaneGeometry(5, 5), new THREE.PlaneGeometry(5, 5),
new THREE.MeshBasicMaterial({ new THREE.MeshBasicMaterial({
color: color.Plane, color: color.d,
opacity: 0.2, opacity: 0.2,
side: THREE.DoubleSide, side: THREE.DoubleSide,
transparent: true, transparent: true,
@ -65,7 +66,8 @@ export class Scene extends THREE.Scene {
toneMapped: false toneMapped: false
}) })
); );
pxy.name = "Plane"
pxy.name = 'd' + nid++
helpersGroup.add(pxy); helpersGroup.add(pxy);
const pyz = pxy.clone().rotateY(Math.PI / 2); const pyz = pxy.clone().rotateY(Math.PI / 2);
@ -94,7 +96,6 @@ export class Scene extends THREE.Scene {
this.render = render.bind(this); this.render = render.bind(this);
this.resizeCanvas = resizeCanvas.bind(this);
this.addSketch = addSketch.bind(this); this.addSketch = addSketch.bind(this);
this.extrude = extrude.bind(this); this.extrude = extrude.bind(this);
this.onHover = onHover.bind(this); this.onHover = onHover.bind(this);
@ -116,6 +117,46 @@ export class Scene extends THREE.Scene {
this.render(); this.render();
} }
resizeCanvas(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
saveState() {
localStorage.setItem(
'sv', JSON.stringify([id, this.store.getState(), this.children.slice(4)])
)
}
loadState() {
const [curId, state, treeItems] = JSON.parse(
localStorage.getItem('sv')
)
window.id = curId
this.store.dispatch({ type: 'restore-state', state })
for (let i = 0; i < treeItems.length; i++) {
const obj = loader.parse(treeItems[i])
console.log(obj)
sc.add(obj)
// obj.visible = false
}
}
} }
function render() { function render() {
@ -130,16 +171,6 @@ function render() {
this.stats.end(); this.stats.end();
} }
function resizeCanvas(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
async function addSketch() { async function addSketch() {
@ -154,9 +185,9 @@ async function addSketch() {
window.addEventListener('keydown', (e) => rej(e), { once: true }) window.addEventListener('keydown', (e) => rej(e), { once: true })
}) })
if (pt.type == 'Points') { if (pt.name[0] == 'p') {
references.push(pt) references.push(pt)
} else if (pt.name == 'Plane') { } else if (pt.name[0] == 'd') {
references = [pt] references = [pt]
break; break;
} }
@ -170,9 +201,9 @@ async function addSketch() {
} }
} }
const sketcher = new Sketcher(this.camera, this.canvas, this.store) const sketcher = new Sketcher(this.camera, this.canvas, this.store, nid++)
if (references.length == 1 && references[0].name == 'Plane') { if (references.length == 1 && references[0].name[0] == 'd') {
this.add(sketcher) this.add(sketcher)
sketcher.matrix = references[0].matrix sketcher.matrix = references[0].matrix
sketcher.plane.applyMatrix4(sketcher.matrix) sketcher.plane.applyMatrix4(sketcher.matrix)
@ -204,23 +235,16 @@ window.loader = new THREE.ObjectLoader();
// const mm = []
// for (let i = 1; i <= 3; i++) {
// const obj = loader.parse(JSON.parse(localStorage.getItem(i.toString())))
// mm.push(obj)
// sc.add(mm[mm.length - 1])
// obj.visible = false
// }
// //Create a bsp tree from each of the meshes // //Create a bsp tree from each of the meshes
// let bspA = CSG.fromMesh( mm[0] ) // let bspA = CSG.fromMesh( mm[0] )
// let bspB = CSG.fromMesh( mm[2] ) // let bspB = CSG.fromMesh( mm[2] )
// // Subtract one bsp from the other via .subtract... other supported modes are .union and .intersect // // Subtract one bsp from the other via .subtract... other supported modes are .union and .intersect
// let bspResult = bspA.subtract(bspB) // let bspResult = bspA.subtract(bspB)
// //Get the resulting mesh from the result bsp, and assign meshA.material to the resulting mesh // //Get the resulting mesh from the result bsp, and assign meshA.material to the resulting mesh

View File

@ -16,7 +16,7 @@ export const Root = ({ store }) => (
function treeId2Obj(id) { function treeId2Obj(id) {
// return sc.scene.getObjectById(parseInt(id.slice(1))) // return sc.scene.getObjectById(parseInt(id.slice(1)))
return sc.getObjectById(parseInt(id.slice(1))) return sc.getObjectByName(id)
} }
const App = () => { const App = () => {
@ -54,9 +54,10 @@ const App = () => {
</div> </div>
<div className='feature-tree'> <div className='feature-tree'>
{treeEntries.allIds.map((entId, idx) => ( {treeEntries.map((entId, idx) => (
<div key={idx} <div key={idx}
onClick={() => { onClick={() => {
console.log('here',treeId2Obj(entId))
if (activeSketch) { if (activeSketch) {
treeId2Obj(activeSketch).deactivate() treeId2Obj(activeSketch).deactivate()
} }

View File

@ -27,8 +27,11 @@ export function extrude(sketch) {
offSetPts.push(arr[arr.length - 3], arr[arr.length - 2]) offSetPts.push(arr[arr.length - 3], arr[arr.length - 2])
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) {
// let d = linkedObj[1][i] let d = children[
let d = children[objIdx.get(linkedObj[1][i])] objIdx.get(
linkedObj[1][i]
)
]
if (d == -1 || d == node) continue; if (d == -1 || d == node) continue;
if (d == children[1]) { if (d == children[1]) {
console.log('pair found') console.log('pair found')
@ -64,12 +67,13 @@ export function extrude(sketch) {
const extrudeSettings = { depth: 8, bevelEnabled: false }; const extrudeSettings = { depth: 8, bevelEnabled: false };
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings); const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
const phong = new THREE.MeshPhongMaterial({ const phong = new THREE.MeshPhongMaterial({
color: color.Extrude, color: color.m,
emissive: color.emissive, emissive: color.emissive,
flatShading: true flatShading: true
}); });
const mesh = new THREE.Mesh(geometry, phong) const mesh = new THREE.Mesh(geometry, phong)
mesh.name = "Extrude" // mesh.name = "Extrude"
mesh.name = 'm' + nid++
for (let i = 0; i < offSetPts.length; i += 2) { for (let i = 0; i < offSetPts.length; i += 2) {
if ( if (

View File

@ -10,39 +10,34 @@ import logger from 'redux-logger'
let _entId = 0 let _entId = 0
function reducer(state = {}, action) { function reducer(state = {}, action) {
let id;
switch (action.type) { switch (action.type) {
case 'toggle': case 'toggle':
return { ...state, toggle: action.payload } return { ...state, toggle: action.payload }
case 'rx-sketch': case 'rx-sketch':
id = 's' + action.obj.id
return { return {
...state, treeEntries: { ...state, treeEntries: [...state.treeEntries, action.obj.name]
byId: { ...state.treeEntries.byId, [id]: action.obj }, ,
allIds: [...state.treeEntries.allIds, id]
},
} }
case 'set-active-sketch': case 'set-active-sketch':
return { return {
...state, activeSketch:'s'+action.sketch.id ...state, activeSketch: action.sketch.name
} }
case 'exit-sketch': case 'exit-sketch':
return { return {
...state, activeSketch:'' ...state, activeSketch: ''
} }
case 'rx-extrusion': case 'rx-extrusion':
id = 'e' + action.mesh.id
return { return {
...state, ...state,
treeEntries: { treeEntries: [...state.treeEntries, action.mesh.name]
byId: { ...state.treeEntries.byId, [id]: action.mesh }, ,
allIds: [...state.treeEntries.allIds, id]
},
mesh2sketch: { mesh2sketch: {
...state.mesh2sketch, ...state.mesh2sketch,
['s' + action.sketch.id]: id [action.sketch.name]: action.mesh.name
} }
} }
case 'restore-state':
return action.state
default: default:
return state return state
} }
@ -52,15 +47,10 @@ function reducer(state = {}, action) {
const preloadedState = { const preloadedState = {
treeEntries: { treeEntries: [
byId: { // 's1','m1'
// "s1": obj, ]
// "s1": obj2, ,
},
allIds: [
// 's1','m1'
]
},
} }

View File

@ -7,6 +7,7 @@ import { onHover, onDrag, onPick, onRelease } from '../utils/mouseEvents'
import { addDimension, setCoincident } from './constraintEvents' import { addDimension, setCoincident } from './constraintEvents'
import { get3PtArc } from './sketchArc' import { get3PtArc } from './sketchArc'
import { _vec2, _vec3, raycaster } from '../utils/static' import { _vec2, _vec3, raycaster } from '../utils/static'
import { replacer, reviver } from '../utils/mapJSONReplacer'
@ -14,9 +15,9 @@ import { _vec2, _vec3, raycaster } from '../utils/static'
class Sketcher extends THREE.Group { class Sketcher extends THREE.Group {
constructor(camera, canvas, store) { constructor(camera, canvas, store, nid) {
super() super()
this.name = "Sketch" this.name = "s" + nid
this.matrixAutoUpdate = false; this.matrixAutoUpdate = false;
this.camera = camera; this.camera = camera;
this.canvas = canvas; this.canvas = canvas;
@ -27,7 +28,7 @@ class Sketcher extends THREE.Group {
const axesHelper = new THREE.AxesHelper(2); const axesHelper = new THREE.AxesHelper(2);
this.sub.add(axesHelper); this.sub.add(axesHelper);
this.plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0); this.plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
@ -239,7 +240,7 @@ class Sketcher extends THREE.Group {
updatePointsBuffer(startingIdx = 0) { updatePointsBuffer(startingIdx = 0) {
for (let i = startingIdx; i < this.children.length; i++) { for (let i = startingIdx; i < this.children.length; i++) {
const obj = this.children[i] const obj = this.children[i]
this.objIdx.set(obj.id, i) this.objIdx.set(obj.name, i)
if (obj.type == "Points") { if (obj.type == "Points") {
this.ptsBuf.set(obj.geometry.attributes.position.array, 3 * i) this.ptsBuf.set(obj.geometry.attributes.position.array, 3 * i)
} }
@ -327,6 +328,15 @@ class Sketcher extends THREE.Group {
this.dispatchEvent({ type: 'change' }) this.dispatchEvent({ type: 'change' })
} }
toJSON() {
this.userData = {
constraints: JSON.stringify(this.constraints, replacer),
linkedObjs: JSON.stringify(this.linkedObjs, replacer),
objIdx: JSON.stringify(this.objIdx, replacer)
}
return super.toJSON()
}
} }
const _m1 = new THREE.Matrix4() const _m1 = new THREE.Matrix4()

View File

@ -32,7 +32,7 @@ export function setCoincident() {
this.constraints.set(++this.c_id, this.constraints.set(++this.c_id,
[ [
'coincident', -1, 'coincident', -1,
[toComb[i - 1].id, toComb[i].id, -1, -1] /////// [toComb[i - 1].name, toComb[i].name, -1, -1] ///////
] ]
) )
toComb[i].userData.constraints.push(this.c_id) toComb[i].userData.constraints.push(this.c_id)

View File

@ -16,7 +16,7 @@ export function drawOnClick1(e) {
this.updatePoint = this.children.length this.updatePoint = this.children.length
this.add(...this.toPush) this.add(...this.toPush)
this.linkedObjs.set(this.l_id, [this.mode, this.toPush.map(e=>e.id)]) this.linkedObjs.set(this.l_id, [this.mode, this.toPush.map(e=>e.name)])
for (let obj of this.toPush) { for (let obj of this.toPush) {
obj.userData.l_id = this.l_id obj.userData.l_id = this.l_id
} }

View File

@ -26,12 +26,11 @@ export function sketchLine(mouseLoc) {
this.constraints.set(++this.c_id, this.constraints.set(++this.c_id,
[ [
'coincident', -1, 'coincident', -1,
[this.children[this.children.length - 2].id, p1.id, -1, -1] [this.children[this.children.length - 2].name, p1.name, -1, -1]
] ]
) )
p1.userData.constraints.push(this.c_id) p1.userData.constraints.push(this.c_id)
console.log(this.children[this.children.length - 2].userData.constraints,'here')
this.children[this.children.length - 2].userData.constraints.push(this.c_id) this.children[this.children.length - 2].userData.constraints.push(this.c_id)
} }

View File

@ -0,0 +1,23 @@
// https://stackoverflow.com/a/56150320
function replacer(key, value) {
if (value instanceof Map) {
return {
dataType: 'Map',
value: Array.from(value.entries()), // or with spread: value: [...value]
};
} else {
return value;
}
}
function reviver(key, value) {
if (typeof value === 'object' && value !== null) {
if (value.dataType === 'Map') {
return new Map(value.value);
}
}
return value;
}
export {replacer, reviver}

View File

@ -13,10 +13,10 @@ export function onHover(e) {
); );
let hoverPts; let hoverPts;
if (this.name == 'Scene') { if (this.name[0]=='s') {
hoverPts = raycaster.intersectObjects(this.children, true)
} else {
hoverPts = raycaster.intersectObjects(this.children) hoverPts = raycaster.intersectObjects(this.children)
} else {
hoverPts = raycaster.intersectObjects(this.children, true)
} }
let idx = [] let idx = []
@ -40,7 +40,7 @@ export function onHover(e) {
const obj = this.hovered[this.hovered.length - 1] const obj = this.hovered[this.hovered.length - 1]
if (obj && !this.selected.includes(obj)) { if (obj && !this.selected.includes(obj)) {
// obj.material.color.set(0x555555) // obj.material.color.set(0x555555)
obj.material.color.set(color[obj.name]) obj.material.color.set(color[obj.name[0]])
} }
this.hovered = [] this.hovered = []
@ -58,7 +58,7 @@ export function onHover(e) {
const obj = this.hovered[this.hovered.length - 1] const obj = this.hovered[this.hovered.length - 1]
if (obj && !this.selected.includes(obj)) { if (obj && !this.selected.includes(obj)) {
obj.material.color.set(color[obj.name]) obj.material.color.set(color[obj.name[0]])
} }
this.hovered = [] this.hovered = []
@ -83,7 +83,7 @@ export function onPick(e) {
} else { } else {
for (let obj of this.selected) { for (let obj of this.selected) {
// obj.material.color.set(0x555555) // obj.material.color.set(0x555555)
obj.material.color.set(color[obj.name]) obj.material.color.set(color[obj.name[0]])
} }
this.dispatchEvent({ type: 'change' }) this.dispatchEvent({ type: 'change' })
this.selected = [] this.selected = []
@ -97,7 +97,7 @@ export function onDrag(e) {
const obj = this.hovered[x] const obj = this.hovered[x]
this.ptsBuf.set( this.ptsBuf.set(
mouseLoc, mouseLoc,
this.objIdx.get(obj.id) * 3 this.objIdx.get(obj.name) * 3
) )
} }

View File

@ -15,20 +15,20 @@ const color = {
hover: 0x00ff00, hover: 0x00ff00,
lighting: 0xFFFFFF, lighting: 0xFFFFFF,
emissive: 0x072534, emissive: 0x072534,
Plane: 0xf5bc42, d: 0xf5bc42, //datums: planes
Line: 0x555555, p: 0x555555, //points
Points: 0x555555, l: 0x555555, //lines
Extrude: 0x156289, m: 0x156289, //mesh: extrude
} }
const lineMaterial = new THREE.LineBasicMaterial({ const lineMaterial = new THREE.LineBasicMaterial({
linewidth: 2, linewidth: 2,
color: color.Line, color: color.l,
}) })
const pointMaterial = new THREE.PointsMaterial({ const pointMaterial = new THREE.PointsMaterial({
color: color.Points, color: color.p,
size: 4, size: 4,
}) })
@ -40,7 +40,7 @@ const ptObj = (n) => {
), ),
pointMaterial.clone() pointMaterial.clone()
); );
ret.name = 'Points' ret.name = 'p' + nid++
return ret return ret
} }
@ -51,7 +51,7 @@ const lineObj = (n = 1) => {
), ),
lineMaterial.clone() lineMaterial.clone()
); );
ret.name = 'Line' ret.name = 'l' + nid++
return ret return ret
} }