format project

This commit is contained in:
Kurt Hutten
2021-08-01 09:55:07 +10:00
parent 625db5e26b
commit d8998a73b3
9 changed files with 215 additions and 180 deletions

View File

@@ -244,7 +244,6 @@ const makeScriptWorker = ({callback, convertToSolids})=>{
let workerBaseURI, onInit let workerBaseURI, onInit
function runMain(params={}){ function runMain(params={}){
console.log('runMain');
let time = Date.now() let time = Date.now()
let solids let solids
try{ try{

View File

@@ -59,7 +59,7 @@ export const makeStlDownloadHandler =
(quality === 'high' || ideType === 'openscad') (quality === 'high' || ideType === 'openscad')
) { ) {
saveFile(makeStlBlobFromGeo(geometry)) saveFile(makeStlBlobFromGeo(geometry))
} else if(ideType == 'jscad') { } else if (ideType == 'jscad') {
saveFile(makeStlBlobFromMesh(geometry)) saveFile(makeStlBlobFromMesh(geometry))
} else { } else {
thunkDispatch((dispatch, getState) => { thunkDispatch((dispatch, getState) => {

View File

@@ -14,7 +14,7 @@ const IdeEditor = ({ Loading }) => {
const [theme, setTheme] = useState('vs-dark') const [theme, setTheme] = useState('vs-dark')
const saveCode = useSaveCode() const saveCode = useSaveCode()
const ideTypeToLanguageMap: {[key in CadPackageType]: string} = { const ideTypeToLanguageMap: { [key in CadPackageType]: string } = {
cadquery: 'python', cadquery: 'python',
openscad: 'cpp', openscad: 'cpp',
jscad: 'javascript', jscad: 'javascript',

View File

@@ -25,18 +25,18 @@ function Asset({ geometry: incomingGeo }) {
}, [incomingGeo]) }, [incomingGeo])
if (!incomingGeo) return null if (!incomingGeo) return null
let groupData = incomingGeo.children ? incomingGeo : null const groupData = incomingGeo.children ? incomingGeo : null
if(lastGroup && lastGroup != groupData){ if (lastGroup && lastGroup != groupData) {
state.scene.remove(lastGroup) state.scene.remove(lastGroup)
lastGroup.children.forEach(c=>c?.geometry?.dispose()) lastGroup.children.forEach((c) => c?.geometry?.dispose())
// returning <primitive object={groupData} /> does not add the new group to the scene // returning <primitive object={groupData} /> does not add the new group to the scene
// there is probably some useRef magic that would make this work, but I don't have time to reseach it // there is probably some useRef magic that would make this work, but I don't have time to reseach it
/// FIXME - do this properly with useRef or other react magic /// FIXME - do this properly with useRef or other react magic
if(groupData) state.scene.add(groupData) if (groupData) state.scene.add(groupData)
} }
lastGroup = groupData lastGroup = groupData
if(groupData) return <primitive object={groupData} /> if (groupData) return <primitive object={groupData} />
if (incomingGeo.children) return <primitive object={incomingGeo} /> if (incomingGeo.children) return <primitive object={incomingGeo} />

View File

@@ -3,7 +3,6 @@ import Svg from 'src/components/Svg/Svg'
import { Popover } from '@headlessui/react' import { Popover } from '@headlessui/react'
import type { CadPackage } from 'src/helpers/hooks/useIdeState' import type { CadPackage } from 'src/helpers/hooks/useIdeState'
const menuOptions: { const menuOptions: {
name: string name: string
sub: string sub: string

View File

@@ -1,17 +1,18 @@
const setPoints = (points, p, i)=>{ const setPoints = (points, p, i) => {
points[i++] = p[0] points[i++] = p[0]
points[i++] = p[1] points[i++] = p[1]
points[i++] = p[2] || 0 points[i++] = p[2] || 0
} }
function CSG2Vertices(csg){ function CSG2Vertices(csg) {
let idx = 0 let idx = 0
let vLen = 0, iLen = 0 let vLen = 0,
for (let poly of csg.polygons){ iLen = 0
for (let poly of csg.polygons) {
let len = poly.vertices.length let len = poly.vertices.length
vLen += len *3 vLen += len * 3
iLen += 3 * (len-2) iLen += 3 * (len - 2)
} }
const vertices = new Float32Array(vLen) const vertices = new Float32Array(vLen)
const indices = vLen > 65535 ? new Uint32Array(iLen) : new Uint16Array(iLen) const indices = vLen > 65535 ? new Uint32Array(iLen) : new Uint16Array(iLen)
@@ -20,87 +21,89 @@ function CSG2Vertices(csg){
let indOffset = 0 let indOffset = 0
let posOffset = 0 let posOffset = 0
let first = 0 let first = 0
for (let poly of csg.polygons){ for (let poly of csg.polygons) {
let arr = poly.vertices let arr = poly.vertices
let len = arr.length let len = arr.length
first = posOffset first = posOffset
vertices.set(arr[0], vertOffset) vertices.set(arr[0], vertOffset)
vertOffset +=3 vertOffset += 3
vertices.set(arr[1], vertOffset) vertices.set(arr[1], vertOffset)
vertOffset +=3 vertOffset += 3
posOffset +=2 posOffset += 2
for(let i=2; i<len; i++){ for (let i = 2; i < len; i++) {
vertices.set(arr[i], vertOffset) vertices.set(arr[i], vertOffset)
indices[indOffset++] = first indices[indOffset++] = first
indices[indOffset++] = first + i -1 indices[indOffset++] = first + i - 1
indices[indOffset++] = first + i indices[indOffset++] = first + i
vertOffset += 3 vertOffset += 3
posOffset += 1 posOffset += 1
} }
} }
return {vertices, indices, type:'mesh'} return { vertices, indices, type: 'mesh' }
} }
function CSG2LineVertices(csg) {
function CSG2LineVertices(csg){
let vLen = csg.points.length * 3 let vLen = csg.points.length * 3
if(csg.isClosed) vLen += 3 if (csg.isClosed) vLen += 3
var vertices = new Float32Array(vLen) var vertices = new Float32Array(vLen)
csg.points.forEach((p, idx) => setPoints(vertices, p, idx * 3))
csg.points.forEach((p,idx)=>setPoints(vertices, p, idx * 3 )) if (csg.isClosed) {
setPoints(vertices, csg.points[0], vertices.length - 3)
if(csg.isClosed){
setPoints(vertices, csg.points[0], vertices.length - 3 )
} }
return {vertices, type:'line'} return { vertices, type: 'line' }
} }
function CSG2LineSegmentsVertices(csg){ function CSG2LineSegmentsVertices(csg) {
let vLen = csg.sides.length * 6 let vLen = csg.sides.length * 6
var vertices = new Float32Array(vLen) var vertices = new Float32Array(vLen)
csg.sides.forEach((side,idx)=>{ csg.sides.forEach((side, idx) => {
let i = idx * 6 let i = idx * 6
setPoints(vertices, side[0], i) setPoints(vertices, side[0], i)
setPoints(vertices, side[1], i+3) setPoints(vertices, side[1], i + 3)
}) })
return {vertices, type:'lines'} return { vertices, type: 'lines' }
} }
function CSGCached(func, data, cacheKey, transferable){ function CSGCached(func, data, cacheKey, transferable) {
cacheKey = cacheKey || data cacheKey = cacheKey || data
let geo = CSGToBuffers.cache.get(cacheKey) let geo = CSGToBuffers.cache.get(cacheKey)
if(geo) return geo if (geo) return geo
geo = func(data) geo = func(data)
// fill transferable array for postMessage optimization // fill transferable array for postMessage optimization
if(transferable){ if (transferable) {
const {vertices, indices} = geo const { vertices, indices } = geo
transferable.push(vertices) transferable.push(vertices)
if(indices) transferable.push(indices) if (indices) transferable.push(indices)
} }
CSGToBuffers.cache.set(cacheKey, geo) CSGToBuffers.cache.set(cacheKey, geo)
return geo return geo
} }
function CSGToBuffers(csg, transferable){ function CSGToBuffers(csg, transferable) {
let obj let obj
if(csg.polygons) obj = CSGCached(CSG2Vertices,csg,csg.polygons, transferable) if (csg.polygons)
if(csg.sides && !csg.points) obj = CSGCached(CSG2LineSegmentsVertices,csg,csg.sides, transferable) obj = CSGCached(CSG2Vertices, csg, csg.polygons, transferable)
if(csg.points) obj = CSGCached(CSG2LineVertices,csg,csg.points, transferable) if (csg.sides && !csg.points)
obj = CSGCached(CSG2LineSegmentsVertices, csg, csg.sides, transferable)
if (csg.points)
obj = CSGCached(CSG2LineVertices, csg, csg.points, transferable)
return obj return obj
} }
CSGToBuffers.clearCache = ()=>{CSGToBuffers.cache = new WeakMap()} CSGToBuffers.clearCache = () => {
CSGToBuffers.cache = new WeakMap()
}
CSGToBuffers.clearCache() CSGToBuffers.clearCache()
export {CSGToBuffers} export { CSGToBuffers }

View File

@@ -5,7 +5,7 @@ import openscad from './openScadController'
import cadquery from './cadQueryController' import cadquery from './cadQueryController'
import jscad from './jsCadController' import jscad from './jsCadController'
export const cadPackages: {[key in CadPackage]: DefaultKernelExport} = { export const cadPackages: { [key in CadPackage]: DefaultKernelExport } = {
openscad, openscad,
cadquery, cadquery,
jscad, jscad,

View File

@@ -1,45 +1,72 @@
import { RenderArgs, DefaultKernelExport, createUnhealthyResponse, createHealthyResponse } from './common' import {
import { MeshPhongMaterial, LineBasicMaterial, BufferGeometry , BufferAttribute, Line, LineSegments, Color, Mesh, Group} from 'three/build/three.module' RenderArgs,
DefaultKernelExport,
createUnhealthyResponse,
createHealthyResponse,
} from './common'
import {
MeshPhongMaterial,
LineBasicMaterial,
BufferGeometry,
BufferAttribute,
Line,
LineSegments,
Color,
Mesh,
Group,
} from 'three/build/three.module'
const materials = { const materials = {
mesh: { mesh: {
def: new MeshPhongMaterial( { color: 0x0084d1, flatShading: true } ), def: new MeshPhongMaterial({ color: 0x0084d1, flatShading: true }),
material: (params)=>new MeshPhongMaterial(params), material: (params) => new MeshPhongMaterial(params),
}, },
line: { line: {
def: new LineBasicMaterial( { color: 0x0000ff } ), def: new LineBasicMaterial({ color: 0x0000ff }),
material: ({color,opacity,transparent})=>new LineBasicMaterial({color,opacity,transparent}), material: ({ color, opacity, transparent }) =>
new LineBasicMaterial({ color, opacity, transparent }),
}, },
lines:null lines: null,
} }
materials.lines = materials.line materials.lines = materials.line
function CSG2Object3D(obj){ function CSG2Object3D(obj) {
const {vertices, indices, color, transforms} = obj const { vertices, indices, color, transforms } = obj
let materialDef = materials[obj.type] const materialDef = materials[obj.type]
if(!materialDef){ if (!materialDef) {
console.error('Can not hangle object type: '+obj.type, obj) console.error('Can not hangle object type: ' + obj.type, obj)
return null return null
} }
let material = materialDef.def let material = materialDef.def
if(color){ if (color) {
let c = color const c = color
material = new materialDef.material({ color: new Color(c[0],c[1],c[2]), flatShading: true, opacity: c[3] === void 0 ? 1:c[3], transparent: c[3] != 1 && c[3] !== void 0}) material = new materialDef.material({
color: new Color(c[0], c[1], c[2]),
flatShading: true,
opacity: c[3] === void 0 ? 1 : c[3],
transparent: c[3] != 1 && c[3] !== void 0,
})
} }
var geo = new BufferGeometry() const geo = new BufferGeometry()
geo.setAttribute('position', new BufferAttribute(vertices,3)) geo.setAttribute('position', new BufferAttribute(vertices, 3))
var mesh; let mesh
switch(obj.type){ switch (obj.type) {
case 'mesh': geo.setIndex(new BufferAttribute(indices,1)); mesh = new THREE.Mesh(geo, material); break; case 'mesh':
case 'line': mesh = new Line(geo, material); break; geo.setIndex(new BufferAttribute(indices, 1))
case 'lines': mesh = new LineSegments(geo, material); break; mesh = new THREE.Mesh(geo, material)
break
case 'line':
mesh = new Line(geo, material)
break
case 'lines':
mesh = new LineSegments(geo, material)
break
} }
if(transforms) mesh.applyMatrix4({elements:transforms}) if (transforms) mesh.applyMatrix4({ elements: transforms })
return mesh return mesh
} }
@@ -48,8 +75,8 @@ const scriptUrl = '/demo-worker.js'
let resolveReference = null let resolveReference = null
let response = null let response = null
const callResolve = ()=>{ const callResolve = () => {
if(resolveReference) resolveReference() if (resolveReference) resolveReference()
resolveReference resolveReference
} }
@@ -57,10 +84,9 @@ export const render: DefaultKernelExport['render'] = async ({
code, code,
settings, settings,
}: RenderArgs) => { }: RenderArgs) => {
if (!scriptWorker) {
if(!scriptWorker){
const baseURI = document.baseURI.toString() const baseURI = document.baseURI.toString()
const script =`let baseURI = '${baseURI}' const script = `let baseURI = '${baseURI}'
importScripts(new URL('${scriptUrl}',baseURI)) importScripts(new URL('${scriptUrl}',baseURI))
let worker = jscadWorker({ let worker = jscadWorker({
baseURI: baseURI, baseURI: baseURI,
@@ -70,18 +96,21 @@ let worker = jscadWorker({
}) })
self.addEventListener('message', (e)=>worker.postMessage(e.data)) self.addEventListener('message', (e)=>worker.postMessage(e.data))
` `
let blob = new Blob([script],{type: 'text/javascript'}) const blob = new Blob([script], { type: 'text/javascript' })
scriptWorker = new Worker(window.URL.createObjectURL(blob)) scriptWorker = new Worker(window.URL.createObjectURL(blob))
scriptWorker.addEventListener('message',(e)=>{ scriptWorker.addEventListener('message', (e) => {
console.log('message from worker', e.data) console.log('message from worker', e.data)
let data = e.data const data = e.data
if(data.action == 'entities'){ if (data.action == 'entities') {
if(data.error){ if (data.error) {
response = createUnhealthyResponse( new Date(),data.error ) response = createUnhealthyResponse(new Date(), data.error)
}else{ } else {
let group = new Group() const group = new Group()
data.entities.map(CSG2Object3D).filter(o=>o).forEach(o=>group.add(o)) data.entities
response = createHealthyResponse( { .map(CSG2Object3D)
.filter((o) => o)
.forEach((o) => group.add(o))
response = createHealthyResponse({
type: 'geometry', type: 'geometry',
data: group, data: group,
consoleMessage: data.scriptStats, consoleMessage: data.scriptStats,
@@ -94,11 +123,16 @@ self.addEventListener('message', (e)=>worker.postMessage(e.data))
callResolve() callResolve()
response = null response = null
scriptWorker.postMessage({action:'init', baseURI, alias:[]}) scriptWorker.postMessage({ action: 'init', baseURI, alias: [] })
} }
scriptWorker.postMessage({action:'runScript', worker:'script', script:code, url:'jscad_script' }) scriptWorker.postMessage({
action: 'runScript',
worker: 'script',
script: code,
url: 'jscad_script',
})
let waitResult = new Promise(resolve=>{ const waitResult = new Promise((resolve) => {
resolveReference = resolve resolveReference = resolve
}) })

View File

@@ -11,7 +11,7 @@ function withThunk(dispatch, getState) {
export type CadPackage = 'openscad' | 'cadquery' | 'jscad' export type CadPackage = 'openscad' | 'cadquery' | 'jscad'
const initCodeMap: {[key in CadPackage]: string} = { const initCodeMap: { [key in CadPackage]: string } = {
openscad: `// involute donut openscad: `// involute donut
// ^ first comment is used for download title (i.e "involute-donut.stl") // ^ first comment is used for download title (i.e "involute-donut.stl")
@@ -42,7 +42,7 @@ result = (cq.Workplane().circle(diam).extrude(20.0)
show_object(result) show_object(result)
`, `,
jscad: ` jscad: `
const { booleans, colors, primitives } = require('@jscad/modeling') // modeling comes from the included MODELING library const { booleans, colors, primitives } = require('@jscad/modeling') // modeling comes from the included MODELING library
const { intersect, subtract } = booleans const { intersect, subtract } = booleans
@@ -68,7 +68,7 @@ const main = ({scale=1}) => {
return [transpCube, star2D, line2D, ...logo] return [transpCube, star2D, line2D, ...logo]
} }
module.exports = {main} module.exports = {main}
` `,
} }
const codeStorageKey = 'Last-editor-code' const codeStorageKey = 'Last-editor-code'