import { PathToNode, VariableDeclarator, parse, recast } from 'lang/wasm' import { Axis, Selection, Selections, updateSelections } from 'lib/selections' import { assign, createMachine } from 'xstate' import { SidebarType } from 'components/ModelingSidebar/ModelingPanes' import { isNodeSafeToReplacePath, getNodePathFromSourceRange, } from 'lang/queryAst' import { kclManager, sceneInfra, sceneEntitiesManager, engineCommandManager, editorManager, } from 'lib/singletons' import { horzVertInfo, applyConstraintHorzVert, } from 'components/Toolbar/HorzVert' import { applyConstraintHorzVertAlign, horzVertDistanceInfo, } from 'components/Toolbar/SetHorzVertDistance' import { angleBetweenInfo } from 'components/Toolbar/SetAngleBetween' import { angleLengthInfo } from 'components/Toolbar/setAngleLength' import { applyConstraintEqualLength, setEqualLengthInfo, } from 'components/Toolbar/EqualLength' import { addStartProfileAt, deleteFromSelection, extrudeSketch, } from 'lang/modifyAst' import { getNodeFromPath } from '../lang/queryAst' import { applyConstraintEqualAngle, equalAngleInfo, } from 'components/Toolbar/EqualAngle' import { applyRemoveConstrainingValues, removeConstrainingValuesInfo, } from 'components/Toolbar/RemoveConstrainingValues' import { intersectInfo } from 'components/Toolbar/Intersect' import { absDistanceInfo, applyConstraintAxisAlign, } from 'components/Toolbar/SetAbsDistance' import { Models } from '@kittycad/lib/dist/types/src' import { ModelingCommandSchema } from 'lib/commandBarConfigs/modelingCommandConfig' import { err, trap } from 'lib/trap' import { DefaultPlaneStr, getFaceDetails } from 'clientSideScene/sceneEntities' import { Vector3 } from 'three' import { quaternionFromUpNForward } from 'clientSideScene/helpers' import { uuidv4 } from 'lib/utils' import { Coords2d } from 'lang/std/sketch' import { deleteSegment } from 'clientSideScene/ClientSideSceneComp' import { executeAst } from 'lang/langHelpers' import toast from 'react-hot-toast' export const MODELING_PERSIST_KEY = 'MODELING_PERSIST_KEY' export type SetSelections = | { selectionType: 'singleCodeCursor' selection?: Selection } | { selectionType: 'otherSelection' selection: Axis } | { selectionType: 'completeSelection' selection: Selections updatedPathToNode?: PathToNode } | { selectionType: 'mirrorCodeMirrorSelections' selection: Selections } export type MouseState = | { type: 'idle' } | { type: 'isHovering' on: any } | { type: 'isDragging' on: any } | { type: 'timeoutEnd' pathToNodeString: string } export interface SketchDetails { sketchPathToNode: PathToNode zAxis: [number, number, number] yAxis: [number, number, number] origin: [number, number, number] } export interface SegmentOverlay { windowCoords: Coords2d angle: number group: any pathToNode: PathToNode visible: boolean } export interface SegmentOverlays { [pathToNodeString: string]: SegmentOverlay } export type SegmentOverlayPayload = | { type: 'set-one' pathToNodeString: string seg: SegmentOverlay } | { type: 'delete-one' pathToNodeString: string } | { type: 'clear' } | { type: 'set-many' overlays: SegmentOverlays } interface Store { mediaStream?: MediaStream buttonDownInStream: number | undefined didDragInStream: boolean streamDimensions: { streamWidth: number; streamHeight: number } openPanes: SidebarType[] } export type ModelingMachineEvent = | { type: 'Enter sketch' data?: { forceNewSketch?: boolean } } | { type: 'Sketch On Face' } | { type: 'Select default plane' data: { zAxis: [number, number, number] yAxis: [number, number, number] } & ( | { type: 'defaultPlane' plane: DefaultPlaneStr planeId: string } | { type: 'extrudeFace' position: [number, number, number] sketchPathToNode: PathToNode extrudePathToNode: PathToNode cap: 'start' | 'end' | 'none' faceId: string } ) } | { type: 'Set selection' data: SetSelections } | { type: 'Delete selection' } | { type: 'Sketch no face' } | { type: 'Toggle gui mode' } | { type: 'Cancel' } | { type: 'CancelSketch' } | { type: 'Add start point' } | { type: 'Make segment horizontal' } | { type: 'Make segment vertical' } | { type: 'Constrain horizontal distance' } | { type: 'Constrain ABS X' } | { type: 'Constrain ABS Y' } | { type: 'Constrain vertical distance' } | { type: 'Constrain angle' } | { type: 'Constrain perpendicular distance' } | { type: 'Constrain horizontally align' } | { type: 'Constrain vertically align' } | { type: 'Constrain snap to X' } | { type: 'Constrain snap to Y' } | { type: 'Constrain length' } | { type: 'Constrain equal length' } | { type: 'Constrain parallel' } | { type: 'Constrain remove constraints'; data?: PathToNode } | { type: 'Re-execute' } | { type: 'Export'; data: ModelingCommandSchema['Export'] } | { type: 'Extrude'; data?: ModelingCommandSchema['Extrude'] } | { type: 'Equip Line tool' } | { type: 'Equip tangential arc to' } | { type: 'Equip rectangle tool' } | { type: 'Add rectangle origin' data: [x: number, y: number] } | { type: 'done.invoke.animate-to-face' | 'done.invoke.animate-to-sketch' data: SketchDetails } | { type: 'Set mouse state'; data: MouseState } | { type: 'Set context'; data: Partial } | { type: 'Set Segment Overlays' data: SegmentOverlayPayload } | { type: 'Delete segment' data: PathToNode } | { type: 'code edit during sketch' } | { type: 'Convert to variable' data: { pathToNode: PathToNode variableName: string } } export type MoveDesc = { line: number; snippet: string } export const PERSIST_MODELING_CONTEXT = 'persistModelingContext' interface PersistedModelingContext { openPanes: Store['openPanes'] } type PersistedKeys = keyof PersistedModelingContext export const PersistedValues: PersistedKeys[] = ['openPanes'] const persistedContext: Partial = (typeof window !== 'undefined' && JSON.parse(localStorage.getItem(PERSIST_MODELING_CONTEXT) || '{}')) || { openPanes: ['code'], } export const modelingMachine = createMachine( { /** @xstate-layout N4IgpgJg5mDOIC5QFkD2EwBsCWA7KAxAMICGuAxlgNoAMAuoqAA6qzYAu2qujIAHogC0ANhoAWAHQB2GgE4ATLNEAOAKwBGAMyzNAGhABPRFNWaJmscOXyp61aplWAvk-1oMOfAQDKYdgAJYLDByTm5aBiQQFjYwniiBBEFlK2l1Gil5UxpreTEpfSMEeTyJYU0reW1hVRTxYRc3dCw8Ql8AgFtUAFcgwPYSdjAI3hiOLnjQROTlGgl5ZUWxDK0ZVVlCxE1VOfXxGlUq2R1NKUaQdxavdv9ybiG+dhGosbjeRJpNhBpzy882vz+XxQDpgXABADyADcwAAnTAkAywZ7MVjjbjvRCfQxY37Nf4SbAQTBgAgAUXBcMCAGs-OQABYo6Jot4JITyYRSCTqDk6NSadSyMTyL6abQSZQ6KX2CwaM6uC741qE4mkilDWE0umM9SRVGxCaYpJ5OZidSiOw5TQ5DJfZbyCQKKQ1HlWLTKc14jzKokk8mPWHdDBM16GtlJexcxQHYSyVRiWrqL7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Q2GKNzZIzAQe5VNuz3ZY8UTjJEtMz6yOmBK2gKQfka43Itgro6CFs-zGlgde5V5YL48jzszt+ZZExeyy86wJ+koSCPkzuG+Adld9TWzJFAFrTY29Mx+yN4sOh8TAUZOFgFgGLFdukrZXFjLpCPMzLYx7GmQ7LHKjFZcYobSoW0sagdzhCwlvFqOns+LML6wcLn8L8SLxMk6pg98NQblALWL2lJiJlQ92tR1EEkJJRmyH88t16N19o564gslDsnl3lvlYA6984Mk8iOiCwiw64bG8tlgb8xdZWYoWyQTN2w1nAjK+VYV-rtrcSZTy0eQ2CMF8LcliANQqKKQOwvL1s-D0ESb3VnEfAfVjK41cEmDSLpUuQ56nI4gXJBmUoG4YU06JgLgLgQAA */ id: 'Modeling', tsTypes: {} as import('./modelingMachine.typegen').Typegen0, predictableActionArguments: true, preserveActionOrder: true, context: { tool: null as Models['SceneToolType_type'] | null, selection: [] as string[], selectionRanges: { otherSelections: [], codeBasedSelections: [], } as Selections, sketchDetails: { sketchPathToNode: [], zAxis: [0, 0, 1], yAxis: [0, 1, 0], origin: [0, 0, 0], } as null | SketchDetails, sketchPlaneId: '' as string, sketchEnginePathId: '' as string, moveDescs: [] as MoveDesc[], mouseState: { type: 'idle' } as MouseState, segmentOverlays: {} as SegmentOverlays, segmentHoverMap: {} as { [pathToNodeString: string]: number }, store: { buttonDownInStream: undefined, didDragInStream: false, streamDimensions: { streamWidth: 1280, streamHeight: 720 }, openPanes: persistedContext.openPanes || ['code'], } as Store, }, schema: { events: {} as ModelingMachineEvent, }, states: { idle: { on: { 'Enter sketch': [ { target: 'animating to existing sketch', cond: 'Selection is on face', }, 'Sketch no face', ], Extrude: { target: 'idle', cond: 'has valid extrude selection', actions: ['AST extrude'], internal: true, }, Export: { target: 'idle', internal: true, cond: 'Has exportable geometry', actions: 'Engine export', }, 'Delete selection': { target: 'idle', cond: 'has valid selection for deletion', actions: ['AST delete selection'], internal: true, }, }, entry: 'reset client scene mouse handlers', }, Sketch: { states: { SketchIdle: { on: { 'Make segment vertical': { cond: 'Can make selection vertical', target: 'Await constrain vertically', }, 'Make segment horizontal': { cond: 'Can make selection horizontal', target: 'Await constrain horizontally', }, 'Constrain horizontal distance': { target: 'Await horizontal distance info', cond: 'Can constrain horizontal distance', }, 'Constrain vertical distance': { target: 'Await vertical distance info', cond: 'Can constrain vertical distance', }, 'Constrain ABS X': { target: 'Await ABS X info', cond: 'Can constrain ABS X', }, 'Constrain ABS Y': { target: 'Await ABS Y info', cond: 'Can constrain ABS Y', }, 'Constrain angle': { target: 'Await angle info', cond: 'Can constrain angle', }, 'Constrain length': { target: 'Await length info', cond: 'Can constrain length', }, 'Constrain perpendicular distance': { target: 'Await perpendicular distance info', cond: 'Can constrain perpendicular distance', }, 'Constrain horizontally align': { cond: 'Can constrain horizontally align', target: 'Await constrain horizontally align', }, 'Constrain vertically align': { cond: 'Can constrain vertically align', target: 'Await constrain vertically align', }, 'Constrain snap to X': { cond: 'Can constrain snap to X', target: 'Await constrain snap to X', }, 'Constrain snap to Y': { cond: 'Can constrain snap to Y', target: 'Await constrain snap to Y', }, 'Constrain equal length': { cond: 'Can constrain equal length', target: 'Await constrain equal length', }, 'Constrain parallel': { target: 'Await constrain parallel', cond: 'Can canstrain parallel', }, 'Constrain remove constraints': { cond: 'Can constrain remove constraints', target: 'Await constrain remove constraints', }, 'Re-execute': { target: 'SketchIdle', internal: true, actions: ['set sketchMetadata from pathToNode'], }, 'Equip Line tool': 'Line tool', 'Equip tangential arc to': { target: 'Tangential arc to', cond: 'is editing existing sketch', }, 'Equip rectangle tool': { target: 'Rectangle tool', cond: 'Sketch is empty', }, 'code edit during sketch': 'clean slate', 'Convert to variable': { target: 'Await convert to variable', cond: 'Can convert to variable', }, }, entry: 'setup client side sketch segments', }, 'Await horizontal distance info': { invoke: { src: 'Get horizontal info', id: 'get-horizontal-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await vertical distance info': { invoke: { src: 'Get vertical info', id: 'get-vertical-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await ABS X info': { invoke: { src: 'Get ABS X info', id: 'get-abs-x-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await ABS Y info': { invoke: { src: 'Get ABS Y info', id: 'get-abs-y-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await angle info': { invoke: { src: 'Get angle info', id: 'get-angle-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await length info': { invoke: { src: 'Get length info', id: 'get-length-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Await perpendicular distance info': { invoke: { src: 'Get perpendicular distance info', id: 'get-perpendicular-distance-info', onDone: { target: 'SketchIdle', actions: 'Set selection', }, onError: 'SketchIdle', }, }, 'Line tool': { exit: [], on: { 'Equip tangential arc to': { target: 'Tangential arc to', cond: 'is editing existing sketch', }, 'Equip rectangle tool': { target: 'Rectangle tool', cond: 'Sketch is empty', }, }, states: { Init: { always: [ { target: 'normal', cond: 'is editing existing sketch', actions: 'set up draft line', }, 'No Points', ], }, normal: {}, 'No Points': { entry: 'setup noPoints onClick listener', on: { 'Add start point': { target: 'normal', actions: 'set up draft line without teardown', }, Cancel: '#Modeling.Sketch.undo startSketchOn', }, }, }, initial: 'Init', }, Init: { always: [ { target: 'SketchIdle', cond: 'is editing existing sketch', }, 'Line tool', ], }, 'Tangential arc to': { entry: 'set up draft arc', on: { 'Equip Line tool': 'Line tool', }, }, 'undo startSketchOn': { invoke: { src: 'AST-undo-startSketchOn', id: 'AST-undo-startSketchOn', onDone: '#Modeling.idle', }, }, 'Rectangle tool': { entry: ['listen for rectangle origin'], states: { 'Awaiting second corner': {}, 'Awaiting origin': { on: { 'Add rectangle origin': { target: 'Awaiting second corner', actions: 'set up draft rectangle', }, }, }, }, initial: 'Awaiting origin', }, 'clean slate': { always: 'SketchIdle', }, 'Await convert to variable': { invoke: { src: 'Get convert to variable info', id: 'get-convert-to-variable-info', onError: 'SketchIdle', onDone: { target: 'SketchIdle', actions: ['Set selection'], }, }, }, 'Await constrain remove constraints': { invoke: { src: 'do-constrain-remove-constraint', id: 'do-constrain-remove-constraint', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain horizontally': { invoke: { src: 'do-constrain-horizontally', id: 'do-constrain-horizontally', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain vertically': { invoke: { src: 'do-constrain-vertically', id: 'do-constrain-vertically', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain horizontally align': { invoke: { src: 'do-constrain-horizontally-align', id: 'do-constrain-horizontally-align', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain vertically align': { invoke: { src: 'do-constrain-vertically-align', id: 'do-constrain-vertically-align', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain snap to X': { invoke: { src: 'do-constrain-snap-to-x', id: 'do-constrain-snap-to-x', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain snap to Y': { invoke: { src: 'do-constrain-snap-to-y', id: 'do-constrain-snap-to-y', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain equal length': { invoke: { src: 'do-constrain-equal-length', id: 'do-constrain-equal-length', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, 'Await constrain parallel': { invoke: { src: 'do-constrain-parallel', id: 'do-constrain-parallel', onDone: { target: 'SketchIdle', actions: 'Set selection', }, }, }, }, initial: 'Init', on: { CancelSketch: '.SketchIdle', 'Delete segment': { internal: true, actions: ['Delete segment', 'Set sketchDetails'], }, 'code edit during sketch': '.clean slate', }, exit: [ 'sketch exit execute', 'tear down client sketch', 'remove sketch grid', 'engineToClient cam sync direction', 'Reset Segment Overlays', 'enable copilot', ], entry: [ 'add axis n grid', 'conditionally equip line tool', 'clientToEngine cam sync direction', ], }, 'Sketch no face': { entry: [ 'disable copilot', 'show default planes', 'set selection filter to faces only', ], exit: ['hide default planes', 'set selection filter to defaults'], on: { 'Select default plane': { target: 'animating to plane', actions: ['reset sketch metadata'], }, }, }, 'animating to plane': { invoke: { src: 'animate-to-face', id: 'animate-to-face', onDone: { target: 'Sketch', actions: 'set new sketch metadata', }, }, }, 'animating to existing sketch': { invoke: [ { src: 'animate-to-sketch', id: 'animate-to-sketch', onDone: { target: 'Sketch', actions: ['disable copilot', 'set new sketch metadata'], }, }, ], }, }, initial: 'idle', on: { Cancel: { target: 'idle', // TODO what if we're existing extrude equipped, should these actions still be fired? // maybe cancel needs to have a guard for if else logic? actions: ['reset sketch metadata', 'enable copilot'], }, 'Set selection': { internal: true, actions: 'Set selection', }, 'Set mouse state': { internal: true, actions: 'Set mouse state', }, 'Set context': { internal: true, actions: 'Set context', }, 'Set Segment Overlays': { internal: true, actions: 'Set Segment Overlays', }, }, }, { guards: { 'is editing existing sketch': ({ sketchDetails }) => { // should check that the variable declaration is a pipeExpression // and that the pipeExpression contains a "startProfileAt" callExpression if (!sketchDetails?.sketchPathToNode) return false const variableDeclaration = getNodeFromPath( kclManager.ast, sketchDetails.sketchPathToNode, 'VariableDeclarator' ) if (err(variableDeclaration)) return false if (variableDeclaration.node.type !== 'VariableDeclarator') return false const pipeExpression = variableDeclaration.node.init if (pipeExpression.type !== 'PipeExpression') return false const hasStartProfileAt = pipeExpression.body.some( (item) => item.type === 'CallExpression' && item.callee.name === 'startProfileAt' ) return hasStartProfileAt && pipeExpression.body.length > 2 }, 'Can make selection horizontal': ({ selectionRanges }) => { const info = horzVertInfo(selectionRanges, 'horizontal') if (trap(info)) return false return info.enabled }, 'Can make selection vertical': ({ selectionRanges }) => { const info = horzVertInfo(selectionRanges, 'vertical') if (trap(info)) return false return info.enabled }, 'Can constrain horizontal distance': ({ selectionRanges }) => { const info = horzVertDistanceInfo({ selectionRanges, constraint: 'setHorzDistance', }) if (trap(info)) return false return info.enabled }, 'Can constrain vertical distance': ({ selectionRanges }) => { const info = horzVertDistanceInfo({ selectionRanges, constraint: 'setVertDistance', }) if (trap(info)) return false return info.enabled }, 'Can constrain ABS X': ({ selectionRanges }) => { const info = absDistanceInfo({ selectionRanges, constraint: 'xAbs' }) if (trap(info)) return false return info.enabled }, 'Can constrain ABS Y': ({ selectionRanges }) => { const info = absDistanceInfo({ selectionRanges, constraint: 'yAbs' }) if (trap(info)) return false return info.enabled }, 'Can constrain angle': ({ selectionRanges }) => { const angleBetween = angleBetweenInfo({ selectionRanges }) if (trap(angleBetween)) return false const angleLength = angleLengthInfo({ selectionRanges, angleOrLength: 'setAngle', }) if (trap(angleLength)) return false return angleBetween.enabled || angleLength.enabled }, 'Can constrain length': ({ selectionRanges }) => { const angleLength = angleLengthInfo({ selectionRanges }) if (trap(angleLength)) return false return angleLength.enabled }, 'Can constrain perpendicular distance': ({ selectionRanges }) => { const info = intersectInfo({ selectionRanges }) if (trap(info)) return false return info.enabled }, 'Can constrain horizontally align': ({ selectionRanges }) => { const info = horzVertDistanceInfo({ selectionRanges, constraint: 'setHorzDistance', }) if (trap(info)) return false return info.enabled }, 'Can constrain vertically align': ({ selectionRanges }) => { const info = horzVertDistanceInfo({ selectionRanges, constraint: 'setHorzDistance', }) if (trap(info)) return false return info.enabled }, 'Can constrain snap to X': ({ selectionRanges }) => { const info = absDistanceInfo({ selectionRanges, constraint: 'snapToXAxis', }) if (trap(info)) return false return info.enabled }, 'Can constrain snap to Y': ({ selectionRanges }) => { const info = absDistanceInfo({ selectionRanges, constraint: 'snapToYAxis', }) if (trap(info)) return false return info.enabled }, 'Can constrain equal length': ({ selectionRanges }) => { const info = setEqualLengthInfo({ selectionRanges }) if (trap(info)) return false return info.enabled }, 'Can canstrain parallel': ({ selectionRanges }) => { const info = equalAngleInfo({ selectionRanges }) if (err(info)) return false return info.enabled }, 'Can constrain remove constraints': ({ selectionRanges }, { data }) => { const info = removeConstrainingValuesInfo({ selectionRanges, pathToNodes: data && [data], }) if (trap(info)) return false return info.enabled }, 'Can convert to variable': (_, { data }) => { if (!data) return false const ast = parse(recast(kclManager.ast)) if (err(ast)) return false const isSafeRetVal = isNodeSafeToReplacePath(ast, data.pathToNode) if (err(isSafeRetVal)) return false return isSafeRetVal.isSafe }, }, // end guards actions: { 'set sketchMetadata from pathToNode': assign(({ sketchDetails }) => { if (!sketchDetails?.sketchPathToNode || !sketchDetails) return {} return { sketchDetails: { ...sketchDetails, sketchPathToNode: sketchDetails.sketchPathToNode, }, } }), 'hide default planes': () => { sceneInfra.removeDefaultPlanes() kclManager.hidePlanes() }, 'reset sketch metadata': assign({ sketchDetails: null, sketchEnginePathId: '', sketchPlaneId: '', }), 'set new sketch metadata': assign((_, { data }) => ({ sketchDetails: data, })), 'AST extrude': async (_, event) => { if (!event.data) return const { selection, distance } = event.data let ast = kclManager.ast if ( 'variableName' in distance && distance.variableName && distance.insertIndex !== undefined ) { const newBody = [...ast.body] newBody.splice( distance.insertIndex, 0, distance.variableDeclarationAst ) ast.body = newBody } const pathToNode = getNodePathFromSourceRange( ast, selection.codeBasedSelections[0].range ) const extrudeSketchRes = extrudeSketch( ast, pathToNode, false, 'variableName' in distance ? distance.variableIdentifierAst : distance.valueAst ) if (trap(extrudeSketchRes)) return const { modifiedAst, pathToExtrudeArg } = extrudeSketchRes const updatedAst = await kclManager.updateAst(modifiedAst, true, { focusPath: pathToExtrudeArg, }) if (updatedAst?.selections) { editorManager.selectRange(updatedAst?.selections) } }, 'AST delete selection': async ({ sketchDetails, selectionRanges }) => { let ast = kclManager.ast const modifiedAst = await deleteFromSelection( ast, selectionRanges.codeBasedSelections[0], kclManager.programMemory, getFaceDetails ) if (err(modifiedAst)) return const testExecute = await executeAst({ ast: modifiedAst, useFakeExecutor: true, engineCommandManager, }) if (testExecute.errors.length) { toast.error('Unable to delete part') return } await kclManager.updateAst(modifiedAst, true) }, 'conditionally equip line tool': (_, { type }) => { if (type === 'done.invoke.animate-to-face') { sceneInfra.modelingSend('Equip Line tool') } }, 'setup client side sketch segments': ({ sketchDetails, selectionRanges, }) => { if (!sketchDetails) return ;(async () => { if (Object.keys(sceneEntitiesManager.activeSegments).length > 0) { await sceneEntitiesManager.tearDownSketch({ removeAxis: false }) } sceneInfra.resetMouseListeners() await sceneEntitiesManager.setupSketch({ sketchPathToNode: sketchDetails?.sketchPathToNode || [], forward: sketchDetails.zAxis, up: sketchDetails.yAxis, position: sketchDetails.origin, maybeModdedAst: kclManager.ast, selectionRanges, }) sceneInfra.resetMouseListeners() sceneEntitiesManager.setupSketchIdleCallbacks({ pathToNode: sketchDetails?.sketchPathToNode || [], forward: sketchDetails.zAxis, up: sketchDetails.yAxis, position: sketchDetails.origin, }) })() }, 'tear down client sketch': () => { if (sceneEntitiesManager.activeSegments) { sceneEntitiesManager.tearDownSketch({ removeAxis: false }) } }, 'remove sketch grid': () => sceneEntitiesManager.removeSketchGrid(), 'set up draft line': ({ sketchDetails }) => { if (!sketchDetails) return sceneEntitiesManager.setUpDraftSegment( sketchDetails.sketchPathToNode, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin, 'line' ) }, 'set up draft arc': ({ sketchDetails }) => { if (!sketchDetails) return sceneEntitiesManager.setUpDraftSegment( sketchDetails.sketchPathToNode, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin, 'tangentialArcTo' ) }, 'listen for rectangle origin': ({ sketchDetails }) => { if (!sketchDetails) return sceneEntitiesManager.setupRectangleOriginListener() }, 'set up draft rectangle': ({ sketchDetails }, { data }) => { if (!sketchDetails || !data) return sceneEntitiesManager.setupDraftRectangle( sketchDetails.sketchPathToNode, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin, data ) }, 'set up draft line without teardown': ({ sketchDetails }) => { if (!sketchDetails) return sceneEntitiesManager.setUpDraftSegment( sketchDetails.sketchPathToNode, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin, 'line', false ) }, 'show default planes': () => { sceneInfra.showDefaultPlanes() sceneEntitiesManager.setupDefaultPlaneHover() kclManager.showPlanes() }, 'setup noPoints onClick listener': ({ sketchDetails }) => { if (!sketchDetails) return sceneEntitiesManager.createIntersectionPlane() const quaternion = quaternionFromUpNForward( new Vector3(...sketchDetails.yAxis), new Vector3(...sketchDetails.zAxis) ) sceneEntitiesManager.intersectionPlane && sceneEntitiesManager.intersectionPlane.setRotationFromQuaternion( quaternion ) sceneEntitiesManager.intersectionPlane && sceneEntitiesManager.intersectionPlane.position.copy( new Vector3(...(sketchDetails?.origin || [0, 0, 0])) ) sceneInfra.setCallbacks({ onClick: async (args) => { if (!args) return if (args.mouseEvent.which !== 1) return const { intersectionPoint } = args if (!intersectionPoint?.twoD || !sketchDetails?.sketchPathToNode) return const addStartProfileAtRes = addStartProfileAt( kclManager.ast, sketchDetails.sketchPathToNode, [intersectionPoint.twoD.x, intersectionPoint.twoD.y] ) if (trap(addStartProfileAtRes)) return const { modifiedAst } = addStartProfileAtRes await kclManager.updateAst(modifiedAst, false) sceneEntitiesManager.removeIntersectionPlane() sceneInfra.modelingSend('Add start point') }, }) }, 'add axis n grid': ({ sketchDetails }) => { if (!sketchDetails) return if (localStorage.getItem('disableAxis')) return sceneEntitiesManager.createSketchAxis( sketchDetails.sketchPathToNode || [], sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) }, 'reset client scene mouse handlers': () => { // when not in sketch mode we don't need any mouse listeners // (note the orbit controls are always active though) sceneInfra.resetMouseListeners() }, 'clientToEngine cam sync direction': () => { sceneInfra.camControls.syncDirection = 'clientToEngine' }, 'engineToClient cam sync direction': () => { sceneInfra.camControls.syncDirection = 'engineToClient' }, 'set selection filter to faces only': () => engineCommandManager.sendSceneCommand({ type: 'modeling_cmd_req', cmd_id: uuidv4(), cmd: { type: 'set_selection_filter', filter: ['face', 'object'], }, }), 'set selection filter to defaults': () => kclManager.defaultSelectionFilter(), 'Delete segment': ({ sketchDetails }, { data: pathToNode }) => deleteSegment({ pathToNode, sketchDetails }), 'Reset Segment Overlays': () => sceneEntitiesManager.resetOverlays(), 'Set context': assign({ store: ({ store }, { data }) => { if (data.streamDimensions) { sceneInfra._streamDimensions = data.streamDimensions } const result = { ...store, ...data, } const persistedContext: Partial = {} for (const key of PersistedValues) { persistedContext[key] = result[key] } if (typeof window !== 'undefined') { window.localStorage.setItem( PERSIST_MODELING_CONTEXT, JSON.stringify(persistedContext) ) } return result }, }), }, // end actions services: { 'do-constrain-remove-constraint': async ( { selectionRanges, sketchDetails }, { data } ) => { const constraint = applyRemoveConstrainingValues({ selectionRanges, pathToNodes: data && [data], }) if (trap(constraint)) return const { pathToNodeMap } = constraint if (!sketchDetails) return let updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( pathToNodeMap[0], constraint.modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return return { selectionType: 'completeSelection', selection: updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ), } }, 'do-constrain-horizontally': async ({ selectionRanges, sketchDetails, }) => { const constraint = applyConstraintHorzVert( selectionRanges, 'horizontal', kclManager.ast, kclManager.programMemory ) if (trap(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails.sketchPathToNode, modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return return { selectionType: 'completeSelection', selection: updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ), } }, 'do-constrain-vertically': async ({ selectionRanges, sketchDetails }) => { const constraint = applyConstraintHorzVert( selectionRanges, 'vertical', kclManager.ast, kclManager.programMemory ) if (trap(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return return { selectionType: 'completeSelection', selection: updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ), } }, 'do-constrain-horizontally-align': async ({ selectionRanges, sketchDetails, }) => { const constraint = applyConstraintHorzVertAlign({ selectionRanges, constraint: 'setVertDistance', }) if (trap(constraint)) return const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, 'do-constrain-vertically-align': async ({ selectionRanges, sketchDetails, }) => { const constraint = applyConstraintHorzVertAlign({ selectionRanges, constraint: 'setHorzDistance', }) if (trap(constraint)) return const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, 'do-constrain-snap-to-x': async ({ selectionRanges, sketchDetails }) => { const constraint = applyConstraintAxisAlign({ selectionRanges, constraint: 'snapToXAxis', }) if (err(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, 'do-constrain-snap-to-y': async ({ selectionRanges, sketchDetails }) => { const constraint = applyConstraintAxisAlign({ selectionRanges, constraint: 'snapToYAxis', }) if (trap(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, 'do-constrain-parallel': async ({ selectionRanges, sketchDetails }) => { const constraint = applyConstraintEqualAngle({ selectionRanges, }) if (trap(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) { trap(new Error('No sketch details')) return } const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], parse(recast(modifiedAst)), sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, 'do-constrain-equal-length': async ({ selectionRanges, sketchDetails, }) => { const constraint = applyConstraintEqualLength({ selectionRanges, }) if (trap(constraint)) return false const { modifiedAst, pathToNodeMap } = constraint if (!sketchDetails) return const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch( sketchDetails?.sketchPathToNode || [], modifiedAst, sketchDetails.zAxis, sketchDetails.yAxis, sketchDetails.origin ) if (trap(updatedAst, { suppress: true })) return if (!updatedAst) return const updatedSelectionRanges = updateSelections( pathToNodeMap, selectionRanges, updatedAst.newAst ) return { selectionType: 'completeSelection', selection: updatedSelectionRanges, } }, }, // end services } )