viewport.js 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600
  1. /*
  2. 3D Modeler - viewport
  3. The three.js scene: cameras, navigation, origin planes, the view cube, the
  4. axis triad and the display of tessellated bodies coming from the kernel.
  5. World is Z-up and in millimetres, like STEP and STL. Rendering is on
  6. demand: call invalidate() after changing anything, nothing redraws on its
  7. own while the view is still.
  8. Callbacks in options: onHover(item | null), onSelect([item]) for faces and
  9. edges of bodies (an item is the kernel's face or edge record plus kind,
  10. body and index), onHoverPlane(key | null) for the origin planes.
  11. Assemblies (js/assembly/) hand in bodies with a placement `matrix`, a
  12. `color` and a `group` (the component they belong to). Their face and
  13. edge records are then given in assembly coordinates, with the record in
  14. the part's own coordinates as `local`. In component mode
  15. (setComponentMode) the pointer picks whole groups instead of faces.
  16. */
  17. import * as THREE from 'three';
  18. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  19. import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
  20. import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
  21. import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
  22. import { TransformControls } from 'three/addons/controls/TransformControls.js';
  23. import { finishById, drawPattern, matchFaces, lightingById, normalizeScene, DEFAULT_COLOR, DEFAULT_SCALE, DEFAULT_SCENE } from './appearance.js';
  24. import { transformInfo } from './assembly/geometry.js';
  25. import { silhouetteSource, silhouetteSegments } from './silhouette.js';
  26. import { dragOffset, snapOffset } from './planedrag.js';
  27. import { faceView } from './faceview.js';
  28. const HOME_DIRECTION = new THREE.Vector3(1, -1, 1).normalize();
  29. const WORLD_UP = new THREE.Vector3(0, 0, 1);
  30. // The orbit ring shown while the left button orbits, as in the free orbit
  31. // of desktop CAD: a circle in the middle of the view with a tick outside it at each
  32. // quarter. Drag inside it to turn the view freely, outside it to roll the
  33. // view, on the top or bottom tick to turn about the screen's across axis, on
  34. // the left or right tick about its up axis. app.js draws it from this too.
  35. export function orbitRing(width, height) {
  36. const r = Math.round(Math.min(width, height) * 0.37);
  37. return { cx: Math.round(width / 2) + 0.5, cy: Math.round(height / 2) + 0.5, r: r, tick: Math.round(r * 0.21) };
  38. }
  39. // Two arrows round a circle, black on a white outline: the roll cursor
  40. const ROLL_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">' +
  41. '<g fill="none" stroke-linecap="round"><path d="M4.5 13A7.5 7.5 0 0 1 17 6.5M19.5 11A7.5 7.5 0 0 1 7 17.5" stroke="#fff" stroke-width="4"/>' +
  42. '<path d="M4.5 13A7.5 7.5 0 0 1 17 6.5M19.5 11A7.5 7.5 0 0 1 7 17.5" stroke="#000" stroke-width="1.6"/></g>' +
  43. '<path d="M15.5 8.1L18.5 4.9L18.9 8.2ZM8.5 15.9L5.5 19.1L5.1 15.8Z" fill="#000" stroke="#fff" stroke-width="1" stroke-linejoin="round"/></svg>';
  44. const RING_CURSORS = {
  45. free: 'grab',
  46. roll: 'url("data:image/svg+xml,' + encodeURIComponent(ROLL_SVG) + '") 12 12, alias',
  47. tilt: 'ns-resize',
  48. spin: 'ew-resize'
  49. };
  50. const RING_GRIP = 10; // pixels either side of a tick that still catch it
  51. const PLANE_SIZE = 120;
  52. // Origin planes: normal, the direction that is "up" on screen when looking at
  53. // the plane, and the label shown in the model browser.
  54. export const ORIGIN_PLANES = {
  55. yz: { label: 'YZ Plane', normal: [1, 0, 0], up: [0, 0, 1] },
  56. xz: { label: 'XZ Plane', normal: [0, -1, 0], up: [0, 0, 1] },
  57. xy: { label: 'XY Plane', normal: [0, 0, 1], up: [0, 1, 0] }
  58. };
  59. // View cube faces in the same convention: looking at FRONT means standing on -Y.
  60. const CUBE_FACES = [
  61. { name: 'FRONT', normal: [0, -1, 0], up: [0, 0, 1] },
  62. { name: 'BACK', normal: [0, 1, 0], up: [0, 0, 1] },
  63. { name: 'RIGHT', normal: [1, 0, 0], up: [0, 0, 1] },
  64. { name: 'LEFT', normal: [-1, 0, 0], up: [0, 0, 1] },
  65. { name: 'TOP', normal: [0, 0, 1], up: [0, 1, 0] },
  66. { name: 'BOTTOM', normal: [0, 0, -1], up: [0, -1, 0] }
  67. ];
  68. export function createViewport(options) {
  69. const canvas = options.canvas;
  70. const stage = canvas.parentElement;
  71. // stencil: the section caps (syncCaps) are masked with it
  72. const renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true, alpha: true, stencil: true });
  73. renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  74. const scene = new THREE.Scene();
  75. const target = new THREE.Vector3();
  76. // onRender: called after every frame. onSelection: while set, gets the
  77. // selection instead of options.onSelect (a feature panel that is picking).
  78. const api = { onRender: null, onSelection: null };
  79. const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, -5000, 5000);
  80. const persp = new THREE.PerspectiveCamera(35, 1, 1, 20000);
  81. let camera = ortho;
  82. let viewHeight = 260; // world millimetres visible top to bottom (orthographic)
  83. [ortho, persp].forEach(function (cam) {
  84. cam.up.copy(WORLD_UP);
  85. cam.position.copy(HOME_DIRECTION).multiplyScalar(600);
  86. cam.lookAt(target);
  87. });
  88. // A light that travels with the camera keeps every face readable while orbiting
  89. const headlight = new THREE.DirectionalLight(0xffffff, 2.1);
  90. const hemi = new THREE.HemisphereLight(0xffffff, 0x8a8f99, 1.5);
  91. scene.add(hemi);
  92. scene.add(headlight);
  93. scene.add(headlight.target);
  94. // How this viewer likes to see models (appearance.js normalizeScene):
  95. // lighting preset, reflections, ground shadow, ground plane, textures
  96. let sceneOpts = Object.assign({}, DEFAULT_SCENE);
  97. function applyLighting() {
  98. const l = lightingById(sceneOpts.lighting);
  99. hemi.color.setHex(l.sky);
  100. hemi.groundColor.setHex(l.ground);
  101. hemi.intensity = l.hemi;
  102. headlight.color.setHex(l.head);
  103. headlight.intensity = l.headIntensity;
  104. }
  105. /* ---- ground: a shadow and a grid under the model ---- */
  106. // The shadow comes from a light straight above that lights nothing
  107. // (intensity 0): it only casts the shadow on a plane that shows nothing
  108. // but shadows, so the look of the model does not change
  109. renderer.shadowMap.enabled = true;
  110. renderer.shadowMap.type = THREE.PCFShadowMap;
  111. const sun = new THREE.DirectionalLight(0xffffff, 0);
  112. sun.castShadow = false;
  113. sun.shadow.mapSize.set(2048, 2048);
  114. sun.shadow.bias = -0.0004;
  115. sun.shadow.radius = 4; // soft edges (PCF)
  116. scene.add(sun);
  117. scene.add(sun.target);
  118. const groundGroup = new THREE.Group();
  119. groundGroup.visible = false;
  120. scene.add(groundGroup);
  121. const shadowPlane = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.ShadowMaterial({ opacity: 0.45, depthWrite: false }));
  122. shadowPlane.receiveShadow = true;
  123. groundGroup.add(shadowPlane);
  124. let grid = null;
  125. let gridKey = '';
  126. let groundDirty = true; // placed again before the next frame
  127. const controls = new OrbitControls(camera, canvas);
  128. controls.enableDamping = false;
  129. controls.zoomToCursor = true;
  130. controls.screenSpacePanning = true;
  131. // The desktop CAD mouse: the left button only selects and draws, the middle
  132. // button pans, Shift + middle orbits (OrbitControls swaps pan and rotate
  133. // on Shift by itself), the wheel zooms. Orbit and Pan on the navigation
  134. // bar, or holding F4, lend the left button to the view (setLeftDrag).
  135. controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.PAN, RIGHT: null };
  136. controls.addEventListener('change', invalidate);
  137. // The wheel zooms the desktop CAD way round: rolling it away from you
  138. // zooms out, towards you zooms in (the owner found three.js's own way
  139. // flipped). Only the wheel: pinching keeps its direction.
  140. const wheelZoom = controls._handleMouseWheel;
  141. controls._handleMouseWheel = function (event) {
  142. wheelZoom.call(controls, { clientX: event.clientX, clientY: event.clientY, deltaX: event.deltaX, deltaY: -event.deltaY, deltaMode: event.deltaMode });
  143. };
  144. let leftDrag = 'select'; // 'select' | 'orbit' | 'pan'
  145. let ringHover = 'free'; // the orbit ring zone under the pointer (ringZone)
  146. let sketching = false;
  147. // Free orbit, as in desktop CAD: the view turns round the orbit centre about
  148. // the axes of the screen, never about world Z, so any side of the part
  149. // can face down and nothing snaps the view upright again. OrbitControls
  150. // still reads the mouse and fingers (Shift + middle button, one finger,
  151. // the left button inside the orbit ring), but its two turn steps come
  152. // here instead of changing its turntable angles. camera.up turns with the
  153. // view, and OrbitControls.update() then keeps exactly this orientation.
  154. function screenAxis(x, y, z) {
  155. return new THREE.Vector3(x, y, z).applyQuaternion(camera.quaternion);
  156. }
  157. // Turn the camera by `angle` about `axis` (world space, through the orbit centre)
  158. function turnView(axis, angle) {
  159. if (!angle) {
  160. return;
  161. }
  162. const q = new THREE.Quaternion().setFromAxisAngle(axis, angle);
  163. const up = screenAxis(0, 1, 0).applyQuaternion(q);
  164. camera.position.sub(controls.target).applyQuaternion(q).add(controls.target);
  165. camera.up.copy(up);
  166. camera.lookAt(controls.target);
  167. }
  168. // The part follows the pointer: dragging right turns the camera the other
  169. // way about the screen's up, dragging down about the screen's across axis
  170. controls._rotateLeft = function (angle) {
  171. turnView(screenAxis(0, 1, 0), -angle);
  172. };
  173. controls._rotateUp = function (angle) {
  174. turnView(screenAxis(1, 0, 0), -angle);
  175. };
  176. function leftButton() {
  177. return leftDrag === 'pan' ? THREE.MOUSE.PAN : leftDrag === 'orbit' ? THREE.MOUSE.ROTATE : null;
  178. }
  179. /* ---------------- origin geometry ---------------- */
  180. const originGroup = new THREE.Group();
  181. originGroup.visible = false;
  182. scene.add(originGroup);
  183. const planeMeshes = {};
  184. Object.keys(ORIGIN_PLANES).forEach(function (key) {
  185. const def = ORIGIN_PLANES[key];
  186. const material = new THREE.MeshBasicMaterial({
  187. color: 0xd8b24a, transparent: true, opacity: 0.22, side: THREE.DoubleSide, depthWrite: false
  188. });
  189. const mesh = new THREE.Mesh(new THREE.PlaneGeometry(PLANE_SIZE, PLANE_SIZE), material);
  190. mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), new THREE.Vector3().fromArray(def.normal));
  191. mesh.userData.plane = key;
  192. const outline = new THREE.LineSegments(
  193. new THREE.EdgesGeometry(mesh.geometry),
  194. new THREE.LineBasicMaterial({ color: 0x9c7a1c })
  195. );
  196. mesh.add(outline);
  197. originGroup.add(mesh);
  198. planeMeshes[key] = mesh;
  199. });
  200. /* ---------------- work planes ---------------- */
  201. // Work plane features, drawn as blue sheets: [{ id, frame, draft }]
  202. const workGroup = new THREE.Group();
  203. scene.add(workGroup);
  204. let hotWork = null;
  205. function setWorkPlanes(list) {
  206. while (workGroup.children.length) {
  207. const child = workGroup.children.pop();
  208. child.geometry.dispose();
  209. child.material.dispose();
  210. child.children[0].geometry.dispose();
  211. }
  212. // Big enough to be seen around the part, centred on the part
  213. const box = new THREE.Box3();
  214. if (bodies.length) {
  215. box.setFromObject(bodyGroup);
  216. }
  217. const centre = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
  218. const size = box.isEmpty() ? PLANE_SIZE : Math.max(box.getSize(new THREE.Vector3()).length() * 0.9, 40);
  219. (list || []).forEach(function (plane) {
  220. const f = plane.frame;
  221. const n = new THREE.Vector3().fromArray(f.n);
  222. const o = new THREE.Vector3().fromArray(f.o);
  223. const mesh = new THREE.Mesh(new THREE.PlaneGeometry(size, size), new THREE.MeshBasicMaterial({
  224. color: plane.draft ? HOVER : 0x4a90d9, transparent: true, opacity: 0.2, side: THREE.DoubleSide, depthWrite: false
  225. }));
  226. mesh.matrixAutoUpdate = false;
  227. // The part's centre dropped onto the plane is the middle of the sheet
  228. const middle = centre.clone().sub(n.clone().multiplyScalar(centre.clone().sub(o).dot(n)));
  229. mesh.matrix.makeBasis(new THREE.Vector3().fromArray(f.x), new THREE.Vector3().fromArray(f.y), n).setPosition(middle);
  230. mesh.userData.work = plane.id;
  231. mesh.add(new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry), new THREE.LineBasicMaterial({ color: plane.draft ? HOVER : 0x2f6fb5 })));
  232. workGroup.add(mesh);
  233. });
  234. hotWork = null;
  235. invalidate();
  236. }
  237. function setHotWork(id) {
  238. if (id === hotWork) {
  239. return;
  240. }
  241. hotWork = id;
  242. workGroup.children.forEach(function (mesh) {
  243. mesh.material.opacity = mesh.userData.work === id ? 0.45 : 0.2;
  244. });
  245. invalidate();
  246. }
  247. /* ---------------- bodies ---------------- */
  248. // One entry per solid: { data, mesh, lines }. `data` is the description
  249. // from the kernel (kernel/occt.js describe): the mesh with an index range
  250. // per face and the edge segments with a vertex range per edge.
  251. const bodyGroup = new THREE.Group();
  252. const overlayGroup = new THREE.Group();
  253. scene.add(bodyGroup);
  254. scene.add(overlayGroup);
  255. let bodies = [];
  256. const bodyMaterial = new THREE.MeshStandardMaterial({
  257. color: 0xbfc3c9, metalness: 0.1, roughness: 0.62,
  258. polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  259. });
  260. const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x20242b });
  261. // Edges a surface covers, dashed: drawn only where something nearer was
  262. // drawn first (GreaterDepth), after every body (transparent, renderOrder
  263. // 1). The dash length follows the zoom (updateDashes), so it stays the
  264. // same on screen.
  265. const hiddenEdgeMaterial = hiddenLineMaterial();
  266. // Wireframe: the bodies are drawn into the depth buffer only, so the
  267. // edges behind them can tell they are covered
  268. const depthMaterial = new THREE.MeshBasicMaterial({
  269. colorWrite: false, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  270. });
  271. const capMaterial = new THREE.MeshBasicMaterial({ color: 0xc9713d, side: THREE.BackSide });
  272. // Materials of coloured bodies (assembly components), one per body so
  273. // each can be tinted on its own; cleared with the bodies
  274. let ownMaterials = [];
  275. // Materials of painted faces (appearance faces), made again with the
  276. // bodies or the look
  277. let faceMaterials = [];
  278. let partAppearance = null; // the look of the part on show (setAppearance)
  279. const looks = new WeakMap(); // material -> { app, color, opacity } it was dressed with
  280. /* ---- appearance (appearance.js): colour, finish, pattern ---- */
  281. const patternTextures = {}; // pattern -> CanvasTexture, drawn once
  282. let baseOpacity = 1; // of the part on show: below 1 for glass
  283. let ghostOn = false; // a fillet / chamfer result preview is on
  284. function patternBase(pattern) {
  285. let base = patternTextures[pattern];
  286. if (!base) {
  287. const canvas = document.createElement('canvas');
  288. canvas.width = 256;
  289. canvas.height = 256;
  290. drawPattern(canvas.getContext('2d'), 256, pattern);
  291. base = new THREE.CanvasTexture(canvas);
  292. base.wrapS = THREE.RepeatWrapping;
  293. base.wrapT = THREE.RepeatWrapping;
  294. base.colorSpace = THREE.SRGBColorSpace;
  295. base.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
  296. patternTextures[pattern] = base;
  297. }
  298. return base;
  299. }
  300. // The picture of an Image finish (a data URL): null until it is loaded,
  301. // then the looks are dressed again
  302. const imageTextures = new Map(); // data URL -> Texture | 'loading' | 'failed'
  303. function imageBase(url) {
  304. const known = imageTextures.get(url);
  305. if (known) {
  306. return typeof known === 'string' ? null : known;
  307. }
  308. imageTextures.set(url, 'loading');
  309. const img = new Image();
  310. img.onload = function () {
  311. const t = new THREE.Texture(img);
  312. t.wrapS = THREE.RepeatWrapping;
  313. t.wrapT = THREE.RepeatWrapping;
  314. t.colorSpace = THREE.SRGBColorSpace;
  315. t.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
  316. t.needsUpdate = true;
  317. imageTextures.set(url, t);
  318. refreshLooks();
  319. };
  320. img.onerror = function () {
  321. imageTextures.set(url, 'failed');
  322. };
  323. img.src = url;
  324. return null;
  325. }
  326. // The pattern or picture of a finish, one tile per `scale` mm (the
  327. // texture coordinates are in mm), turned by `rotation` degrees; none
  328. // while textures are off
  329. function finishTexture(finish, app) {
  330. if (!sceneOpts.textures) {
  331. return null;
  332. }
  333. const base = finish.image ? (app && app.image ? imageBase(app.image) : null) : finish.pattern ? patternBase(finish.pattern) : null;
  334. if (!base) {
  335. return null;
  336. }
  337. const scale = (app && app.scale) || DEFAULT_SCALE;
  338. const img = base.image;
  339. // A picture keeps its proportions: `scale` is its width
  340. const aspect = finish.image && img && img.width && img.height ? img.width / img.height : 1;
  341. const texture = base.clone(); // the same picture, its own repeat
  342. texture.repeat.set(1 / scale, aspect / scale);
  343. texture.rotation = THREE.MathUtils.degToRad((app && app.rotation) || 0);
  344. texture.needsUpdate = true;
  345. return texture;
  346. }
  347. // Metal needs something to reflect, or it looks dull grey: a small
  348. // studio (a grey room with bright panels) made once, prefiltered by
  349. // three.js's PMREM generator, used by the metal finishes only, so the
  350. // default look of a part does not change
  351. let studio = null;
  352. function studioEnvironment() {
  353. if (studio) {
  354. return studio;
  355. }
  356. const room = new THREE.Scene();
  357. const box = new THREE.BoxGeometry(10, 10, 10);
  358. room.add(new THREE.Mesh(box, new THREE.MeshBasicMaterial({ color: 0x7d838c, side: THREE.BackSide })));
  359. const panel = function (w, h, position, rotation, intensity) {
  360. const mesh = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({
  361. color: new THREE.Color(1, 1, 1).multiplyScalar(intensity), side: THREE.DoubleSide
  362. }));
  363. mesh.position.fromArray(position);
  364. mesh.rotation.fromArray(rotation);
  365. room.add(mesh);
  366. };
  367. panel(7, 2.2, [0, 4.8, 0], [Math.PI / 2, 0, 0], 3.2);
  368. panel(2.4, 5, [-4.8, 0.5, 0.8], [0, Math.PI / 2, 0], 2.2);
  369. panel(2, 4, [4.8, 0, -1.5], [0, -Math.PI / 2, 0], 1.6);
  370. panel(5, 1.2, [0, -1, -4.8], [0, 0, 0], 1.2);
  371. const pmrem = new THREE.PMREMGenerator(renderer);
  372. studio = pmrem.fromScene(room, 0.04).texture;
  373. pmrem.dispose();
  374. room.traverse(function (o) {
  375. if (o.geometry) {
  376. o.geometry.dispose();
  377. }
  378. if (o.material) {
  379. o.material.dispose();
  380. }
  381. });
  382. return studio;
  383. }
  384. // Give a material the look of an appearance. `color` (a component's
  385. // colour) wins over the appearance's own. Returns its opacity.
  386. function dressMaterial(material, app, color) {
  387. const finish = finishById(app && app.texture);
  388. if (material.map) {
  389. material.map.dispose();
  390. }
  391. material.color.set(color !== undefined ? color : (app && app.color) || DEFAULT_COLOR);
  392. material.roughness = finish.roughness;
  393. material.metalness = finish.metalness;
  394. // Reflections: metals mirror the studio, glossy finishes a little
  395. const metal = finish.metalness >= 0.3;
  396. material.envMap = sceneOpts.reflections && (metal || finish.roughness < 0.4) ? studioEnvironment() : null;
  397. material.envMapIntensity = metal ? 1 : 0.35;
  398. material.map = finishTexture(finish, app);
  399. const opacity = finish.opacity || 1;
  400. material.transparent = opacity < 1;
  401. material.opacity = opacity;
  402. material.depthWrite = opacity >= 1;
  403. material.needsUpdate = true;
  404. looks.set(material, { app: app, color: color, opacity: opacity });
  405. return opacity;
  406. }
  407. // The faces painted in the look of each body (appearance faces) get
  408. // materials of their own, through geometry groups: one group per run of
  409. // faces with the same look, material 0 the body's own
  410. function applyFaceLooks() {
  411. faceMaterials.forEach(function (m) {
  412. if (m.map) {
  413. m.map.dispose();
  414. }
  415. m.dispose();
  416. });
  417. faceMaterials = [];
  418. bodies.forEach(function (body, b) {
  419. const geometry = body.mesh.geometry;
  420. geometry.clearGroups();
  421. body.mesh.material = body.baseMaterial;
  422. const own = body.data.color !== undefined || !!body.data.appearance;
  423. const app = own ? body.data.appearance : partAppearance;
  424. const refs = app && app.faces;
  425. if (!refs || !refs.length || !body.data.faces) {
  426. return;
  427. }
  428. const hit = matchFaces(body.data.faces, refs, body.data.partBody !== undefined ? body.data.partBody : b);
  429. if (!hit.some(function (r) {
  430. return r >= 0;
  431. })) {
  432. return;
  433. }
  434. const list = [body.baseMaterial];
  435. const slot = {};
  436. let run = null;
  437. body.data.faces.forEach(function (face, i) {
  438. let m = 0;
  439. if (hit[i] >= 0) {
  440. const ref = refs[hit[i]];
  441. const key = ref.color + '/' + ref.texture;
  442. if (slot[key] === undefined) {
  443. const material = new THREE.MeshStandardMaterial({
  444. polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  445. });
  446. dressMaterial(material, { color: ref.color, texture: ref.texture, scale: app.scale, rotation: app.rotation });
  447. material.clippingPlanes = sectionPlanes;
  448. material.clipIntersection = section.mode === 'threequarter';
  449. faceMaterials.push(material);
  450. slot[key] = list.length;
  451. list.push(material);
  452. }
  453. m = slot[key];
  454. }
  455. if (run && run.m === m && run.end === face.start) {
  456. run.end = face.start + face.count;
  457. } else {
  458. run = { start: face.start, end: face.start + face.count, m: m };
  459. geometry.addGroup(run.start, 0, m);
  460. }
  461. geometry.groups[geometry.groups.length - 1].count = run.end - run.start;
  462. });
  463. body.mesh.material = list;
  464. });
  465. }
  466. // Every look dressed again: after the scene changed (textures,
  467. // reflections) or a picture finished loading
  468. function refreshLooks() {
  469. baseOpacity = dressMaterial(bodyMaterial, partAppearance);
  470. ownMaterials.forEach(function (m) {
  471. const look = looks.get(m);
  472. if (look) {
  473. dressMaterial(m, look.app, look.color);
  474. }
  475. });
  476. applyFaceLooks();
  477. applyGhost();
  478. applyVisualStyle();
  479. invalidate();
  480. }
  481. // While a result preview is on, the real body is a faint ghost
  482. function applyGhost() {
  483. faceMaterials.forEach(function (m) {
  484. const o = looks.get(m).opacity;
  485. m.transparent = ghostOn || o < 1;
  486. m.opacity = ghostOn ? 0.06 : o;
  487. m.depthWrite = !ghostOn && o >= 1;
  488. m.needsUpdate = true;
  489. });
  490. bodyMaterial.transparent = ghostOn || baseOpacity < 1;
  491. bodyMaterial.opacity = ghostOn ? 0.06 : baseOpacity;
  492. bodyMaterial.depthWrite = !ghostOn && baseOpacity >= 1;
  493. edgeMaterial.transparent = ghostOn;
  494. edgeMaterial.opacity = ghostOn ? 0.3 : 1;
  495. bodyMaterial.needsUpdate = true;
  496. edgeMaterial.needsUpdate = true;
  497. }
  498. // Texture coordinates in mm by box projection: each vertex takes the two
  499. // axes across its normal's main direction, so a pattern lies flat on
  500. // every side of a part
  501. function addUVs(geometry) {
  502. const pos = geometry.getAttribute('position');
  503. const nor = geometry.getAttribute('normal');
  504. const uv = new Float32Array(pos.count * 2);
  505. for (let i = 0; i < pos.count; i++) {
  506. const ax = Math.abs(nor.getX(i));
  507. const ay = Math.abs(nor.getY(i));
  508. const az = Math.abs(nor.getZ(i));
  509. if (az >= ax && az >= ay) {
  510. uv[2 * i] = pos.getX(i);
  511. uv[2 * i + 1] = pos.getY(i);
  512. } else if (ax >= ay) {
  513. uv[2 * i] = pos.getY(i);
  514. uv[2 * i + 1] = pos.getZ(i);
  515. } else {
  516. uv[2 * i] = pos.getX(i);
  517. uv[2 * i + 1] = pos.getZ(i);
  518. }
  519. }
  520. geometry.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
  521. }
  522. // The section view: mode "none" | "half" | "quarter" | "threequarter";
  523. // plane / plane2 "xz" | "yz" | "xy"; offset / offset2 the position along
  524. // the plane's normal axis (null: through the middle of the model);
  525. // flip / flip2 keep the other side
  526. let section = { mode: 'none', plane: 'xz', offset: null, flip: false, plane2: 'yz', offset2: null, flip2: false };
  527. let sectionPlanes = [];
  528. let sectionHandles = null; // the sheets and arrows to drag the planes (made below)
  529. let sectionHot = null; // the one under the pointer
  530. // The hatched cut faces (syncCaps): made when first needed
  531. let capGroup = null;
  532. let capParts = []; // [{ body, plane: 0 | 1, stencils: [mesh, mesh], cap: mesh }]
  533. let capKey = ''; // what capParts were made for
  534. let hatch = null; // the hatching texture
  535. let bodiesVersion = 0; // counts setBodies, so the caps are made again for new bodies
  536. const capPlanes = [new THREE.Plane(), new THREE.Plane()];
  537. const capOutside = [new THREE.Plane(), new THREE.Plane()]; // the same, turned round
  538. let componentMode = false; // the pointer picks whole components (groups)
  539. renderer.localClippingEnabled = true;
  540. const HOVER = 0xf0943a;
  541. const SELECTED = 0x2f7fe0;
  542. const overlayMaterials = {
  543. hoverface: new THREE.MeshBasicMaterial({ color: HOVER, transparent: true, opacity: 0.55, depthWrite: false }),
  544. selectedface: new THREE.MeshBasicMaterial({ color: SELECTED, transparent: true, opacity: 0.6, depthWrite: false }),
  545. // WebGL draws plain lines one pixel wide, too thin to see what the
  546. // pointer is on: highlighted edges use the screen space "fat" lines
  547. // (width in CSS pixels, kept in step with the canvas in resize())
  548. // The part of an edge behind the model is drawn again, faint, so a
  549. // picked loop can be followed all round without hiding the faces
  550. hoveredge: new LineMaterial({ color: HOVER, linewidth: 4, depthWrite: false }),
  551. hoveredgehidden: new LineMaterial({ color: HOVER, linewidth: 2, depthTest: false, depthWrite: false, transparent: true, opacity: 0.35 }),
  552. selectededge: new LineMaterial({ color: SELECTED, linewidth: 3, depthWrite: false }),
  553. selectededgehidden: new LineMaterial({ color: SELECTED, linewidth: 2, depthTest: false, depthWrite: false, transparent: true, opacity: 0.35 })
  554. };
  555. let visualStyle = 'shaded-edges';
  556. let interactive = true; // false while the sketcher owns the pointer
  557. let pickFilter = null; // { edges, faces, toggle } while a feature panel picks, else null
  558. let hovered = null; // { type: "face" | "edge", body, index }
  559. let selection = []; // same shape as hovered
  560. function disposeGroup(group) {
  561. while (group.children.length) {
  562. const child = group.children.pop();
  563. if (child.geometry) {
  564. child.geometry.dispose();
  565. }
  566. }
  567. }
  568. // Every material the bodies are drawn with, for clipping and styles
  569. function bodyMaterials() {
  570. return [bodyMaterial, capMaterial, edgeMaterial, hiddenEdgeMaterial, depthMaterial].concat(ownMaterials, faceMaterials);
  571. }
  572. function hiddenLineMaterial() {
  573. return new THREE.LineDashedMaterial({
  574. color: 0x20242b, transparent: true, opacity: 0.6, depthFunc: THREE.GreaterDepth, depthWrite: false,
  575. dashSize: 1, gapSize: 1
  576. });
  577. }
  578. // Dashes of about 6 pixels with gaps of 4 at any zoom
  579. function updateDashes() {
  580. const w = worldPerPixel();
  581. const dashed = [hiddenEdgeMaterial];
  582. previewGroup.children.forEach(function (child) {
  583. if (child.userData.role === 'result-hidden') {
  584. dashed.push(child.material);
  585. }
  586. });
  587. dashed.forEach(function (material) {
  588. material.dashSize = 6 * w;
  589. material.gapSize = 4 * w;
  590. });
  591. }
  592. // Put a body's objects where its placement matrix says (assemblies)
  593. function placeBody(body, matrix) {
  594. const m = new THREE.Matrix4().fromArray(matrix);
  595. [body.mesh, body.depth, body.cap, body.hidden, body.lines].concat(body.sil ? [body.sil.front, body.sil.behind] : []).forEach(function (object) {
  596. m.decompose(object.position, object.quaternion, object.scale);
  597. object.updateMatrixWorld(true);
  598. });
  599. body.matrix = matrix.slice();
  600. groundDirty = true;
  601. silhouetteKey = '';
  602. }
  603. /* ---- silhouettes of round faces (silhouette.js) ---- */
  604. let silhouetteKey = ''; // the view the silhouettes were worked out for
  605. function makeSilhouette(data) {
  606. const src = silhouetteSource(data.positions, data.indices, data.faces);
  607. if (!src) {
  608. return null;
  609. }
  610. const geometry = new THREE.BufferGeometry();
  611. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(src.edges * 6), 3));
  612. geometry.setAttribute('lineDistance', new THREE.BufferAttribute(new Float32Array(src.edges * 2), 1));
  613. geometry.setDrawRange(0, 0);
  614. const front = new THREE.LineSegments(geometry, edgeMaterial);
  615. const behind = new THREE.LineSegments(geometry, hiddenEdgeMaterial);
  616. behind.renderOrder = 1;
  617. // Their points change with the view: no stale bounds
  618. front.frustumCulled = false;
  619. behind.frustumCulled = false;
  620. bodyGroup.add(front);
  621. bodyGroup.add(behind);
  622. silhouetteKey = '';
  623. return { src: src, geometry: geometry, front: front, behind: behind };
  624. }
  625. const silInverse = new THREE.Matrix4();
  626. const silView = new THREE.Vector3();
  627. function updateSilhouettes() {
  628. if (visualStyle === 'shaded' || !bodies.length) {
  629. return;
  630. }
  631. const perspective = camera === persp;
  632. if (perspective) {
  633. silView.copy(camera.position);
  634. } else {
  635. camera.getWorldDirection(silView);
  636. }
  637. const key = (perspective ? 'p' : 'o') + silView.toArray().map(function (v) {
  638. return v.toFixed(5);
  639. }).join(',') + '/' + bodies.length;
  640. if (key === silhouetteKey) {
  641. return;
  642. }
  643. silhouetteKey = key;
  644. bodies.forEach(function (body) {
  645. if (!body.sil) {
  646. return;
  647. }
  648. // The view in the body's own coordinates (assembly placements)
  649. body.mesh.updateMatrixWorld();
  650. silInverse.copy(body.mesh.matrixWorld).invert();
  651. const v = silView.clone();
  652. if (perspective) {
  653. v.applyMatrix4(silInverse);
  654. } else {
  655. v.transformDirection(silInverse);
  656. }
  657. const geometry = body.sil.geometry;
  658. const count = silhouetteSegments(body.sil.src, v.toArray(), perspective,
  659. geometry.getAttribute('position').array, geometry.getAttribute('lineDistance').array);
  660. geometry.setDrawRange(0, count * 2);
  661. geometry.getAttribute('position').needsUpdate = true;
  662. geometry.getAttribute('lineDistance').needsUpdate = true;
  663. });
  664. }
  665. // The ground shadow and grid under the bodies (not while sketching)
  666. function placeGround() {
  667. groundDirty = false;
  668. const show = !sketching && bodies.length > 0 && (sceneOpts.shadows || sceneOpts.ground);
  669. groundGroup.visible = show;
  670. sun.castShadow = show && sceneOpts.shadows;
  671. if (!show) {
  672. return;
  673. }
  674. bodyGroup.updateMatrixWorld(true);
  675. const box = new THREE.Box3();
  676. bodies.forEach(function (b) {
  677. box.expandByObject(b.mesh);
  678. });
  679. if (box.isEmpty()) {
  680. groundGroup.visible = false;
  681. sun.castShadow = false;
  682. return;
  683. }
  684. const size = box.getSize(new THREE.Vector3());
  685. const centre = box.getCenter(new THREE.Vector3());
  686. const span = Math.max(size.x, size.y, size.z, 1);
  687. const z = box.min.z - span * 0.002;
  688. shadowPlane.visible = sceneOpts.shadows;
  689. shadowPlane.position.set(centre.x, centre.y, z);
  690. shadowPlane.scale.set(span * 4, span * 4, 1);
  691. // A grid of 1, 2 or 5 times a power of ten, about four cells across the part
  692. const step = Math.pow(10, Math.floor(Math.log10(span / 4)));
  693. const ratio = span / 4 / step;
  694. const cell = ratio >= 5 ? step * 5 : ratio >= 2 ? step * 2 : step;
  695. const cells = 2 * Math.ceil(span * 1.5 / cell);
  696. const key = cell + ':' + cells;
  697. if (key !== gridKey) {
  698. if (grid) {
  699. groundGroup.remove(grid);
  700. grid.geometry.dispose();
  701. grid.material.dispose();
  702. }
  703. grid = new THREE.GridHelper(cell * cells, cells, 0x8a919c, 0x8a919c);
  704. grid.rotation.x = Math.PI / 2; // the XY plane: Z is up
  705. grid.material.transparent = true;
  706. grid.material.opacity = 0.4;
  707. grid.material.depthWrite = false;
  708. groundGroup.add(grid);
  709. gridKey = key;
  710. }
  711. grid.visible = sceneOpts.ground;
  712. grid.position.set(Math.round(centre.x / cell) * cell, Math.round(centre.y / cell) * cell, z);
  713. // The light a little off straight above, so the shadow shows the shape
  714. sun.position.set(centre.x + span * 0.6, centre.y + span * 0.9, box.max.z + span * 2);
  715. sun.target.position.set(centre.x, centre.y, z);
  716. sun.target.updateMatrixWorld();
  717. const cam = sun.shadow.camera;
  718. cam.left = -span * 1.6;
  719. cam.right = span * 1.6;
  720. cam.top = span * 1.6;
  721. cam.bottom = -span * 1.6;
  722. cam.near = 0.1;
  723. cam.far = span * 4 + size.z;
  724. cam.updateProjectionMatrix();
  725. }
  726. function setBodies(list) {
  727. bodiesVersion++;
  728. disposeGroup(bodyGroup);
  729. ownMaterials.forEach(function (material) {
  730. material.dispose();
  731. });
  732. ownMaterials = [];
  733. bodies = list.map(function (data, i) {
  734. const geometry = new THREE.BufferGeometry();
  735. geometry.setAttribute('position', new THREE.BufferAttribute(data.positions, 3));
  736. geometry.setIndex(new THREE.BufferAttribute(data.indices, 1));
  737. geometry.computeVertexNormals();
  738. addUVs(geometry);
  739. let material = bodyMaterial;
  740. let cap = capMaterial;
  741. if (data.color !== undefined || data.appearance) {
  742. // A component colour (or a part's own look in an assembly or
  743. // a drawing): a material of its own, so it can be tinted
  744. material = new THREE.MeshStandardMaterial({
  745. polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  746. });
  747. dressMaterial(material, data.appearance, data.color);
  748. // The cut face of a component in a darker shade of its colour
  749. cap = new THREE.MeshBasicMaterial({ color: material.color.clone().multiplyScalar(0.62), side: THREE.BackSide });
  750. ownMaterials.push(material, cap);
  751. }
  752. const mesh = new THREE.Mesh(geometry, material);
  753. mesh.userData.body = i;
  754. mesh.castShadow = true;
  755. const lineGeometry = new THREE.BufferGeometry();
  756. lineGeometry.setAttribute('position', new THREE.BufferAttribute(data.edgePositions || new Float32Array(0), 3));
  757. const lines = new THREE.LineSegments(lineGeometry, edgeMaterial);
  758. lines.userData.body = i;
  759. // The same edges dashed where a surface covers them, for the
  760. // wireframe and hidden edge styles
  761. const hidden = new THREE.LineSegments(lineGeometry, hiddenEdgeMaterial);
  762. hidden.computeLineDistances();
  763. hidden.renderOrder = 1;
  764. // The body in the depth buffer only, for the wireframe style:
  765. // drawn first, so the edges it covers are known to be covered
  766. const depth = new THREE.Mesh(geometry, depthMaterial);
  767. depth.renderOrder = -1;
  768. // The inside of the body in a flat colour: where a section view
  769. // cuts the solid open, this is what shows, so the cut looks filled
  770. const capMesh = new THREE.Mesh(geometry, cap);
  771. bodyGroup.add(depth);
  772. bodyGroup.add(mesh);
  773. bodyGroup.add(capMesh);
  774. bodyGroup.add(hidden);
  775. bodyGroup.add(lines);
  776. // The outline of round faces as seen from where the camera is
  777. // (a hole's walls, a fillet): worked out again when the view
  778. // turns (updateSilhouettes), solid in front and dashed behind
  779. const sil = makeSilhouette(data);
  780. const body = { data: data, mesh: mesh, baseMaterial: material, depth: depth, lines: lines, hidden: hidden, cap: capMesh, sil: sil, matrix: null, group: data.group };
  781. if (data.matrix) {
  782. placeBody(body, data.matrix);
  783. }
  784. return body;
  785. });
  786. applyFaceLooks();
  787. applyGhost();
  788. groundDirty = true;
  789. applySection();
  790. // Face and edge numbers belong to the shape that was just replaced
  791. const hadSelection = selection.length > 0;
  792. hovered = null;
  793. selection = [];
  794. applyVisualStyle();
  795. drawOverlays();
  796. // Only speak up when something was actually deselected; a rebuild
  797. // must not wipe the message of the command that caused it
  798. if (hadSelection) {
  799. announceSelection();
  800. }
  801. }
  802. // A feature panel that is picking gets the selection instead of the app
  803. function announceSelection() {
  804. const items = selection.map(describeItem);
  805. if (api.onSelection) {
  806. api.onSelection(items);
  807. } else if (options.onSelect) {
  808. options.onSelect(items);
  809. }
  810. }
  811. // shaded: surfaces only; shaded with edges: and the edges in front;
  812. // hidden-edges: and the covered edges dashed; wireframe: no surfaces,
  813. // the edges in front solid and the covered ones dashed
  814. // Solid bodies the user hid (by number): not drawn, not picked
  815. let hiddenBodies = new Set();
  816. function applyVisualStyle() {
  817. const wire = visualStyle === 'wireframe';
  818. const dashed = wire || visualStyle === 'hidden-edges';
  819. // Without surfaces the lines stand on the background: light ones on
  820. // the dark theme's stage
  821. const light = wire && document.body.classList.contains('dark');
  822. const lineColor = light ? 0xd0d5dd : 0x20242b;
  823. edgeMaterial.color.setHex(lineColor);
  824. hiddenEdgeMaterial.color.setHex(lineColor);
  825. hiddenEdgeMaterial.opacity = light ? 0.45 : 0.6;
  826. bodyMaterial.visible = !wire;
  827. bodies.forEach(function (body, i) {
  828. body.off = hiddenBodies.has(i);
  829. body.mesh.visible = !body.off;
  830. [].concat(body.mesh.material).forEach(function (m) {
  831. m.visible = !wire;
  832. });
  833. // While a fillet or chamfer result is previewed, the result
  834. // stands for the body (its own depth, its own dashed edges)
  835. body.depth.visible = wire && !ghostOn && !body.off;
  836. body.lines.visible = visualStyle !== 'shaded' && !body.off;
  837. body.hidden.visible = dashed && !ghostOn && !body.off;
  838. // The inside drawn flat only when there are no hatched caps (no stencil buffer)
  839. body.cap.visible = section.mode !== 'none' && !wire && !body.off && !capParts.length;
  840. if (body.sil) {
  841. body.sil.front.visible = visualStyle !== 'shaded' && !body.off;
  842. body.sil.behind.visible = dashed && !ghostOn && !body.off;
  843. }
  844. });
  845. capParts.forEach(function (part) {
  846. const on = section.mode !== 'none' && !wire && !part.body.off;
  847. part.cap.visible = on;
  848. part.stencils.forEach(function (mesh) {
  849. mesh.visible = on;
  850. });
  851. });
  852. // A fillet or chamfer preview is drawn in the same style as the body
  853. previewGroup.children.forEach(function (child) {
  854. const role = child.userData.role;
  855. if (role === 'result-solid') {
  856. child.visible = !wire;
  857. } else if (role === 'result-depth') {
  858. child.visible = wire;
  859. } else if (role === 'result-lines') {
  860. child.visible = visualStyle !== 'shaded';
  861. child.material.color.setHex(lineColor);
  862. } else if (role === 'result-hidden') {
  863. child.visible = dashed;
  864. child.material.color.setHex(lineColor);
  865. child.material.opacity = hiddenEdgeMaterial.opacity;
  866. }
  867. });
  868. }
  869. /* ---------------- section view ---------------- */
  870. // The model is cut by planes parallel to the origin planes, on the
  871. // graphics card: the kernel is not involved, so it costs nothing and the
  872. // model stays whole.
  873. // half what lies in front of the plane is removed
  874. // quarter one quarter is left standing
  875. // threequarter one quarter is removed
  876. // "In front" is the side the home view looks from (-Y, +X, +Z); flip
  877. // keeps that side instead.
  878. const SECTION_AXES = { xz: 1, yz: 0, xy: 2 };
  879. const SECTION_KEEP = { xz: [0, 1, 0], yz: [-1, 0, 0], xy: [0, 0, -1] };
  880. // The bounding box of what is shown, as [min, max] arrays, or null
  881. function modelBounds() {
  882. if (!bodies.length) {
  883. return null;
  884. }
  885. const box = new THREE.Box3().setFromObject(bodyGroup);
  886. return box.isEmpty() ? null : [box.min.toArray(), box.max.toArray()];
  887. }
  888. // Where a plane sits on its axis: the offset, else the middle of the model
  889. function sectionAt(key, offset, bounds) {
  890. const axis = SECTION_AXES[key];
  891. return offset === null || offset === undefined || !isFinite(offset) ? (bounds ? (bounds[0][axis] + bounds[1][axis]) / 2 : 0) : offset;
  892. }
  893. function sectionPlane(key, offset, flip) {
  894. const axis = SECTION_AXES[key];
  895. const at = sectionAt(key, offset, modelBounds());
  896. const normal = new THREE.Vector3().fromArray(SECTION_KEEP[key]);
  897. if (flip) {
  898. normal.negate();
  899. }
  900. // n . p + c = 0 on the plane, with the point (at on the axis)
  901. const point = new THREE.Vector3();
  902. point.setComponent(axis, at);
  903. return new THREE.Plane(normal, -normal.dot(point));
  904. }
  905. function applySection() {
  906. const planes = [];
  907. if (section.mode !== 'none' && bodies.length) {
  908. planes.push(sectionPlane(section.plane, section.offset, section.flip));
  909. if (section.mode !== 'half') {
  910. planes.push(sectionPlane(section.plane2, section.offset2, section.flip2));
  911. }
  912. }
  913. sectionPlanes = planes;
  914. bodyMaterials().forEach(function (material) {
  915. material.clippingPlanes = planes;
  916. // With "intersection" only what fails every plane is removed: one quarter
  917. material.clipIntersection = section.mode === 'threequarter';
  918. material.needsUpdate = true;
  919. });
  920. syncCaps(planes);
  921. applyVisualStyle();
  922. placeSectionHandles();
  923. invalidate();
  924. }
  925. /* ---------------- section caps ---------------- */
  926. // A cut face is drawn as a real face on the cutting plane, hatched, as
  927. // a section drawing shows it, instead of the inside of the body showing
  928. // through (body.cap, the inside drawn flat, only stands in when there is
  929. // no stencil buffer: shown with the caps, a thin wall seen at a grazing
  930. // angle lets it through the front face in specks). For each plane and body: the body clipped by that plane
  931. // alone goes into the stencil buffer only (back faces add one, front
  932. // faces take one away), which leaves non-zero exactly where the plane
  933. // runs through solid material; then a sheet on the plane is drawn
  934. // there, cut by the other plane (Quarter keeps the part inside it,
  935. // Three Quarter the part outside), and the stencil is cleared again.
  936. function syncCaps(planes) {
  937. const key = planes.length ? section.mode + ':' + planes.length + ':' + bodiesVersion : '';
  938. if (key !== capKey) {
  939. buildCaps(planes.length);
  940. capKey = key;
  941. }
  942. planes.forEach(function (plane, k) {
  943. capPlanes[k].copy(plane);
  944. capOutside[k].copy(plane).negate();
  945. });
  946. placeCaps();
  947. }
  948. function clearCaps() {
  949. capParts.forEach(function (part) {
  950. part.stencils.forEach(function (mesh) {
  951. mesh.removeFromParent();
  952. mesh.material.dispose();
  953. });
  954. part.cap.removeFromParent();
  955. part.cap.geometry.dispose();
  956. part.cap.material.dispose();
  957. });
  958. capParts = [];
  959. }
  960. function buildCaps(count) {
  961. clearCaps();
  962. // Without a stencil buffer body.cap (the inside drawn flat) stands in
  963. const attributes = renderer.getContext().getContextAttributes();
  964. if (!count || !attributes || !attributes.stencil) {
  965. return;
  966. }
  967. if (!capGroup) {
  968. capGroup = new THREE.Group();
  969. scene.add(capGroup);
  970. hatch = hatchTexture();
  971. }
  972. let order = 10; // after the bodies; each body's stencil passes, then its sheet
  973. for (let k = 0; k < count; k++) {
  974. const others = count < 2 ? [] : [section.mode === 'threequarter' ? capOutside[1 - k] : capPlanes[1 - k]];
  975. bodies.forEach(function (body) {
  976. // Children of the body's mesh: they follow its placement and hide with it
  977. const stencils = [[THREE.BackSide, THREE.IncrementWrapStencilOp], [THREE.FrontSide, THREE.DecrementWrapStencilOp]].map(function (pass) {
  978. const mesh = new THREE.Mesh(body.mesh.geometry, new THREE.MeshBasicMaterial({
  979. side: pass[0], colorWrite: false, depthWrite: false, depthTest: false, clippingPlanes: [capPlanes[k]],
  980. stencilWrite: true, stencilFunc: THREE.AlwaysStencilFunc,
  981. stencilFail: pass[1], stencilZFail: pass[1], stencilZPass: pass[1]
  982. }));
  983. mesh.renderOrder = order;
  984. body.mesh.add(mesh);
  985. return mesh;
  986. });
  987. const geometry = new THREE.BufferGeometry();
  988. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(12), 3));
  989. geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(8), 2));
  990. geometry.setIndex([0, 1, 2, 0, 2, 3]);
  991. const cap = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
  992. // the body's cut colour (a component's own shade) under the hatching
  993. color: body.cap.material.color.clone(), map: hatch, side: THREE.DoubleSide, clippingPlanes: others,
  994. stencilWrite: true, stencilRef: 0, stencilFunc: THREE.NotEqualStencilFunc,
  995. stencilFail: THREE.ReplaceStencilOp, stencilZFail: THREE.ReplaceStencilOp, stencilZPass: THREE.ReplaceStencilOp
  996. }));
  997. cap.renderOrder = order + 1;
  998. // Fragments the other plane cuts away leave their stencil behind: clear it all
  999. cap.onAfterRender = function (r) {
  1000. r.clearStencil();
  1001. };
  1002. capGroup.add(cap);
  1003. capParts.push({ body: body, plane: k, stencils: stencils, cap: cap });
  1004. order += 2;
  1005. });
  1006. }
  1007. }
  1008. // Every cap sheet over the model's extent on its plane. The hatching is
  1009. // fixed to the plane, one stripe every CAP_STRIPE_PIXELS on screen at
  1010. // the zoom it was placed for (render() places it again when the zoom
  1011. // changes), so even a thin wall shows a few stripes
  1012. const CAP_STRIPE_PIXELS = 10;
  1013. let capZoom = 0; // world per pixel the hatching was placed for
  1014. function placeCaps() {
  1015. const bounds = capParts.length ? modelBounds() : null;
  1016. if (!bounds) {
  1017. return;
  1018. }
  1019. const size = Math.max(bounds[1][0] - bounds[0][0], bounds[1][1] - bounds[0][1], bounds[1][2] - bounds[0][2], 1);
  1020. const pad = size * 0.05 + 1;
  1021. capZoom = worldPerPixel();
  1022. const tile = Math.max(capZoom * CAP_STRIPE_PIXELS, 1e-4);
  1023. capParts.forEach(function (part) {
  1024. const plane = capPlanes[part.plane];
  1025. const axis = Math.abs(plane.normal.x) > 0.5 ? 0 : Math.abs(plane.normal.y) > 0.5 ? 1 : 2;
  1026. const at = -plane.constant / plane.normal.getComponent(axis);
  1027. const u = (axis + 1) % 3;
  1028. const v = (axis + 2) % 3;
  1029. const positions = part.cap.geometry.getAttribute('position');
  1030. const uvs = part.cap.geometry.getAttribute('uv');
  1031. [[0, 0], [1, 0], [1, 1], [0, 1]].forEach(function (corner, i) {
  1032. const p = [0, 0, 0];
  1033. p[axis] = at;
  1034. p[u] = corner[0] ? bounds[1][u] + pad : bounds[0][u] - pad;
  1035. p[v] = corner[1] ? bounds[1][v] + pad : bounds[0][v] - pad;
  1036. positions.setXYZ(i, p[0], p[1], p[2]);
  1037. uvs.setXY(i, p[u] / tile, p[v] / tile);
  1038. });
  1039. positions.needsUpdate = true;
  1040. uvs.needsUpdate = true;
  1041. part.cap.geometry.computeBoundingSphere();
  1042. });
  1043. }
  1044. // Diagonal stripes on white, one per tile: the map multiplies the cap's
  1045. // colour, so the ground keeps it and the stripes are a darker shade
  1046. function hatchTexture() {
  1047. const n = 64;
  1048. const stripe = 14;
  1049. const c = document.createElement('canvas');
  1050. c.width = n;
  1051. c.height = n;
  1052. const g = c.getContext('2d');
  1053. const image = g.createImageData(n, n);
  1054. for (let y = 0; y < n; y++) {
  1055. for (let x = 0; x < n; x++) {
  1056. // Distance into the stripe along the diagonal, softened at its edges
  1057. const d = (x + y + 1) % n;
  1058. const cover = Math.max(0, Math.min(1, Math.min(d, stripe - d) + 0.5));
  1059. const value = Math.round(255 - cover * 95);
  1060. const i = (y * n + x) * 4;
  1061. image.data[i] = value;
  1062. image.data[i + 1] = value;
  1063. image.data[i + 2] = value;
  1064. image.data[i + 3] = 255;
  1065. }
  1066. }
  1067. g.putImageData(image, 0, 0);
  1068. const texture = new THREE.CanvasTexture(c);
  1069. texture.wrapS = THREE.RepeatWrapping;
  1070. texture.wrapT = THREE.RepeatWrapping;
  1071. texture.colorSpace = THREE.SRGBColorSpace;
  1072. texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
  1073. return texture;
  1074. }
  1075. // mode: "none" | "half" | "quarter" | "threequarter", or a whole spec
  1076. // (see `section` above); missing fields keep their value
  1077. function setSection(spec) {
  1078. section = Object.assign({}, section, typeof spec === 'string' ? { mode: spec } : spec);
  1079. if (section.plane2 === section.plane) {
  1080. section.plane2 = section.plane === 'yz' ? 'xz' : 'yz';
  1081. }
  1082. setHovered(null);
  1083. applySection();
  1084. }
  1085. // Is a point in the part of the model a section view has cut away?
  1086. function cutAway(point) {
  1087. if (!sectionPlanes.length) {
  1088. return false;
  1089. }
  1090. const outside = sectionPlanes.filter(function (plane) {
  1091. return plane.distanceToPoint(point) < 0;
  1092. }).length;
  1093. return section.mode === 'threequarter' ? outside === sectionPlanes.length : outside > 0;
  1094. }
  1095. function setVisualStyle(style) {
  1096. visualStyle = style;
  1097. silhouetteKey = '';
  1098. applyVisualStyle();
  1099. invalidate();
  1100. }
  1101. // What a hovered or selected item is, for the status bar and for commands
  1102. function describeItem(item) {
  1103. const body = bodies[item.body];
  1104. const data = body && body.data;
  1105. if (!data) {
  1106. return null;
  1107. }
  1108. if (item.type === 'body') {
  1109. return { kind: 'component', body: item.body, group: body.group };
  1110. }
  1111. const info = item.type === 'face' ? data.faces[item.index] : data.edges[item.index];
  1112. if (!info) {
  1113. return null;
  1114. }
  1115. const base = { kind: item.type, body: item.body, index: item.index, group: body.group };
  1116. // A placed body (assembly) reports where the item is in the assembly
  1117. return body.matrix ? Object.assign(base, transformInfo(info, body.matrix), { local: info }) : Object.assign(base, info);
  1118. }
  1119. // A small geometry of its own for one face or edge, so highlights can be
  1120. // thrown away without touching the buffers of the body. Returns a list
  1121. // of objects to draw (an edge: in front of the model, and faint behind).
  1122. function overlayFor(item, state) {
  1123. const body = bodies[item.body];
  1124. const info = body && (item.type === 'face' ? body.data.faces[item.index] : item.type === 'edge' ? body.data.edges[item.index] : null);
  1125. if (!info) {
  1126. return null;
  1127. }
  1128. const made = overlayShapes(body, info, item, state);
  1129. if (body.matrix) {
  1130. made.forEach(function (object) {
  1131. object.position.copy(body.mesh.position);
  1132. object.quaternion.copy(body.mesh.quaternion);
  1133. object.scale.copy(body.mesh.scale);
  1134. });
  1135. }
  1136. return made;
  1137. }
  1138. function overlayShapes(body, info, item, state) {
  1139. if (item.type === 'face') {
  1140. const geometry = new THREE.BufferGeometry();
  1141. const out = new Float32Array(info.count * 3);
  1142. for (let i = 0; i < info.count; i++) {
  1143. const v = body.data.indices[info.start + i] * 3;
  1144. out[i * 3] = body.data.positions[v];
  1145. out[i * 3 + 1] = body.data.positions[v + 1];
  1146. out[i * 3 + 2] = body.data.positions[v + 2];
  1147. }
  1148. geometry.setAttribute('position', new THREE.BufferAttribute(out, 3));
  1149. return [new THREE.Mesh(geometry, overlayMaterials[state + 'face'])];
  1150. }
  1151. const geometry = new LineSegmentsGeometry();
  1152. geometry.setPositions(body.data.edgePositions.slice(info.start * 3, (info.start + info.count) * 3));
  1153. const hidden = new LineSegments2(geometry, overlayMaterials[state + 'edgehidden']);
  1154. const line = new LineSegments2(geometry, overlayMaterials[state + 'edge']);
  1155. hidden.renderOrder = 5; // after a fillet or chamfer preview, so it is tested against it
  1156. line.renderOrder = 6;
  1157. return [hidden, line];
  1158. }
  1159. function same(a, b) {
  1160. if (!a || !b || a.type !== b.type) {
  1161. return false;
  1162. }
  1163. // Whole components are the same when they are one group
  1164. if (a.type === 'body') {
  1165. return groupOf(a.body) === groupOf(b.body);
  1166. }
  1167. return a.body === b.body && a.index === b.index;
  1168. }
  1169. function groupOf(index) {
  1170. const body = bodies[index];
  1171. return body ? (body.group === undefined ? index : body.group) : null;
  1172. }
  1173. // Tint every body of the hovered and selected components (component
  1174. // mode) and the groups asked for with setGroupTint
  1175. let groupTints = {}; // group -> "hover" | "selected"
  1176. function applyTints() {
  1177. const tint = {};
  1178. Object.keys(groupTints).forEach(function (g) {
  1179. tint[g] = groupTints[g];
  1180. });
  1181. selection.forEach(function (item) {
  1182. if (item.type === 'body') {
  1183. tint[groupOf(item.body)] = 'selected';
  1184. }
  1185. });
  1186. if (hovered && hovered.type === 'body' && tint[groupOf(hovered.body)] !== 'selected') {
  1187. tint[groupOf(hovered.body)] = 'hover';
  1188. }
  1189. bodies.forEach(function (body, i) {
  1190. const state = tint[groupOf(i)];
  1191. [].concat(body.mesh.material).forEach(function (material) {
  1192. if (!material.emissive || material === bodyMaterial) {
  1193. return;
  1194. }
  1195. material.emissive.setHex(state === 'selected' ? SELECTED : state === 'hover' ? HOVER : 0x000000);
  1196. material.emissiveIntensity = state === 'selected' ? 0.45 : state === 'hover' ? 0.35 : 0;
  1197. });
  1198. });
  1199. }
  1200. // What picking an item takes along. While Fillet or Chamfer picks, an
  1201. // edge stands for its whole tangent chain (pickFilter.chains, one chain
  1202. // number per edge and body, from the kernel), because that is what the
  1203. // feature rounds; otherwise just the item.
  1204. function chainOf(item) {
  1205. const chains = item && item.type === 'edge' && pickFilter && pickFilter.chains;
  1206. const list = chains && chains[item.body];
  1207. if (!list || !(list[item.index] >= 0)) {
  1208. return item ? [item] : [];
  1209. }
  1210. const out = [];
  1211. list.forEach(function (id, index) {
  1212. if (id === list[item.index]) {
  1213. out.push({ type: 'edge', body: item.body, index: index });
  1214. }
  1215. });
  1216. return out;
  1217. }
  1218. function sameChain(a, b) {
  1219. return chainOf(a).some(function (member) {
  1220. return same(member, b);
  1221. });
  1222. }
  1223. // How many edges the selection covers, tangent chains included
  1224. function coveredEdges() {
  1225. const seen = {};
  1226. selection.forEach(function (item) {
  1227. chainOf(item).forEach(function (member) {
  1228. if (member.type === 'edge') {
  1229. seen[member.body + ':' + member.index] = true;
  1230. }
  1231. });
  1232. });
  1233. return Object.keys(seen).length;
  1234. }
  1235. function drawOverlays() {
  1236. disposeGroup(overlayGroup);
  1237. const add = function (item, state) {
  1238. chainOf(item).forEach(function (member) {
  1239. (overlayFor(member, state) || []).forEach(function (o) {
  1240. overlayGroup.add(o);
  1241. });
  1242. });
  1243. };
  1244. selection.forEach(function (item) {
  1245. add(item, 'selected');
  1246. });
  1247. if (hovered && !selection.some(function (item) {
  1248. return sameChain(item, hovered);
  1249. })) {
  1250. add(hovered, 'hover');
  1251. }
  1252. applyTints();
  1253. invalidate();
  1254. }
  1255. // The cursor when the pointer is over nothing in particular: what a left
  1256. // drag would do
  1257. function restCursor() {
  1258. return leftDrag === 'pan' ? 'move' : leftDrag === 'orbit' ? RING_CURSORS[ringHover] : '';
  1259. }
  1260. function setHovered(item) {
  1261. if (same(item, hovered) || (!item && !hovered)) {
  1262. return;
  1263. }
  1264. hovered = item;
  1265. if (!planeHandler && !sketching) {
  1266. // Something that can be picked shows the selection arrow, even
  1267. // while Orbit or Pan has the left button
  1268. canvas.style.cursor = item ? 'default' : restCursor();
  1269. }
  1270. drawOverlays();
  1271. if (options.onHover) {
  1272. options.onHover(item ? describeItem(item) : null);
  1273. }
  1274. }
  1275. function setSelection(list) {
  1276. selection = list;
  1277. drawOverlays();
  1278. announceSelection();
  1279. }
  1280. // The item if the active pick filter lets it through, else null
  1281. function allowed(item) {
  1282. if (!item || !pickFilter) {
  1283. return item;
  1284. }
  1285. return (item.type === 'edge' && pickFilter.edges) || (item.type === 'face' && pickFilter.faces) ||
  1286. (item.type === 'body' && pickFilter.components) ? item : null;
  1287. }
  1288. // Select the edges a feature remembers ([{ body, mid, length }]).
  1289. // Returns how many of them were found in the model as shown.
  1290. function selectEdges(refs) {
  1291. const found = [];
  1292. (refs || []).forEach(function (ref) {
  1293. bodies.forEach(function (body, b) {
  1294. if (ref.body !== undefined && ref.body !== b) {
  1295. return;
  1296. }
  1297. body.data.edges.forEach(function (edge, i) {
  1298. const hit = edge.mid && Math.hypot(edge.mid[0] - ref.mid[0], edge.mid[1] - ref.mid[1], edge.mid[2] - ref.mid[2]) < 1e-3 &&
  1299. Math.abs(edge.length - ref.length) < 1e-3;
  1300. if (hit && !found.some(function (f) {
  1301. return f.body === b && f.index === i;
  1302. })) {
  1303. found.push({ type: 'edge', body: b, index: i });
  1304. }
  1305. });
  1306. });
  1307. });
  1308. setSelection(found);
  1309. return found.length;
  1310. }
  1311. // Select the faces a feature remembers ([{ body, centre, area }]).
  1312. // Returns how many of them were found in the model as shown.
  1313. function selectFaces(refs) {
  1314. const found = [];
  1315. (refs || []).forEach(function (ref) {
  1316. bodies.forEach(function (body, b) {
  1317. if (ref.body !== undefined && ref.body !== b) {
  1318. return;
  1319. }
  1320. body.data.faces.forEach(function (face, i) {
  1321. const hit = face.centre && Math.hypot(face.centre[0] - ref.centre[0], face.centre[1] - ref.centre[1], face.centre[2] - ref.centre[2]) < 1e-3 &&
  1322. Math.abs(face.area - ref.area) < Math.max(1e-3, ref.area * 1e-6);
  1323. if (hit && !found.some(function (f) {
  1324. return f.body === b && f.index === i;
  1325. })) {
  1326. found.push({ type: 'face', body: b, index: i });
  1327. }
  1328. });
  1329. });
  1330. });
  1331. setSelection(found);
  1332. return found.length;
  1333. }
  1334. /* ---------------- camera helpers ---------------- */
  1335. function resize() {
  1336. const w = Math.max(stage.clientWidth, 1);
  1337. const h = Math.max(stage.clientHeight, 1);
  1338. renderer.setSize(w, h, false);
  1339. ['hoveredge', 'hoveredgehidden', 'selectededge', 'selectededgehidden'].forEach(function (key) {
  1340. overlayMaterials[key].resolution.set(w, h);
  1341. });
  1342. Object.keys(axisMaterials).forEach(function (key) {
  1343. axisMaterials[key].resolution.set(w, h);
  1344. });
  1345. const aspect = w / h;
  1346. ortho.left = -viewHeight * aspect / 2;
  1347. ortho.right = viewHeight * aspect / 2;
  1348. ortho.top = viewHeight / 2;
  1349. ortho.bottom = -viewHeight / 2;
  1350. ortho.updateProjectionMatrix();
  1351. persp.aspect = aspect;
  1352. persp.updateProjectionMatrix();
  1353. invalidate();
  1354. }
  1355. function setProjection(mode) {
  1356. const next = mode === 'perspective' ? persp : ortho;
  1357. if (next === camera) {
  1358. return;
  1359. }
  1360. // Keep the same view direction and roughly the same apparent size
  1361. const offset = camera.position.clone().sub(controls.target);
  1362. const visible = camera === ortho ? viewHeight / ortho.zoom
  1363. : 2 * offset.length() * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2));
  1364. const direction = offset.normalize();
  1365. if (next === persp) {
  1366. const distance = visible / (2 * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)));
  1367. persp.position.copy(controls.target).addScaledVector(direction, distance);
  1368. } else {
  1369. ortho.zoom = viewHeight / visible;
  1370. ortho.position.copy(controls.target).addScaledVector(direction, 600);
  1371. ortho.updateProjectionMatrix();
  1372. }
  1373. next.up.copy(camera.up);
  1374. next.lookAt(controls.target);
  1375. camera = next;
  1376. controls.object = camera;
  1377. gizmo.camera = camera;
  1378. controls.update();
  1379. invalidate();
  1380. }
  1381. function contentBox() {
  1382. const box = new THREE.Box3();
  1383. if (bodyGroup.children.length) {
  1384. box.setFromObject(bodyGroup);
  1385. }
  1386. if (box.isEmpty()) {
  1387. const half = PLANE_SIZE / 2;
  1388. box.set(new THREE.Vector3(-half, -half, -half), new THREE.Vector3(half, half, half));
  1389. }
  1390. return box;
  1391. }
  1392. let animation = null;
  1393. // Fly the camera so it looks along -normal with `up` at the top of the screen.
  1394. // fit = true also centres and zooms on the content.
  1395. function flyTo(normal, up, fit) {
  1396. noteView();
  1397. const box = contentBox();
  1398. const sphere = box.getBoundingSphere(new THREE.Sphere());
  1399. const endTarget = fit ? sphere.center.clone() : controls.target.clone();
  1400. const n = new THREE.Vector3().fromArray(normal).normalize();
  1401. const u = new THREE.Vector3().fromArray(up).normalize();
  1402. const m = new THREE.Matrix4().lookAt(n, new THREE.Vector3(), u);
  1403. const endQuat = new THREE.Quaternion().setFromRotationMatrix(m);
  1404. const distance = camera.position.distanceTo(controls.target);
  1405. let endZoom = ortho.zoom;
  1406. let endDistance = distance;
  1407. if (fit) {
  1408. const size = Math.max(sphere.radius * 2.3, 1);
  1409. endZoom = viewHeight / size;
  1410. endDistance = camera === persp
  1411. ? size / (2 * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)))
  1412. : 600;
  1413. }
  1414. animation = {
  1415. started: performance.now(),
  1416. duration: 380,
  1417. startQuat: camera.quaternion.clone(),
  1418. endQuat: endQuat,
  1419. startTarget: controls.target.clone(),
  1420. endTarget: endTarget,
  1421. startZoom: ortho.zoom,
  1422. endZoom: endZoom,
  1423. startDistance: distance,
  1424. endDistance: endDistance
  1425. };
  1426. controls.enabled = false;
  1427. invalidate();
  1428. }
  1429. function stepAnimation(now) {
  1430. const a = animation;
  1431. let t = Math.min((now - a.started) / a.duration, 1);
  1432. t = t * t * (3 - 2 * t);
  1433. const q = a.startQuat.clone().slerp(a.endQuat, t);
  1434. const tgt = a.startTarget.clone().lerp(a.endTarget, t);
  1435. const distance = THREE.MathUtils.lerp(a.startDistance, a.endDistance, t);
  1436. camera.position.copy(tgt).add(new THREE.Vector3(0, 0, 1).applyQuaternion(q).multiplyScalar(distance));
  1437. camera.up.copy(new THREE.Vector3(0, 1, 0).applyQuaternion(q));
  1438. camera.lookAt(tgt);
  1439. controls.target.copy(tgt);
  1440. if (camera === ortho) {
  1441. ortho.zoom = THREE.MathUtils.lerp(a.startZoom, a.endZoom, t);
  1442. ortho.updateProjectionMatrix();
  1443. }
  1444. if (t >= 1) {
  1445. animation = null;
  1446. controls.enabled = true;
  1447. }
  1448. }
  1449. // Orbit, pan or zoom starts. camera.up is set to the screen's up as it
  1450. // is, so OrbitControls keeps the view as it is (rolled, upside down)
  1451. // instead of standing world Z up again.
  1452. controls.addEventListener('start', function () {
  1453. noteView();
  1454. camera.up.copy(screenAxis(0, 1, 0));
  1455. });
  1456. // Where the camera is ({ projection, position, up, target, zoom })
  1457. function currentView() {
  1458. return {
  1459. projection: camera === persp ? 'perspective' : 'orthographic',
  1460. position: camera.position.toArray(), up: camera.up.toArray(),
  1461. target: controls.target.toArray(), zoom: ortho.zoom
  1462. };
  1463. }
  1464. // Before the view changes (orbit, pan, zoom, a view cube click, Home,
  1465. // Zoom All, Look At) api.onViewChange gets the view as it was, for F5
  1466. // Previous View. Steps closer than 0.6 s (a turn of the wheel) count once.
  1467. let viewNoted = 0;
  1468. function noteView() {
  1469. const now = Date.now();
  1470. if (api.onViewChange && now - viewNoted > 600) {
  1471. api.onViewChange(currentView());
  1472. }
  1473. viewNoted = now;
  1474. }
  1475. function home() {
  1476. // "up" for an isometric view is world Z projected on the view plane; lookAt sorts that out
  1477. flyTo(HOME_DIRECTION.toArray(), WORLD_UP.toArray(), true);
  1478. }
  1479. function zoomAll() {
  1480. const direction = camera.position.clone().sub(controls.target).normalize();
  1481. flyTo(direction.toArray(), camera.up.toArray(), true);
  1482. }
  1483. function lookAtPlane(key) {
  1484. const def = ORIGIN_PLANES[key];
  1485. flyTo(def.normal, def.up, true);
  1486. }
  1487. /* ---------------- picking ---------------- */
  1488. const raycaster = new THREE.Raycaster();
  1489. const pointer = new THREE.Vector2();
  1490. const EDGE_PIXELS = 6;
  1491. let lastFaceDistance = Infinity; // how far the last face under the pointer was
  1492. let lastFacePoint = null; // and where on it the pointer was
  1493. let planeHandler = null; // set while a command waits for a plane or a planar face
  1494. let planeDragHandler = null; // and, optionally, what dragging away from one does
  1495. let planeDrag = null; // { pick, frame, x, y, screen, active, offset } while pressed on a plane
  1496. let hotPlane = null;
  1497. let originPinned = false;
  1498. let downAt = null;
  1499. function setHotPlane(key) {
  1500. if (key === hotPlane) {
  1501. return;
  1502. }
  1503. hotPlane = key;
  1504. Object.keys(planeMeshes).forEach(function (k) {
  1505. planeMeshes[k].material.opacity = k === key ? 0.5 : 0.22;
  1506. });
  1507. if (options.onHoverPlane) {
  1508. options.onHoverPlane(key);
  1509. }
  1510. invalidate();
  1511. }
  1512. // World millimetres covered by one screen pixel at the orbit centre
  1513. function worldPerPixel() {
  1514. const height = Math.max(stage.clientHeight, 1);
  1515. if (camera === ortho) {
  1516. return viewHeight / ortho.zoom / height;
  1517. }
  1518. const distance = camera.position.distanceTo(controls.target);
  1519. return 2 * distance * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)) / height;
  1520. }
  1521. function aim(event) {
  1522. const rect = canvas.getBoundingClientRect();
  1523. pointer.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);
  1524. raycaster.setFromCamera(pointer, camera);
  1525. }
  1526. // The range that owns `position` in a list of { start, count } sorted by start
  1527. function ownerOf(ranges, position) {
  1528. let low = 0;
  1529. let high = ranges.length - 1;
  1530. while (low <= high) {
  1531. const mid = (low + high) >> 1;
  1532. if (position < ranges[mid].start) {
  1533. high = mid - 1;
  1534. } else if (position >= ranges[mid].start + ranges[mid].count) {
  1535. low = mid + 1;
  1536. } else {
  1537. return mid;
  1538. }
  1539. }
  1540. return -1;
  1541. }
  1542. // The face or edge under the pointer. An edge wins over the face behind it
  1543. // when the pointer is within a few pixels of it.
  1544. function itemUnderPointer(event, wantEdges) {
  1545. aim(event);
  1546. const tolerance = EDGE_PIXELS * worldPerPixel();
  1547. const faceHit = raycaster.intersectObjects(bodies.filter(function (b) {
  1548. return !b.off;
  1549. }).map(function (b) {
  1550. return b.mesh;
  1551. }), false).filter(function (hit) {
  1552. return !cutAway(hit.point);
  1553. })[0];
  1554. let result = null;
  1555. lastFaceDistance = faceHit ? faceHit.distance : Infinity;
  1556. lastFacePoint = faceHit ? faceHit.point.toArray() : null;
  1557. if (faceHit) {
  1558. const body = faceHit.object.userData.body;
  1559. const index = ownerOf(bodies[body].data.faces, faceHit.faceIndex * 3);
  1560. if (index >= 0) {
  1561. result = { type: 'face', body: body, index: index };
  1562. }
  1563. }
  1564. if (componentMode) {
  1565. // Whole components: the body under the pointer stands for its group
  1566. return result ? { type: 'body', body: result.body } : null;
  1567. }
  1568. if (wantEdges && (visualStyle !== 'shaded' || wantEdges === 'always')) {
  1569. const lines = bodies.filter(function (b) {
  1570. return !b.off;
  1571. }).map(function (b) {
  1572. return b.lines;
  1573. });
  1574. const edgeNear = function (threshold, limit) {
  1575. raycaster.params.Line.threshold = threshold;
  1576. return raycaster.intersectObjects(lines, false).filter(function (hit) {
  1577. return hit.distance <= limit && !cutAway(hit.point);
  1578. })[0];
  1579. };
  1580. // A visible edge first (in front of the face under the pointer)
  1581. let edgeHit = edgeNear(tolerance, faceHit ? faceHit.distance + tolerance * 2 : Infinity);
  1582. // Wireframe and "hidden edges" draw the edges behind the faces
  1583. // too: such an edge can be picked where it is drawn, when the
  1584. // pointer is right on it (half the tolerance), so the faces in
  1585. // front stay easy to pick everywhere else
  1586. if (!edgeHit && (visualStyle === 'wireframe' || visualStyle === 'hidden-edges')) {
  1587. edgeHit = edgeNear(tolerance * 0.5, Infinity);
  1588. }
  1589. if (edgeHit) {
  1590. const body = edgeHit.object.userData.body;
  1591. const index = ownerOf(bodies[body].data.edges, edgeHit.index);
  1592. if (index >= 0) {
  1593. result = { type: 'edge', body: body, index: index };
  1594. }
  1595. }
  1596. }
  1597. return result;
  1598. }
  1599. function planeUnderPointer(event) {
  1600. if (!originGroup.visible) {
  1601. return null;
  1602. }
  1603. aim(event);
  1604. const hits = raycaster.intersectObjects(Object.values(planeMeshes), false);
  1605. return hits.length ? hits[0].object.userData.plane : null;
  1606. }
  1607. // What a plane pick would return here: a planar face of a body first,
  1608. // then an origin plane when those are shown
  1609. function planeTargetUnderPointer(event) {
  1610. const item = itemUnderPointer(event, false);
  1611. // A work plane in front of the model wins over the face behind it
  1612. const sheet = raycaster.intersectObjects(workGroup.children, false).filter(function (hit) {
  1613. return hit.object.userData.work;
  1614. })[0];
  1615. if (sheet && (!item || sheet.distance < lastFaceDistance)) {
  1616. return { kind: 'work', id: sheet.object.userData.work };
  1617. }
  1618. if (item) {
  1619. const info = describeItem(item);
  1620. return info.type === 'plane' ? { kind: 'face', item: item, info: info } : null;
  1621. }
  1622. const key = planeUnderPointer(event);
  1623. return key ? { kind: 'origin', key: key } : null;
  1624. }
  1625. // What a plane pick hands over for a target under the pointer
  1626. function pickOf(target) {
  1627. return target.kind === 'origin' ? { kind: 'origin', key: target.key }
  1628. : target.kind === 'work' ? { kind: 'work', id: target.id }
  1629. : { kind: 'face', body: target.item.body, face: target.item.index, origin: target.info.origin, normal: target.info.normal, point: lastFacePoint, name: target.info.name || null };
  1630. }
  1631. // Pressed on a plane while a plane is wanted: a drag pulls out an
  1632. // offset plane (planedrag.js); a click still picks the plane
  1633. function startPlaneDrag(event) {
  1634. const target = planeTargetUnderPointer(event);
  1635. const pick = target ? pickOf(target) : null;
  1636. const frame = pick ? planeDragHandler.frameOf(pick) : null;
  1637. if (!frame) {
  1638. return;
  1639. }
  1640. // Where the press meets the plane, and how the normal shows on screen
  1641. aim(event);
  1642. const n = new THREE.Vector3().fromArray(frame.n);
  1643. const hit = raycaster.ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint(n, new THREE.Vector3().fromArray(frame.o)), new THREE.Vector3());
  1644. const at = hit ? hit.toArray() : frame.o;
  1645. const a = project(at);
  1646. const b = project([at[0] + frame.n[0], at[1] + frame.n[1], at[2] + frame.n[2]]);
  1647. const rect = canvas.getBoundingClientRect();
  1648. planeDrag = {
  1649. pick: pick, frame: frame, x: event.clientX - rect.left, y: event.clientY - rect.top,
  1650. screen: [b[0] - a[0], b[1] - a[1]], active: false, offset: 0
  1651. };
  1652. try {
  1653. canvas.setPointerCapture(event.pointerId);
  1654. } catch (e) {
  1655. // A synthetic event has no pointer to capture
  1656. }
  1657. }
  1658. canvas.addEventListener('pointermove', function (event) {
  1659. if (refPick && !event.buttons && !animation) {
  1660. showRefHot(refUnderPointer(event));
  1661. return;
  1662. }
  1663. if (planeDrag && (event.buttons & 1)) {
  1664. const rect = canvas.getBoundingClientRect();
  1665. const now = [event.clientX - rect.left, event.clientY - rect.top];
  1666. if (!planeDrag.active && Math.hypot(now[0] - planeDrag.x, now[1] - planeDrag.y) > 5) {
  1667. planeDrag.active = true;
  1668. setHovered(null);
  1669. }
  1670. if (planeDrag.active) {
  1671. const wpp = worldPerPixel();
  1672. planeDrag.offset = snapOffset(dragOffset([planeDrag.x, planeDrag.y], now, planeDrag.screen, wpp), wpp);
  1673. planeDragHandler.move(planeDrag.pick, planeDrag.offset, now);
  1674. }
  1675. return;
  1676. }
  1677. if (event.buttons || animation || (!interactive && !planeHandler)) {
  1678. return;
  1679. }
  1680. if (sectionHot) {
  1681. setHovered(null); // the pointer is on a section plane's sheet or arrow
  1682. return;
  1683. }
  1684. if (gizmoActive && gizmo.axis !== null) {
  1685. setHovered(null); // the pointer is on the triad
  1686. return;
  1687. }
  1688. if (planeHandler) {
  1689. const target = planeTargetUnderPointer(event);
  1690. setHovered(target && target.kind === 'face' ? target.item : null);
  1691. setHotPlane(target && target.kind === 'origin' ? target.key : null);
  1692. setHotWork(target && target.kind === 'work' ? target.id : null);
  1693. return;
  1694. }
  1695. setHovered(allowed(itemUnderPointer(event, true)));
  1696. });
  1697. canvas.addEventListener('pointerleave', function () {
  1698. setHovered(null);
  1699. setHotPlane(null);
  1700. });
  1701. canvas.addEventListener('pointerdown', function (event) {
  1702. downAt = [event.clientX, event.clientY];
  1703. planeDrag = null;
  1704. if (planeHandler && planeDragHandler && event.button === 0 && leftDrag === 'select') {
  1705. startPlaneDrag(event);
  1706. }
  1707. // A press on the triad drags it; it must not also pick what is behind
  1708. gizmoGrab = gizmoActive && gizmo.axis !== null;
  1709. });
  1710. canvas.addEventListener('pointerup', function (event) {
  1711. // A click, not the end of an orbit drag
  1712. const moved = downAt ? Math.hypot(event.clientX - downAt[0], event.clientY - downAt[1]) : 99;
  1713. downAt = null;
  1714. if (refPick && event.button === 0 && moved <= 4) {
  1715. const picked = refUnderPointer(event);
  1716. if (picked) {
  1717. refPick.handler(picked);
  1718. }
  1719. return;
  1720. }
  1721. const drag = planeDrag;
  1722. planeDrag = null;
  1723. if (drag && drag.active) {
  1724. // Dragged off a plane: the offset plane, not a pick
  1725. const handler = planeDragHandler;
  1726. const rect = canvas.getBoundingClientRect();
  1727. stopPlanePick();
  1728. handler.end(drag.pick, drag.offset, [event.clientX - rect.left, event.clientY - rect.top]);
  1729. return;
  1730. }
  1731. if (gizmoGrab) {
  1732. gizmoGrab = false;
  1733. return;
  1734. }
  1735. if (event.button !== 0 || moved > 4 || (!interactive && !planeHandler)) {
  1736. return;
  1737. }
  1738. if (planeHandler) {
  1739. const target = planeTargetUnderPointer(event);
  1740. if (target) {
  1741. const handler = planeHandler;
  1742. stopPlanePick();
  1743. handler(pickOf(target));
  1744. }
  1745. return;
  1746. }
  1747. const item = allowed(itemUnderPointer(event, true));
  1748. // While a panel picks, every click adds or drops; nothing is cleared by a miss
  1749. const additive = event.ctrlKey || event.shiftKey || event.metaKey || !!(pickFilter && pickFilter.toggle);
  1750. if (!item) {
  1751. if (!additive && selection.length) {
  1752. setSelection([]);
  1753. }
  1754. return;
  1755. }
  1756. // A click anywhere on a picked tangent chain drops the chain
  1757. const already = selection.some(function (s) {
  1758. return sameChain(s, item);
  1759. });
  1760. if (additive) {
  1761. setSelection(already ? selection.filter(function (s) {
  1762. return !sameChain(s, item);
  1763. }) : selection.concat([item]));
  1764. } else {
  1765. setSelection([item]);
  1766. }
  1767. });
  1768. // Wait for the user to pick a plane. With a solid in the scene the planar
  1769. // faces of the model are offered and the origin planes stay hidden (they
  1770. // would cover the part); in an empty part the origin planes are shown.
  1771. // Origin planes the user switched on stay pickable either way.
  1772. // dragHandler (optional): { frameOf(pick) -> { o, x, y, n } or null,
  1773. // move(pick, offset, [x, y]), end(pick, offset, [x, y]) } for dragging
  1774. // an offset plane off the one under the pointer
  1775. function startPlanePick(handler, withOrigin, dragHandler) {
  1776. planeHandler = handler;
  1777. planeDragHandler = dragHandler || null;
  1778. planeDrag = null;
  1779. setHovered(null);
  1780. originGroup.visible = originPinned || !bodies.length || !!withOrigin;
  1781. canvas.style.cursor = 'crosshair';
  1782. invalidate();
  1783. }
  1784. function stopPlanePick() {
  1785. planeHandler = null;
  1786. planeDragHandler = null;
  1787. planeDrag = null;
  1788. setHotWork(null);
  1789. setHotPlane(null);
  1790. setHovered(null);
  1791. originGroup.visible = originPinned;
  1792. canvas.style.cursor = restCursor();
  1793. invalidate();
  1794. }
  1795. function setOriginVisible(visible) {
  1796. originPinned = visible;
  1797. originGroup.visible = visible || (!!planeHandler && !bodies.length);
  1798. invalidate();
  1799. }
  1800. // Turn the camera square onto a plane given by its normal
  1801. function lookAlong(normal) {
  1802. const n = new THREE.Vector3().fromArray(normal).normalize();
  1803. const up = Math.abs(n.z) > 0.99 ? [0, n.z > 0 ? 1 : -1, 0] : [0, 0, 1];
  1804. flyTo(n.toArray(), up, true);
  1805. }
  1806. // Look at a face (a sketch plane, by its outward normal) from its front
  1807. // at an angle, the model fitted, so a solid built out of it shows its
  1808. // depth (faceview.js)
  1809. function viewFace(normal) {
  1810. const view = faceView(normal);
  1811. flyTo(view.dir, view.up, true);
  1812. }
  1813. /* ---------------- feature tools: regions, preview solid, drag arrow ---------------- */
  1814. // What a feature panel (features/extrude.js) shows in the model while it
  1815. // is open: the sketch regions that can be picked, the solid the feature
  1816. // would make, and an arrow to pull its distance.
  1817. const regionGroup = new THREE.Group();
  1818. const previewGroup = new THREE.Group();
  1819. const arrowHead = new THREE.Group();
  1820. scene.add(regionGroup);
  1821. scene.add(previewGroup);
  1822. scene.add(arrowHead);
  1823. const regionMaterial = function (color, opacity) {
  1824. return new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: opacity, side: THREE.DoubleSide, depthTest: false });
  1825. };
  1826. const regionMaterials = {
  1827. idle: regionMaterial(0x3b78e0, 0.16),
  1828. hot: regionMaterial(0x3b78e0, 0.42),
  1829. selected: regionMaterial(HOVER, 0.5),
  1830. selectedHot: regionMaterial(HOVER, 0.68)
  1831. };
  1832. let regionItems = [];
  1833. let regionHandler = null;
  1834. let hotRegion = -1;
  1835. function paintRegions() {
  1836. regionGroup.children.forEach(function (mesh, i) {
  1837. const hot = i === hotRegion;
  1838. mesh.material = regionMaterials[regionItems[i].selected ? (hot ? 'selectedHot' : 'selected') : (hot ? 'hot' : 'idle')];
  1839. });
  1840. invalidate();
  1841. }
  1842. // list: [{ positions: Float32Array (triangles, world), selected }] or null
  1843. // to stop. handler(index) is called when a region is clicked.
  1844. function setRegions(list, handler) {
  1845. disposeGroup(regionGroup);
  1846. regionItems = list || [];
  1847. regionHandler = list ? handler : null;
  1848. hotRegion = -1;
  1849. regionItems.forEach(function (item) {
  1850. const geometry = new THREE.BufferGeometry();
  1851. geometry.setAttribute('position', new THREE.BufferAttribute(item.positions, 3));
  1852. const mesh = new THREE.Mesh(geometry, regionMaterials.idle);
  1853. mesh.renderOrder = 3;
  1854. regionGroup.add(mesh);
  1855. });
  1856. if (!list) {
  1857. canvas.style.cursor = restCursor();
  1858. }
  1859. paintRegions();
  1860. }
  1861. /* ---- lines to pick as an axis (Revolve) ---- */
  1862. // Drawn over everything, picked by their distance on screen, so a line
  1863. // seen end-on or behind the model can still be had
  1864. const axisGroup = new THREE.Group();
  1865. scene.add(axisGroup);
  1866. const axisMaterials = {
  1867. idle: new LineMaterial({ color: 0x3b78e0, linewidth: 2, depthTest: false, depthWrite: false, transparent: true, opacity: 0.85 }),
  1868. hot: new LineMaterial({ color: HOVER, linewidth: 4, depthTest: false, depthWrite: false }),
  1869. selected: new LineMaterial({ color: SELECTED, linewidth: 4, depthTest: false, depthWrite: false })
  1870. };
  1871. let axisItems = [];
  1872. let axisHandler = null;
  1873. let hotAxis = -1;
  1874. function paintAxes() {
  1875. axisGroup.children.forEach(function (line, i) {
  1876. line.material = axisMaterials[i === hotAxis ? 'hot' : axisItems[i].selected ? 'selected' : 'idle'];
  1877. });
  1878. invalidate();
  1879. }
  1880. // list: [{ a: [x, y, z], b: [x, y, z], selected }] or null to stop;
  1881. // handler(index) is called when one is clicked
  1882. function setAxes(list, handler) {
  1883. disposeGroup(axisGroup);
  1884. axisItems = list || [];
  1885. axisHandler = list ? handler : null;
  1886. hotAxis = -1;
  1887. axisItems.forEach(function (item) {
  1888. const geometry = new LineSegmentsGeometry();
  1889. geometry.setPositions(item.a.concat(item.b));
  1890. const line = new LineSegments2(geometry, axisMaterials.idle);
  1891. line.renderOrder = 7;
  1892. axisGroup.add(line);
  1893. });
  1894. paintAxes();
  1895. }
  1896. /* ---------------- work axes and work points ---------------- */
  1897. // Work axes as long dashed lines, work points as small diamonds, both
  1898. // drawn over the model; their size on screen does not change with zoom
  1899. // (updateWorkRefs, every frame)
  1900. const workRefGroup = new THREE.Group();
  1901. scene.add(workRefGroup);
  1902. const workAxisMaterial = new THREE.LineDashedMaterial({ color: 0x2f6fb5, dashSize: 1, gapSize: 1, depthTest: false, depthWrite: false, transparent: true });
  1903. const workAxisDraftMaterial = new THREE.LineDashedMaterial({ color: HOVER, dashSize: 1, gapSize: 1, depthTest: false, depthWrite: false, transparent: true });
  1904. const workPointGeometry = new THREE.OctahedronGeometry(1);
  1905. const workPointMaterial = new THREE.MeshBasicMaterial({ color: 0x2f6fb5, depthTest: false, depthWrite: false, transparent: true });
  1906. const workPointDraftMaterial = new THREE.MeshBasicMaterial({ color: HOVER, depthTest: false, depthWrite: false, transparent: true });
  1907. let workAxisList = [];
  1908. let workPointList = [];
  1909. // The middle and size of the model, for lines long enough to see
  1910. function modelSpan() {
  1911. const box = new THREE.Box3();
  1912. if (bodies.length) {
  1913. box.setFromObject(bodyGroup);
  1914. }
  1915. return {
  1916. centre: box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3()),
  1917. size: box.isEmpty() ? PLANE_SIZE : Math.max(box.getSize(new THREE.Vector3()).length() * 1.1, 50)
  1918. };
  1919. }
  1920. // The two ends of a long line along { o, d }, around the model's middle
  1921. function lineEnds(o, d) {
  1922. const span = modelSpan();
  1923. const oo = new THREE.Vector3().fromArray(o);
  1924. const dd = new THREE.Vector3().fromArray(d).normalize();
  1925. const mid = oo.clone().addScaledVector(dd, span.centre.clone().sub(oo).dot(dd));
  1926. return [mid.clone().addScaledVector(dd, -span.size / 2).toArray(), mid.clone().addScaledVector(dd, span.size / 2).toArray()];
  1927. }
  1928. function clearWorkRefs(test) {
  1929. workRefGroup.children.filter(test).forEach(function (child) {
  1930. workRefGroup.remove(child);
  1931. if (child.geometry !== workPointGeometry) {
  1932. child.geometry.dispose();
  1933. }
  1934. });
  1935. }
  1936. // list: [{ id, o, d, draft }]
  1937. function setWorkAxes(list) {
  1938. clearWorkRefs(function (c) {
  1939. return c.userData.workAxis !== undefined;
  1940. });
  1941. workAxisList = (list || []).map(function (axis) {
  1942. return Object.assign({ ends: lineEnds(axis.o, axis.d) }, axis);
  1943. });
  1944. workAxisList.forEach(function (axis) {
  1945. const geometry = new THREE.BufferGeometry().setFromPoints(axis.ends.map(function (p) {
  1946. return new THREE.Vector3().fromArray(p);
  1947. }));
  1948. const line = new THREE.Line(geometry, axis.draft ? workAxisDraftMaterial : workAxisMaterial);
  1949. line.computeLineDistances();
  1950. line.renderOrder = 8;
  1951. line.userData.workAxis = axis.id;
  1952. workRefGroup.add(line);
  1953. });
  1954. invalidate();
  1955. }
  1956. // list: [{ id, at, draft }]
  1957. function setWorkPoints(list) {
  1958. clearWorkRefs(function (c) {
  1959. return c.userData.workPoint !== undefined;
  1960. });
  1961. workPointList = list || [];
  1962. workPointList.forEach(function (point) {
  1963. const mesh = new THREE.Mesh(workPointGeometry, point.draft ? workPointDraftMaterial : workPointMaterial);
  1964. mesh.position.fromArray(point.at);
  1965. mesh.renderOrder = 9;
  1966. mesh.userData.workPoint = point.id;
  1967. workRefGroup.add(mesh);
  1968. });
  1969. invalidate();
  1970. }
  1971. function updateWorkRefs() {
  1972. const w = worldPerPixel();
  1973. [workAxisMaterial, workAxisDraftMaterial].forEach(function (m) {
  1974. m.dashSize = 10 * w;
  1975. m.gapSize = 4 * w;
  1976. });
  1977. [workRefGroup, refGuides].forEach(function (group) {
  1978. group.children.forEach(function (c) {
  1979. if (c.geometry === workPointGeometry) {
  1980. c.scale.setScalar((c.userData.hot ? 6 : 4.5) * w);
  1981. }
  1982. });
  1983. });
  1984. }
  1985. /* ---------------- picking a plane, an axis or a point ---------------- */
  1986. // For the work feature panels: what may be picked is
  1987. // want: { planes, axes, edges, cylinders, points, vertices }
  1988. // planes: flat faces, origin and work planes; axes: origin and work
  1989. // axes; edges: straight edges; cylinders: round faces; points: the
  1990. // centre point and work points; vertices: corners of the model. The
  1991. // handler gets one of
  1992. // { kind: "plane", target } target as a plane pick gives it
  1993. // { kind: "axis", ref, line } ref { ref: "origin:x" } or { ref: "axis", id }
  1994. // { kind: "edge", item, line } a straight edge, item as selected
  1995. // { kind: "cylinder", item, line, radius, point }
  1996. // { kind: "point", ref, at } ref { ref: "origin" } or { ref: "point", id }
  1997. // { kind: "vertex", at }
  1998. // and the pick stays on until stopRefPick or the next startRefPick.
  1999. const refGuides = new THREE.Group();
  2000. scene.add(refGuides);
  2001. let refPick = null;
  2002. let refHot = null;
  2003. const ORIGIN_AXIS_COLORS = { x: 0xd64545, y: 0x3fae5a, z: 0x3b78e0 };
  2004. function clearGuides() {
  2005. while (refGuides.children.length) {
  2006. const child = refGuides.children.pop();
  2007. if (child.geometry && child.geometry !== workPointGeometry) {
  2008. child.geometry.dispose();
  2009. }
  2010. if (child.userData.ownMaterial) {
  2011. child.material.dispose();
  2012. }
  2013. }
  2014. }
  2015. function originAxisEnds(key) {
  2016. const d = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }[key];
  2017. return lineEnds([0, 0, 0], d);
  2018. }
  2019. function buildGuides() {
  2020. clearGuides();
  2021. const want = refPick ? refPick.want : {};
  2022. if (want.axes) {
  2023. ['x', 'y', 'z'].forEach(function (key) {
  2024. const ends = originAxisEnds(key);
  2025. const geometry = new THREE.BufferGeometry().setFromPoints(ends.map(function (p) {
  2026. return new THREE.Vector3().fromArray(p);
  2027. }));
  2028. const material = new THREE.LineBasicMaterial({ color: ORIGIN_AXIS_COLORS[key], depthTest: false, transparent: true, opacity: 0.8 });
  2029. const line = new THREE.Line(geometry, material);
  2030. line.renderOrder = 8;
  2031. line.userData.ownMaterial = true;
  2032. refGuides.add(line);
  2033. });
  2034. }
  2035. if (want.points) {
  2036. const centre = new THREE.Mesh(workPointGeometry, workPointMaterial);
  2037. centre.renderOrder = 9;
  2038. refGuides.add(centre);
  2039. }
  2040. // The marker of what is under the pointer
  2041. const marker = new THREE.Mesh(workPointGeometry, workPointDraftMaterial);
  2042. marker.visible = false;
  2043. marker.renderOrder = 10;
  2044. marker.userData.hot = true;
  2045. marker.userData.marker = true;
  2046. refGuides.add(marker);
  2047. const hotGeometry = new LineSegmentsGeometry();
  2048. hotGeometry.setPositions([0, 0, 0, 1, 0, 0]);
  2049. const hotLine = new LineSegments2(hotGeometry, axisMaterials.hot);
  2050. hotLine.visible = false;
  2051. hotLine.renderOrder = 10;
  2052. hotLine.userData.hotLine = true;
  2053. refGuides.add(hotLine);
  2054. }
  2055. // The corners of the model (the ends of its edges), in model space
  2056. function modelVertices() {
  2057. const out = [];
  2058. bodies.forEach(function (body) {
  2059. if (body.off) {
  2060. return; // hidden by the user
  2061. }
  2062. const data = body.data;
  2063. const ep = data.edgePositions;
  2064. if (!body.vertices) {
  2065. const seen = new Set();
  2066. body.vertices = [];
  2067. (data.edges || []).forEach(function (e) {
  2068. if (!ep || e.count < 2 || (e.curve && e.curve.type === 'circle' && e.curve.closed)) {
  2069. return;
  2070. }
  2071. [e.start * 3, (e.start + e.count - 1) * 3].forEach(function (i) {
  2072. const p = [ep[i], ep[i + 1], ep[i + 2]];
  2073. const key = p.map(function (v) {
  2074. return Math.round(v * 1e4);
  2075. }).join(',');
  2076. if (!seen.has(key)) {
  2077. seen.add(key);
  2078. body.vertices.push(p);
  2079. }
  2080. });
  2081. });
  2082. }
  2083. const m = body.matrix ? new THREE.Matrix4().fromArray(body.matrix) : null;
  2084. body.vertices.forEach(function (p) {
  2085. out.push(m ? new THREE.Vector3().fromArray(p).applyMatrix4(m).toArray() : p);
  2086. });
  2087. });
  2088. return out;
  2089. }
  2090. function segmentDistance(px, a, b) {
  2091. const dx = b[0] - a[0];
  2092. const dy = b[1] - a[1];
  2093. const len2 = dx * dx + dy * dy;
  2094. const t = len2 ? Math.max(0, Math.min(1, ((px[0] - a[0]) * dx + (px[1] - a[1]) * dy) / len2)) : 0;
  2095. return Math.hypot(px[0] - a[0] - dx * t, px[1] - a[1] - dy * t);
  2096. }
  2097. function refUnderPointer(event) {
  2098. const want = refPick.want;
  2099. const rect = canvas.getBoundingClientRect();
  2100. const px = [event.clientX - rect.left, event.clientY - rect.top];
  2101. // Points first: they are small
  2102. if (want.points || want.vertices) {
  2103. const list = [];
  2104. if (want.points) {
  2105. list.push({ kind: 'point', ref: { ref: 'origin' }, at: [0, 0, 0] });
  2106. workPointList.forEach(function (p) {
  2107. if (p.id) {
  2108. list.push({ kind: 'point', ref: { ref: 'point', id: p.id }, at: p.at });
  2109. }
  2110. });
  2111. }
  2112. if (want.vertices) {
  2113. modelVertices().forEach(function (at) {
  2114. list.push({ kind: 'vertex', at: at });
  2115. });
  2116. }
  2117. let best = null;
  2118. let bestD = 9;
  2119. list.forEach(function (c) {
  2120. const d = Math.hypot(project(c.at)[0] - px[0], project(c.at)[1] - px[1]);
  2121. if (d < bestD) {
  2122. bestD = d;
  2123. best = c;
  2124. }
  2125. });
  2126. if (best) {
  2127. return best;
  2128. }
  2129. }
  2130. if (want.axes) {
  2131. const lines = [];
  2132. ['x', 'y', 'z'].forEach(function (key) {
  2133. lines.push({ kind: 'axis', ref: { ref: 'origin:' + key }, line: { o: [0, 0, 0], d: { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }[key] }, ends: originAxisEnds(key) });
  2134. });
  2135. workAxisList.forEach(function (a) {
  2136. if (a.id) {
  2137. lines.push({ kind: 'axis', ref: { ref: 'axis', id: a.id }, line: { o: a.o, d: a.d }, ends: a.ends });
  2138. }
  2139. });
  2140. let best = null;
  2141. let bestD = 6;
  2142. lines.forEach(function (c) {
  2143. const d = segmentDistance(px, project(c.ends[0]), project(c.ends[1]));
  2144. if (d < bestD) {
  2145. bestD = d;
  2146. best = c;
  2147. }
  2148. });
  2149. if (best) {
  2150. return best;
  2151. }
  2152. }
  2153. if (want.edges || want.cylinders || want.planes) {
  2154. const item = itemUnderPointer(event, want.edges ? 'always' : false);
  2155. const info = item ? describeItem(item) : null;
  2156. if (info && item.type === 'edge' && want.edges && info.curve && info.curve.type === 'line') {
  2157. const a = info.curve.a;
  2158. const b = info.curve.b;
  2159. const d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
  2160. return { kind: 'edge', item: item, info: info, line: { o: a.slice(), d: d }, ends: [a, b] };
  2161. }
  2162. if (info && item.type === 'face' && want.cylinders && info.type === 'cylinder' && info.axis) {
  2163. return { kind: 'cylinder', item: item, info: info, line: { o: info.axis.o.slice(), d: info.axis.d.slice() }, radius: info.radius, point: lastFacePoint };
  2164. }
  2165. if (want.planes) {
  2166. const target = planeTargetUnderPointer(event);
  2167. if (target) {
  2168. return { kind: 'plane', target: pickOf(target), item: target.item || null };
  2169. }
  2170. }
  2171. }
  2172. return null;
  2173. }
  2174. function showRefHot(c) {
  2175. refHot = c;
  2176. const marker = refGuides.children.filter(function (x) {
  2177. return x.userData.marker;
  2178. })[0];
  2179. const hotLine = refGuides.children.filter(function (x) {
  2180. return x.userData.hotLine;
  2181. })[0];
  2182. if (marker) {
  2183. marker.visible = !!c && (c.kind === 'point' || c.kind === 'vertex');
  2184. if (marker.visible) {
  2185. marker.position.fromArray(c.at);
  2186. }
  2187. }
  2188. if (hotLine) {
  2189. hotLine.visible = !!c && c.kind === 'axis';
  2190. if (hotLine.visible) {
  2191. hotLine.geometry.setPositions(c.ends[0].concat(c.ends[1]));
  2192. }
  2193. }
  2194. setHovered(c && (c.kind === 'edge' || c.kind === 'cylinder') ? c.item : c && c.kind === 'plane' && c.item ? c.item : null);
  2195. setHotPlane(c && c.kind === 'plane' && c.target.kind === 'origin' ? c.target.key : null);
  2196. setHotWork(c && c.kind === 'plane' && c.target.kind === 'work' ? c.target.id : null);
  2197. invalidate();
  2198. }
  2199. function startRefPick(want, handler) {
  2200. refPick = { want: want || {}, handler: handler };
  2201. buildGuides();
  2202. originGroup.visible = originPinned || !!refPick.want.planes;
  2203. canvas.style.cursor = 'crosshair';
  2204. showRefHot(null);
  2205. }
  2206. function stopRefPick() {
  2207. if (!refPick) {
  2208. return;
  2209. }
  2210. refPick = null;
  2211. clearGuides();
  2212. refHot = null;
  2213. setHotPlane(null);
  2214. setHotWork(null);
  2215. setHovered(null);
  2216. originGroup.visible = originPinned;
  2217. canvas.style.cursor = restCursor();
  2218. invalidate();
  2219. }
  2220. function axisUnderPointer(event) {
  2221. const rect = canvas.getBoundingClientRect();
  2222. const px = [event.clientX - rect.left, event.clientY - rect.top];
  2223. let best = -1;
  2224. let bestD = 8;
  2225. axisItems.forEach(function (item, i) {
  2226. const a = project(item.a);
  2227. const b = project(item.b);
  2228. const dx = b[0] - a[0];
  2229. const dy = b[1] - a[1];
  2230. const len2 = dx * dx + dy * dy;
  2231. const t = len2 ? Math.max(0, Math.min(1, ((px[0] - a[0]) * dx + (px[1] - a[1]) * dy) / len2)) : 0;
  2232. const d = Math.hypot(px[0] - a[0] - dx * t, px[1] - a[1] - dy * t);
  2233. if (d < bestD) {
  2234. bestD = d;
  2235. best = i;
  2236. }
  2237. });
  2238. return best;
  2239. }
  2240. function regionUnderPointer(event) {
  2241. aim(event);
  2242. const hit = raycaster.intersectObjects(regionGroup.children, false)[0];
  2243. return hit ? regionGroup.children.indexOf(hit.object) : -1;
  2244. }
  2245. const previewColors = { join: 0x4caf6d, new: 0x4caf6d, cut: 0xd64545, intersect: 0x3b78e0 };
  2246. // The body as a fillet or chamfer would leave it: the model's own colour,
  2247. // with the faces the feature makes (mesh.fresh: [start, count] index
  2248. // ranges) in the preview green, as desktop CAD shows them
  2249. function resultMesh(geometry, mesh) {
  2250. // The part's own look (colour, finish, pattern), not the ghost's
  2251. const plain = bodyMaterial.clone();
  2252. plain.transparent = baseOpacity < 1;
  2253. plain.opacity = baseOpacity;
  2254. plain.depthWrite = baseOpacity >= 1;
  2255. plain.visible = true;
  2256. const fresh = new THREE.MeshStandardMaterial({
  2257. color: previewColors.join, metalness: 0.05, roughness: 0.55,
  2258. polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  2259. });
  2260. const ranges = (mesh.fresh || []).slice().sort(function (a, b) {
  2261. return a[0] - b[0];
  2262. });
  2263. let at = 0;
  2264. ranges.forEach(function (range) {
  2265. if (range[0] > at) {
  2266. geometry.addGroup(at, range[0] - at, 0);
  2267. }
  2268. geometry.addGroup(range[0], range[1], 1);
  2269. at = range[0] + range[1];
  2270. });
  2271. if (at < mesh.indices.length) {
  2272. geometry.addGroup(at, mesh.indices.length - at, 0);
  2273. }
  2274. return new THREE.Mesh(geometry, [plain, fresh]);
  2275. }
  2276. // mesh: { positions, indices, edgePositions } from the kernel (or a list
  2277. // of them), or null. What is removed (cut, intersect) is drawn through
  2278. // the body so it can be seen. kind "result" is the whole body as it would
  2279. // become (fillet, chamfer; see resultMesh), with the real body turned to
  2280. // a ghost that can still be picked.
  2281. function setPreview(meshes, kind) {
  2282. while (previewGroup.children.length) {
  2283. const child = previewGroup.children.pop();
  2284. child.geometry.dispose();
  2285. [].concat(child.material).forEach(function (material) {
  2286. material.dispose();
  2287. });
  2288. }
  2289. ghostOn = !!meshes && kind === 'result';
  2290. applyGhost();
  2291. (Array.isArray(meshes) ? meshes : meshes ? [meshes] : []).forEach(function (mesh) {
  2292. const adds = kind === 'join' || kind === 'new' || kind === 'result';
  2293. const geometry = new THREE.BufferGeometry();
  2294. geometry.setAttribute('position', new THREE.BufferAttribute(mesh.positions, 3));
  2295. geometry.setIndex(new THREE.BufferAttribute(mesh.indices, 1));
  2296. geometry.computeVertexNormals();
  2297. addUVs(geometry);
  2298. const solid = kind === 'result' ? resultMesh(geometry, mesh) : new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({
  2299. color: previewColors[kind] || previewColors.join, transparent: true, opacity: 0.45,
  2300. depthWrite: false, depthTest: adds, roughness: 0.7,
  2301. polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  2302. }));
  2303. solid.renderOrder = 2;
  2304. const lineGeometry = new THREE.BufferGeometry();
  2305. lineGeometry.setAttribute('position', new THREE.BufferAttribute(mesh.edgePositions, 3));
  2306. const lines = new THREE.LineSegments(lineGeometry, new THREE.LineBasicMaterial({
  2307. color: 0x20242b, transparent: kind !== 'result', opacity: kind === 'result' ? 1 : 0.7, depthTest: adds
  2308. }));
  2309. lines.renderOrder = 2;
  2310. previewGroup.add(solid);
  2311. previewGroup.add(lines);
  2312. if (kind === 'result') {
  2313. // The body as it would become, in the visual style of the
  2314. // body: covered edges dashed in "hidden edges" and wireframe,
  2315. // no surfaces in wireframe (applyVisualStyle)
  2316. solid.userData.role = 'result-solid';
  2317. lines.userData.role = 'result-lines';
  2318. const depth = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
  2319. colorWrite: false, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  2320. }));
  2321. depth.userData.role = 'result-depth';
  2322. depth.renderOrder = -1;
  2323. previewGroup.add(depth);
  2324. const hidden = new THREE.LineSegments(lineGeometry, hiddenLineMaterial());
  2325. hidden.computeLineDistances();
  2326. hidden.userData.role = 'result-hidden';
  2327. hidden.renderOrder = 3;
  2328. previewGroup.add(hidden);
  2329. }
  2330. });
  2331. applyVisualStyle();
  2332. invalidate();
  2333. }
  2334. // The arrow: built for a size of one pixel per unit and scaled every
  2335. // frame, so it stays the same size on screen at any zoom.
  2336. const arrowMaterial = new THREE.MeshBasicMaterial({ color: 0xe07b1f, depthTest: false });
  2337. const arrowPart = function (geometry, y) {
  2338. const mesh = new THREE.Mesh(geometry, arrowMaterial);
  2339. mesh.position.y = y;
  2340. mesh.renderOrder = 4;
  2341. arrowHead.add(mesh);
  2342. return mesh;
  2343. };
  2344. arrowPart(new THREE.SphereGeometry(4.5, 16, 12), 0);
  2345. arrowPart(new THREE.CylinderGeometry(1.6, 1.6, 26, 12), 13);
  2346. arrowPart(new THREE.ConeGeometry(5.5, 14, 16), 33);
  2347. const arrowGrab = arrowPart(new THREE.SphereGeometry(16, 8, 6), 16);
  2348. arrowGrab.material = new THREE.MeshBasicMaterial({ visible: false });
  2349. arrowHead.visible = false;
  2350. let arrow = null; // { origin, dir, length, onDrag }
  2351. let arrowDrag = false;
  2352. let featureDown = null;
  2353. function placeArrow() {
  2354. if (!arrow) {
  2355. return;
  2356. }
  2357. arrowHead.position.copy(arrow.origin).addScaledVector(arrow.dir, arrow.length);
  2358. arrowHead.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), arrow.dir);
  2359. arrowHead.scale.setScalar(worldPerPixel());
  2360. }
  2361. // spec: { origin: [x, y, z], dir: [x, y, z], length } or null.
  2362. // onDrag(distance, done) gets the distance along dir under the pointer.
  2363. function setArrow(spec, onDrag) {
  2364. arrow = spec ? {
  2365. origin: new THREE.Vector3().fromArray(spec.origin),
  2366. dir: new THREE.Vector3().fromArray(spec.dir).normalize(),
  2367. length: spec.length,
  2368. onDrag: onDrag
  2369. } : null;
  2370. arrowHead.visible = !!arrow;
  2371. placeArrow();
  2372. invalidate();
  2373. }
  2374. // Where along the arrow's axis the pointer is: the point of the axis
  2375. // closest to the ray through the pointer
  2376. function alongAxis(event) {
  2377. aim(event);
  2378. const d1 = raycaster.ray.direction;
  2379. const w = raycaster.ray.origin.clone().sub(arrow.origin);
  2380. const b = d1.dot(arrow.dir);
  2381. const denominator = 1 - b * b;
  2382. if (denominator < 1e-6) {
  2383. return null; // looking straight down the axis
  2384. }
  2385. return (arrow.dir.dot(w) - b * d1.dot(w)) / denominator;
  2386. }
  2387. // Registered for the capture phase so a grab of the arrow never starts an orbit
  2388. canvas.addEventListener('pointerdown', function (event) {
  2389. featureDown = [event.clientX, event.clientY];
  2390. if (!arrow || event.button !== 0) {
  2391. return;
  2392. }
  2393. aim(event);
  2394. if (raycaster.intersectObject(arrowGrab, false).length) {
  2395. arrowDrag = true;
  2396. controls.enabled = false;
  2397. event.stopImmediatePropagation();
  2398. try {
  2399. canvas.setPointerCapture(event.pointerId);
  2400. } catch (e) {
  2401. // The pointer is already gone; the drag still works inside the canvas
  2402. }
  2403. }
  2404. }, true);
  2405. canvas.addEventListener('pointermove', function (event) {
  2406. if (arrowDrag) {
  2407. const t = alongAxis(event);
  2408. if (t !== null) {
  2409. arrow.onDrag(t, false);
  2410. }
  2411. return;
  2412. }
  2413. let overAxis = false;
  2414. if (axisHandler && !event.buttons && !animation) {
  2415. const axis = axisUnderPointer(event);
  2416. overAxis = axis >= 0;
  2417. if (axis !== hotAxis) {
  2418. hotAxis = axis;
  2419. canvas.style.cursor = overAxis ? 'default' : restCursor();
  2420. paintAxes();
  2421. }
  2422. }
  2423. if (regionHandler && !event.buttons && !animation) {
  2424. const index = overAxis ? -1 : regionUnderPointer(event);
  2425. if (index !== hotRegion) {
  2426. hotRegion = index;
  2427. canvas.style.cursor = index >= 0 || overAxis ? 'default' : restCursor();
  2428. paintRegions();
  2429. }
  2430. }
  2431. });
  2432. canvas.addEventListener('pointerup', function (event) {
  2433. const moved = featureDown ? Math.hypot(event.clientX - featureDown[0], event.clientY - featureDown[1]) : 99;
  2434. featureDown = null;
  2435. if (arrowDrag) {
  2436. arrowDrag = false;
  2437. controls.enabled = true;
  2438. const t = alongAxis(event);
  2439. if (arrow && t !== null) {
  2440. arrow.onDrag(t, true);
  2441. }
  2442. return;
  2443. }
  2444. if (axisHandler && event.button === 0 && moved <= 4) {
  2445. const axis = axisUnderPointer(event);
  2446. if (axis >= 0) {
  2447. axisHandler(axis);
  2448. return; // an axis in front of a region wins
  2449. }
  2450. }
  2451. if (regionHandler && event.button === 0 && moved <= 4) {
  2452. const index = regionUnderPointer(event);
  2453. if (index >= 0) {
  2454. regionHandler(index);
  2455. }
  2456. }
  2457. });
  2458. /* ---------------- section view handles ---------------- */
  2459. // While the Section View panel is open each cutting plane shows as a
  2460. // see-through sheet over the model with an arrow on it, as in desktop
  2461. // CAD. Dragging the arrow (with any left button mode) or the sheet (while
  2462. // the left button selects) moves the plane along its axis, the same way
  2463. // a plane is dragged into an offset plane (planedrag.js).
  2464. // setSectionHandles(onDrag) turns them on, null off; onDrag(which,
  2465. // position, done) gets "" or "2" (the first or the second plane) and the
  2466. // new position on that plane's axis. Registered before the orbit ring,
  2467. // so a press on an arrow outside the ring drags the plane, not the view.
  2468. const SHEET_COLOR = 0x4a90d9;
  2469. const SHEET_OPACITY = 0.2;
  2470. const sectionGroup = new THREE.Group();
  2471. scene.add(sectionGroup);
  2472. let sectionHandler = null;
  2473. let sectionDrag = null; // { handle, from: [x, y], screen: [x, y] px per mm, at } while dragged
  2474. sectionHandles = [0, 1].map(function () {
  2475. const group = new THREE.Group();
  2476. const positions = new THREE.BufferAttribute(new Float32Array(12), 3);
  2477. const sheetGeometry = new THREE.BufferGeometry();
  2478. sheetGeometry.setAttribute('position', positions);
  2479. sheetGeometry.setIndex([0, 1, 2, 0, 2, 3]);
  2480. const sheetMaterial = new THREE.MeshBasicMaterial({
  2481. color: SHEET_COLOR, transparent: true, opacity: SHEET_OPACITY, side: THREE.DoubleSide, depthWrite: false,
  2482. // drawn just in front of the cut face it lies on
  2483. polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2
  2484. });
  2485. const sheet = new THREE.Mesh(sheetGeometry, sheetMaterial);
  2486. sheet.renderOrder = 3;
  2487. const outlineGeometry = new THREE.BufferGeometry();
  2488. outlineGeometry.setAttribute('position', positions);
  2489. const outline = new THREE.LineLoop(outlineGeometry, new THREE.LineBasicMaterial({ color: 0x2f6fb5 }));
  2490. outline.renderOrder = 3;
  2491. // The arrow, as the feature arrow above: one pixel per unit, scaled every frame
  2492. const head = new THREE.Group();
  2493. const headMaterial = new THREE.MeshBasicMaterial({ color: 0xe07b1f, depthTest: false });
  2494. [[new THREE.SphereGeometry(4.5, 16, 12), 0], [new THREE.CylinderGeometry(1.6, 1.6, 26, 12), 13], [new THREE.ConeGeometry(5.5, 14, 16), 33]].forEach(function (part) {
  2495. const mesh = new THREE.Mesh(part[0], headMaterial);
  2496. mesh.position.y = part[1];
  2497. mesh.renderOrder = 4;
  2498. head.add(mesh);
  2499. });
  2500. const grab = new THREE.Mesh(new THREE.SphereGeometry(16, 8, 6), new THREE.MeshBasicMaterial({ visible: false }));
  2501. grab.position.y = 16;
  2502. head.add(grab);
  2503. group.add(sheet, outline, head);
  2504. group.visible = false;
  2505. sectionGroup.add(group);
  2506. return {
  2507. group: group, sheet: sheet, sheetMaterial: sheetMaterial, positions: positions, head: head, headMaterial: headMaterial, grab: grab,
  2508. origin: new THREE.Vector3(), dir: new THREE.Vector3(0, 1, 0), axis: 0, at: 0, which: ''
  2509. };
  2510. });
  2511. // Put the sheets on the planes, over the model's extent and a margin;
  2512. // each arrow at its sheet's middle, pointing into the side cut away
  2513. function placeSectionHandles() {
  2514. if (!sectionHandles) {
  2515. return;
  2516. }
  2517. const bounds = sectionHandler && section.mode !== 'none' ? modelBounds() : null;
  2518. const specs = !bounds ? [] : [['', section.plane, section.offset, section.flip]].concat(section.mode === 'half' ? []
  2519. : [['2', section.plane2, section.offset2, section.flip2]]);
  2520. const size = bounds ? Math.max(bounds[1][0] - bounds[0][0], bounds[1][1] - bounds[0][1], bounds[1][2] - bounds[0][2], 1) : 1;
  2521. const pad = size * 0.12;
  2522. sectionHandles.forEach(function (h, i) {
  2523. const spec = specs[i];
  2524. h.group.visible = !!spec;
  2525. if (!spec) {
  2526. return;
  2527. }
  2528. const axis = SECTION_AXES[spec[1]];
  2529. const at = sectionAt(spec[1], spec[2], bounds);
  2530. const u = (axis + 1) % 3;
  2531. const v = (axis + 2) % 3;
  2532. [[0, 0], [1, 0], [1, 1], [0, 1]].forEach(function (corner, k) {
  2533. const p = [0, 0, 0];
  2534. p[axis] = at;
  2535. p[u] = corner[0] ? bounds[1][u] + pad : bounds[0][u] - pad;
  2536. p[v] = corner[1] ? bounds[1][v] + pad : bounds[0][v] - pad;
  2537. h.positions.setXYZ(k, p[0], p[1], p[2]);
  2538. });
  2539. h.positions.needsUpdate = true;
  2540. h.sheet.geometry.computeBoundingSphere();
  2541. h.origin.set((bounds[0][0] + bounds[1][0]) / 2, (bounds[0][1] + bounds[1][1]) / 2, (bounds[0][2] + bounds[1][2]) / 2).setComponent(axis, at);
  2542. h.dir.fromArray(SECTION_KEEP[spec[1]]).multiplyScalar(spec[3] ? 1 : -1);
  2543. h.axis = axis;
  2544. h.at = at;
  2545. h.which = spec[0];
  2546. });
  2547. if (sectionHot && !sectionHot.group.visible) {
  2548. setSectionHot(null);
  2549. }
  2550. placeSectionHeads();
  2551. invalidate();
  2552. }
  2553. // Every frame: the arrows keep their size on screen
  2554. function placeSectionHeads() {
  2555. if (!sectionHandles) {
  2556. return;
  2557. }
  2558. const scale = worldPerPixel();
  2559. sectionHandles.forEach(function (h) {
  2560. if (h.group.visible) {
  2561. h.head.position.copy(h.origin);
  2562. h.head.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), h.dir);
  2563. h.head.scale.setScalar(scale);
  2564. h.head.updateMatrixWorld(true);
  2565. }
  2566. });
  2567. }
  2568. function setSectionHandles(onDrag) {
  2569. sectionHandler = onDrag || null;
  2570. if (sectionDrag) {
  2571. sectionDrag = null;
  2572. controls.enabled = true; // closed in the middle of a drag
  2573. }
  2574. setSectionHot(null);
  2575. placeSectionHandles();
  2576. }
  2577. function setSectionHot(handle) {
  2578. if (handle === sectionHot) {
  2579. return;
  2580. }
  2581. sectionHot = handle;
  2582. sectionHandles.forEach(function (h) {
  2583. h.sheetMaterial.opacity = h === handle ? SHEET_OPACITY * 1.8 : SHEET_OPACITY;
  2584. h.headMaterial.color.setHex(h === handle ? 0xf5a04a : 0xe07b1f);
  2585. });
  2586. canvas.style.cursor = handle ? 'move' : hovered ? 'default' : restCursor();
  2587. invalidate();
  2588. }
  2589. // The handle under the pointer: an arrow first (with any left button
  2590. // mode), then a sheet while the left button selects, when no solid
  2591. // stands in front of it
  2592. function sectionHandleAt(event) {
  2593. if (!sectionHandler) {
  2594. return null;
  2595. }
  2596. aim(event);
  2597. const shown = sectionHandles.filter(function (h) {
  2598. return h.group.visible;
  2599. });
  2600. const arrowHit = shown.filter(function (h) {
  2601. return raycaster.intersectObject(h.grab, false).length > 0;
  2602. })[0];
  2603. if (arrowHit || leftDrag !== 'select') {
  2604. return arrowHit || null;
  2605. }
  2606. const solid = raycaster.intersectObjects(bodies.filter(function (b) {
  2607. return !b.off;
  2608. }).map(function (b) {
  2609. return b.mesh;
  2610. }), false).filter(function (hit) {
  2611. return !cutAway(hit.point);
  2612. })[0];
  2613. let best = null;
  2614. let near = solid ? solid.distance : Infinity;
  2615. shown.forEach(function (h) {
  2616. const hit = raycaster.intersectObject(h.sheet, false)[0];
  2617. if (hit && hit.distance < near) {
  2618. near = hit.distance;
  2619. best = h;
  2620. }
  2621. });
  2622. return best;
  2623. }
  2624. function stagePoint(event) {
  2625. const rect = canvas.getBoundingClientRect();
  2626. return [event.clientX - rect.left, event.clientY - rect.top];
  2627. }
  2628. canvas.addEventListener('pointerdown', function (event) {
  2629. if (!sectionHandler || event.button !== 0 || animation) {
  2630. return;
  2631. }
  2632. const h = sectionHandleAt(event);
  2633. if (!h) {
  2634. return;
  2635. }
  2636. // Pixels one millimetre along the plane's axis covers on screen
  2637. const a = project(h.origin.toArray());
  2638. const b = project(h.origin.clone().add(h.dir).toArray());
  2639. sectionDrag = { handle: h, from: stagePoint(event), screen: [b[0] - a[0], b[1] - a[1]], at: h.at };
  2640. setSectionHot(h);
  2641. controls.enabled = false;
  2642. event.stopImmediatePropagation();
  2643. try {
  2644. canvas.setPointerCapture(event.pointerId);
  2645. } catch (e) {
  2646. // A synthetic event has no pointer to capture
  2647. }
  2648. }, true);
  2649. // The position the drag has reached on the plane's axis
  2650. function sectionDragAt(event) {
  2651. const d = sectionDrag;
  2652. const wpp = worldPerPixel();
  2653. const along = dragOffset(d.from, stagePoint(event), d.screen, wpp);
  2654. return snapOffset(d.at + along * d.handle.dir.getComponent(d.handle.axis), wpp);
  2655. }
  2656. canvas.addEventListener('pointermove', function (event) {
  2657. if (sectionDrag) {
  2658. sectionHandler(sectionDrag.handle.which, sectionDragAt(event), false);
  2659. return;
  2660. }
  2661. if (sectionHandler && !event.buttons && !animation) {
  2662. setSectionHot(sectionHandleAt(event));
  2663. }
  2664. });
  2665. function endSectionDrag(event, done) {
  2666. if (!sectionDrag) {
  2667. return;
  2668. }
  2669. const at = event && done ? sectionDragAt(event) : sectionDrag.at;
  2670. const which = sectionDrag.handle.which;
  2671. sectionDrag = null;
  2672. controls.enabled = true;
  2673. if (sectionHandler) {
  2674. sectionHandler(which, at, true);
  2675. }
  2676. }
  2677. canvas.addEventListener('pointerup', function (event) {
  2678. endSectionDrag(event, true);
  2679. });
  2680. canvas.addEventListener('pointercancel', function () {
  2681. endSectionDrag(null, false); // back where the drag started
  2682. });
  2683. canvas.addEventListener('pointerleave', function () {
  2684. if (!sectionDrag) {
  2685. setSectionHot(null);
  2686. }
  2687. });
  2688. /* ---------------- orbit ring (left button orbits) ---------------- */
  2689. // Inside the ring OrbitControls turns the view (freely, see turnView);
  2690. // a press outside it or on a tick is handled here. Registered after the
  2691. // feature arrow's grab, so a press on the arrow still drags the arrow.
  2692. let ringDrag = null; // { zone, x, y } while the ring has the left button
  2693. // "free" inside the ring, "roll" outside it, "tilt" on the top or
  2694. // bottom tick, "spin" on the left or right one
  2695. function ringZone(x, y) {
  2696. const ring = orbitRing(canvas.clientWidth, canvas.clientHeight);
  2697. const dx = x - ring.cx;
  2698. const dy = y - ring.cy;
  2699. const d = Math.hypot(dx, dy);
  2700. if (d > ring.r - RING_GRIP && d < ring.r + ring.tick + RING_GRIP) {
  2701. if (Math.abs(dx) < RING_GRIP) {
  2702. return 'tilt';
  2703. }
  2704. if (Math.abs(dy) < RING_GRIP) {
  2705. return 'spin';
  2706. }
  2707. }
  2708. return d > ring.r ? 'roll' : 'free';
  2709. }
  2710. function canvasPoint(event) {
  2711. const rect = canvas.getBoundingClientRect();
  2712. return [event.clientX - rect.left, event.clientY - rect.top];
  2713. }
  2714. canvas.addEventListener('pointerdown', function (event) {
  2715. if (leftDrag !== 'orbit' || event.button !== 0 || animation || (gizmoActive && gizmo.axis !== null)) {
  2716. return;
  2717. }
  2718. const at = canvasPoint(event);
  2719. const zone = ringZone(at[0], at[1]);
  2720. if (zone === 'free') {
  2721. return; // OrbitControls has it
  2722. }
  2723. noteView();
  2724. ringDrag = { zone: zone, x: at[0], y: at[1] };
  2725. controls.enabled = false; // OrbitControls leaves this press alone
  2726. try {
  2727. canvas.setPointerCapture(event.pointerId);
  2728. } catch (e) {
  2729. // A synthetic event has no pointer to capture
  2730. }
  2731. }, true);
  2732. canvas.addEventListener('pointermove', function (event) {
  2733. const at = canvasPoint(event);
  2734. if (ringDrag) {
  2735. const turn = Math.PI * 2 / (canvas.clientHeight || 1); // as OrbitControls: a drag of the full height is one turn
  2736. if (ringDrag.zone === 'roll') {
  2737. // The part turns round the middle of the view with the pointer
  2738. const ring = orbitRing(canvas.clientWidth, canvas.clientHeight);
  2739. let angle = Math.atan2(at[1] - ring.cy, at[0] - ring.cx) - Math.atan2(ringDrag.y - ring.cy, ringDrag.x - ring.cx);
  2740. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  2741. turnView(screenAxis(0, 0, 1), angle);
  2742. } else if (ringDrag.zone === 'tilt') {
  2743. turnView(screenAxis(1, 0, 0), -turn * (at[1] - ringDrag.y));
  2744. } else {
  2745. turnView(screenAxis(0, 1, 0), -turn * (at[0] - ringDrag.x));
  2746. }
  2747. ringDrag.x = at[0];
  2748. ringDrag.y = at[1];
  2749. invalidate();
  2750. return;
  2751. }
  2752. // The cursor tells what a drag from here would do
  2753. if (leftDrag === 'orbit' && !event.buttons) {
  2754. const zone = ringZone(at[0], at[1]);
  2755. if (zone !== ringHover) {
  2756. ringHover = zone;
  2757. if (!hovered && hotAxis < 0 && hotRegion < 0 && !planeHandler) {
  2758. canvas.style.cursor = restCursor();
  2759. }
  2760. }
  2761. }
  2762. });
  2763. function endRingDrag() {
  2764. if (ringDrag) {
  2765. ringDrag = null;
  2766. controls.enabled = true;
  2767. }
  2768. }
  2769. canvas.addEventListener('pointerup', endRingDrag);
  2770. canvas.addEventListener('pointercancel', endRingDrag);
  2771. /* ---------------- move / rotate / scale triad (assemblies) ---------------- */
  2772. // three.js TransformControls on a stand-in object at the component's
  2773. // centre. The handler gets the change as a matrix (stand-in now times
  2774. // stand-in at the start, inverted): the component's placement times it.
  2775. const gizmo = new TransformControls(camera, canvas);
  2776. const gizmoHelper = gizmo.getHelper();
  2777. scene.add(gizmoHelper);
  2778. const gizmoProxy = new THREE.Object3D();
  2779. scene.add(gizmoProxy);
  2780. const gizmoStart = new THREE.Matrix4();
  2781. let gizmoActive = false;
  2782. let gizmoGrab = false; // the last press landed on the triad
  2783. let gizmoHandler = null;
  2784. gizmo.addEventListener('change', invalidate);
  2785. gizmo.addEventListener('dragging-changed', function (event) {
  2786. controls.enabled = !event.value;
  2787. if (!event.value && gizmoHandler) {
  2788. gizmoHandler(gizmoDelta(), true);
  2789. }
  2790. });
  2791. gizmo.addEventListener('objectChange', function () {
  2792. if (gizmo.mode === 'scale') {
  2793. // One size in all three directions: the one being pulled
  2794. const s = gizmoProxy.scale;
  2795. let pulled = 1;
  2796. [s.x, s.y, s.z].forEach(function (v) {
  2797. if (Math.abs(v - 1) > Math.abs(pulled - 1)) {
  2798. pulled = v;
  2799. }
  2800. });
  2801. s.setScalar(Math.max(pulled, 0.01));
  2802. }
  2803. if (gizmoHandler) {
  2804. gizmoHandler(gizmoDelta(), false);
  2805. }
  2806. });
  2807. function gizmoDelta() {
  2808. gizmoProxy.updateMatrixWorld(true);
  2809. return gizmoProxy.matrixWorld.clone().multiply(gizmoStart.clone().invert()).toArray();
  2810. }
  2811. // spec: { position: [x, y, z], rotation: 3 x 3 row-major (how the
  2812. // component is turned, for the Local space), mode: "translate" |
  2813. // "rotate" | "scale", space: "world" | "local", snap: { move, turn
  2814. // (degrees), scale } or null }. handler(delta matrix, done)
  2815. function attachGizmo(spec, handler) {
  2816. gizmoProxy.position.fromArray(spec.position);
  2817. if (spec.rotation) {
  2818. const r = spec.rotation;
  2819. gizmoProxy.quaternion.setFromRotationMatrix(new THREE.Matrix4().set(r[0], r[1], r[2], 0, r[3], r[4], r[5], 0, r[6], r[7], r[8], 0, 0, 0, 0, 1));
  2820. } else {
  2821. gizmoProxy.quaternion.identity();
  2822. }
  2823. gizmoProxy.scale.set(1, 1, 1);
  2824. gizmoProxy.updateMatrixWorld(true);
  2825. gizmoStart.copy(gizmoProxy.matrixWorld);
  2826. gizmo.camera = camera;
  2827. gizmo.setMode(spec.mode || 'translate');
  2828. gizmo.setSpace(spec.space || 'world');
  2829. gizmo.setTranslationSnap(spec.snap ? spec.snap.move : null);
  2830. gizmo.setRotationSnap(spec.snap ? THREE.MathUtils.degToRad(spec.snap.turn) : null);
  2831. gizmo.setScaleSnap(spec.snap ? spec.snap.scale : null);
  2832. if (!gizmoActive) {
  2833. gizmo.attach(gizmoProxy);
  2834. }
  2835. gizmoActive = true;
  2836. gizmoHandler = handler;
  2837. invalidate();
  2838. }
  2839. function detachGizmo() {
  2840. if (gizmoActive) {
  2841. gizmo.detach();
  2842. }
  2843. gizmoActive = false;
  2844. gizmoHandler = null;
  2845. gizmoGrab = false;
  2846. controls.enabled = true;
  2847. invalidate();
  2848. }
  2849. /* ---------------- measure lines ---------------- */
  2850. // [{ a: [x, y, z], b: [x, y, z], label }] drawn over the model: a line
  2851. // between the two closest points and its value beside the middle
  2852. const measureGroup = new THREE.Group();
  2853. scene.add(measureGroup);
  2854. const measureMaterial = new LineMaterial({ color: 0xe07b1f, linewidth: 2.5, depthTest: false, depthWrite: false, transparent: true });
  2855. const measureDot = new THREE.MeshBasicMaterial({ color: 0xe07b1f, depthTest: false });
  2856. let measureLabels = [];
  2857. function setMeasure(list) {
  2858. while (measureGroup.children.length) {
  2859. const child = measureGroup.children.pop();
  2860. child.geometry.dispose();
  2861. }
  2862. measureLabels.forEach(function (label) {
  2863. label.el.remove();
  2864. });
  2865. measureLabels = [];
  2866. (list || []).forEach(function (m) {
  2867. const geometry = new LineSegmentsGeometry();
  2868. geometry.setPositions(m.a.concat(m.b));
  2869. const line = new LineSegments2(geometry, measureMaterial);
  2870. line.renderOrder = 9;
  2871. measureGroup.add(line);
  2872. [m.a, m.b].forEach(function (p) {
  2873. const dot = new THREE.Mesh(new THREE.SphereGeometry(1, 12, 8), measureDot);
  2874. dot.position.fromArray(p);
  2875. dot.userData.dot = true;
  2876. dot.renderOrder = 9;
  2877. measureGroup.add(dot);
  2878. });
  2879. if (m.label) {
  2880. const el = document.createElement('div');
  2881. el.className = 'measure-label';
  2882. el.textContent = m.label;
  2883. stage.appendChild(el);
  2884. measureLabels.push({ el: el, point: [(m.a[0] + m.b[0]) / 2, (m.a[1] + m.b[1]) / 2, (m.a[2] + m.b[2]) / 2] });
  2885. }
  2886. });
  2887. invalidate();
  2888. }
  2889. /* ---------------- reference meshes (STL / OBJ brought in) ---------------- */
  2890. // [{ id, positions, indices }]: drawn pale and see-through, never picked;
  2891. // a mesh already drawn with the same data is kept
  2892. const meshGroup = new THREE.Group();
  2893. scene.add(meshGroup);
  2894. const referenceMaterial = new THREE.MeshStandardMaterial({
  2895. color: 0x9fb0c8, roughness: 0.8, metalness: 0, transparent: true, opacity: 0.55,
  2896. side: THREE.DoubleSide, depthWrite: false, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1
  2897. });
  2898. let referenceMeshes = new Map(); // id -> { key, mesh }
  2899. function setMeshes(list) {
  2900. const next = new Map();
  2901. (list || []).forEach(function (m) {
  2902. const key = m.positions.length + ':' + m.indices.length + ':' + (m.positions[0] || 0);
  2903. const old = referenceMeshes.get(m.id);
  2904. if (old && old.key === key) {
  2905. next.set(m.id, old);
  2906. referenceMeshes.delete(m.id);
  2907. return;
  2908. }
  2909. const geometry = new THREE.BufferGeometry();
  2910. geometry.setAttribute('position', new THREE.BufferAttribute(m.positions, 3));
  2911. geometry.setIndex(new THREE.BufferAttribute(m.indices, 1));
  2912. geometry.computeVertexNormals();
  2913. const mesh = new THREE.Mesh(geometry, referenceMaterial);
  2914. mesh.raycast = function () {}; // a reference: never picked
  2915. mesh.renderOrder = 2;
  2916. meshGroup.add(mesh);
  2917. next.set(m.id, { key: key, mesh: mesh });
  2918. });
  2919. referenceMeshes.forEach(function (entry) {
  2920. meshGroup.remove(entry.mesh);
  2921. entry.mesh.geometry.dispose();
  2922. });
  2923. referenceMeshes = next;
  2924. invalidate();
  2925. }
  2926. /* ---------------- problem markers (Check Geometry) ---------------- */
  2927. // [{ at: [x, y, z], kind: "open" | "multiple" | "face" }]: dots over the
  2928. // model, seen through it, where a check found something wrong
  2929. const markerGroup = new THREE.Group();
  2930. scene.add(markerGroup);
  2931. const markerGeometry = new THREE.SphereGeometry(1, 12, 8);
  2932. const markerMaterials = {
  2933. open: new THREE.MeshBasicMaterial({ color: 0xd8342c, depthTest: false, transparent: true, opacity: 0.9 }),
  2934. multiple: new THREE.MeshBasicMaterial({ color: 0xe8a317, depthTest: false, transparent: true, opacity: 0.9 }),
  2935. face: new THREE.MeshBasicMaterial({ color: 0x9b4dca, depthTest: false, transparent: true, opacity: 0.9 })
  2936. };
  2937. function setMarkers(list) {
  2938. while (markerGroup.children.length) {
  2939. markerGroup.children.pop();
  2940. }
  2941. (list || []).forEach(function (m) {
  2942. const dot = new THREE.Mesh(markerGeometry, markerMaterials[m.kind] || markerMaterials.open);
  2943. dot.position.fromArray(m.at);
  2944. dot.renderOrder = 10;
  2945. markerGroup.add(dot);
  2946. });
  2947. invalidate();
  2948. }
  2949. function placeMeasureLabels() {
  2950. const size = worldPerPixel() * 4;
  2951. measureGroup.children.forEach(function (child) {
  2952. if (child.userData.dot) {
  2953. child.scale.setScalar(size);
  2954. }
  2955. });
  2956. markerGroup.children.forEach(function (child) {
  2957. child.scale.setScalar(size * 1.4);
  2958. });
  2959. measureLabels.forEach(function (label) {
  2960. const at = project(label.point);
  2961. label.el.style.left = Math.round(at[0] + 8) + 'px';
  2962. label.el.style.top = Math.round(at[1] - 10) + 'px';
  2963. });
  2964. }
  2965. /* ---------------- view cube ---------------- */
  2966. // A CSS 3D cube that follows the camera. Every face is a 3 x 3 grid: the
  2967. // middle looks straight at the face, a border cell at the edge it touches
  2968. // and a corner cell at the corner, like the cube of a desktop CAD system.
  2969. // The two (or three) cells that meet at an edge (or corner) share a key,
  2970. // so they light up together.
  2971. const cubeCam = options.viewCube;
  2972. const CUBE_HALF = 25;
  2973. const cubeCells = {};
  2974. function lightCells(key, on) {
  2975. (cubeCells[key] || []).forEach(function (cell) {
  2976. cell.classList.toggle('hot', on);
  2977. });
  2978. }
  2979. CUBE_FACES.forEach(function (face) {
  2980. const n = new THREE.Vector3().fromArray(face.normal);
  2981. const u = new THREE.Vector3().fromArray(face.up);
  2982. const x = new THREE.Vector3().crossVectors(u, n);
  2983. const m = new THREE.Matrix4().makeBasis(x, u, n).setPosition(n.clone().multiplyScalar(CUBE_HALF));
  2984. const e = m.elements;
  2985. // Same element order three.js uses for CSS 3D objects (Y axis flipped)
  2986. const css = [e[0], e[1], e[2], e[3], -e[4], -e[5], -e[6], -e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]];
  2987. const el = document.createElement('div');
  2988. el.className = 'vc-face';
  2989. el.style.transform = 'translate(-50%,-50%) matrix3d(' + css.map(fix).join(',') + ')';
  2990. // Rows run top to bottom on the face, columns left to right
  2991. for (let row = 1; row >= -1; row--) {
  2992. for (let col = -1; col <= 1; col++) {
  2993. const direction = n.clone().addScaledVector(x, col).addScaledVector(u, row);
  2994. const key = [direction.x, direction.y, direction.z].map(Math.round).join(',');
  2995. const cell = document.createElement('div');
  2996. cell.className = 'vc-cell';
  2997. (cubeCells[key] = cubeCells[key] || []).push(cell);
  2998. cell.addEventListener('mouseenter', function () {
  2999. lightCells(key, true);
  3000. });
  3001. cell.addEventListener('mouseleave', function () {
  3002. lightCells(key, false);
  3003. });
  3004. cell.addEventListener('click', function () {
  3005. // Straight onto a face keeps that face's own "up"; any
  3006. // tilted view stands upright on world Z
  3007. const straight = row === 0 && col === 0;
  3008. flyTo(direction.toArray(), straight ? face.up : WORLD_UP.toArray(), true);
  3009. });
  3010. el.appendChild(cell);
  3011. }
  3012. }
  3013. const label = document.createElement('span');
  3014. label.className = 'vc-label';
  3015. label.textContent = face.name;
  3016. el.appendChild(label);
  3017. cubeCam.appendChild(el);
  3018. });
  3019. function fix(v) {
  3020. return Math.abs(v) < 1e-10 ? 0 : v;
  3021. }
  3022. const rotationOnly = new THREE.Matrix4();
  3023. function updateOverlays() {
  3024. rotationOnly.extractRotation(camera.matrixWorldInverse);
  3025. const e = rotationOnly.elements;
  3026. cubeCam.style.transform = 'matrix3d(' + [
  3027. e[0], -e[1], e[2], 0, e[4], -e[5], e[6], 0, e[8], -e[9], e[10], 0, 0, 0, 0, 1
  3028. ].map(fix).join(',') + ')';
  3029. drawTriad();
  3030. }
  3031. /* ---------------- axis triad ---------------- */
  3032. const triad = options.triad;
  3033. const AXES = [
  3034. { name: 'X', dir: new THREE.Vector3(1, 0, 0), color: '#d64545' },
  3035. { name: 'Y', dir: new THREE.Vector3(0, 1, 0), color: '#2e9e5b' },
  3036. { name: 'Z', dir: new THREE.Vector3(0, 0, 1), color: '#3b78e0' }
  3037. ];
  3038. function drawTriad() {
  3039. const parts = AXES.map(function (axis) {
  3040. const v = axis.dir.clone().applyMatrix4(rotationOnly);
  3041. return { axis: axis, x: v.x * 26, y: -v.y * 26, depth: v.z };
  3042. }).sort(function (a, b) {
  3043. return a.depth - b.depth;
  3044. });
  3045. triad.innerHTML = parts.map(function (p) {
  3046. return '<line x1="0" y1="0" x2="' + p.x.toFixed(1) + '" y2="' + p.y.toFixed(1) + '" stroke="' + p.axis.color +
  3047. '" stroke-width="2.4" stroke-linecap="round"/><text x="' + (p.x * 1.32).toFixed(1) + '" y="' +
  3048. (p.y * 1.32).toFixed(1) + '" fill="' + p.axis.color + '">' + p.axis.name + '</text>';
  3049. }).join('');
  3050. }
  3051. /* ---------------- sketches ---------------- */
  3052. // Finished sketches drawn in the model: [{ id, segments: Float32Array }]
  3053. // in world coordinates, two vertices per segment.
  3054. const sketchGroup = new THREE.Group();
  3055. const sketchMaterial = new THREE.LineBasicMaterial({ color: 0x3b78e0 });
  3056. scene.add(sketchGroup);
  3057. function setSketches(list) {
  3058. disposeGroup(sketchGroup);
  3059. list.forEach(function (sketch) {
  3060. if (!sketch.segments.length) {
  3061. return;
  3062. }
  3063. const geometry = new THREE.BufferGeometry();
  3064. geometry.setAttribute('position', new THREE.BufferAttribute(sketch.segments, 3));
  3065. sketchGroup.add(new THREE.LineSegments(geometry, sketchMaterial));
  3066. });
  3067. invalidate();
  3068. }
  3069. /* ---------------- screen <-> sketch plane ---------------- */
  3070. const scratch = new THREE.Vector3();
  3071. // World point -> canvas pixel [x, y] (CSS pixels from the canvas corner)
  3072. function project(point) {
  3073. scratch.set(point[0], point[1], point[2]).project(camera);
  3074. return [(scratch.x + 1) / 2 * stage.clientWidth, (1 - scratch.y) / 2 * stage.clientHeight];
  3075. }
  3076. // Pointer position -> coordinates [u, v] on a plane { o, x, y, n },
  3077. // or null when the view is edge-on to the plane
  3078. function pointOnPlane(clientX, clientY, frame) {
  3079. aim({ clientX: clientX, clientY: clientY });
  3080. const n = new THREE.Vector3().fromArray(frame.n);
  3081. const o = new THREE.Vector3().fromArray(frame.o);
  3082. const denominator = raycaster.ray.direction.dot(n);
  3083. if (Math.abs(denominator) < 1e-6) {
  3084. return null;
  3085. }
  3086. const t = o.clone().sub(raycaster.ray.origin).dot(n) / denominator;
  3087. const hit = raycaster.ray.origin.clone().addScaledVector(raycaster.ray.direction, t).sub(o);
  3088. return [hit.dot(scratch.fromArray(frame.x)), hit.dot(scratch.fromArray(frame.y))];
  3089. }
  3090. /* ---------------- render loop ---------------- */
  3091. let scheduled = false;
  3092. function invalidate() {
  3093. if (!scheduled) {
  3094. scheduled = true;
  3095. requestAnimationFrame(render);
  3096. }
  3097. }
  3098. function render(now) {
  3099. scheduled = false;
  3100. if (animation) {
  3101. stepAnimation(now);
  3102. }
  3103. camera.updateMatrixWorld();
  3104. if (groundDirty) {
  3105. placeGround();
  3106. }
  3107. updateWorkRefs();
  3108. updateSilhouettes();
  3109. updateDashes();
  3110. placeArrow();
  3111. placeSectionHeads();
  3112. if (capParts.length && Math.abs(worldPerPixel() - capZoom) > capZoom * 0.02) {
  3113. placeCaps(); // zoomed: the hatching keeps its spacing on screen
  3114. }
  3115. headlight.position.copy(camera.position);
  3116. headlight.target.position.copy(controls.target);
  3117. renderer.render(scene, camera);
  3118. updateOverlays();
  3119. placeMeasureLabels();
  3120. if (api.onRender) {
  3121. api.onRender();
  3122. }
  3123. if (animation) {
  3124. invalidate();
  3125. }
  3126. }
  3127. new ResizeObserver(resize).observe(stage);
  3128. // The theme (body.dark) decides the wireframe line colour
  3129. new MutationObserver(function () {
  3130. applyVisualStyle();
  3131. invalidate();
  3132. }).observe(document.body, { attributes: true, attributeFilter: ['class'] });
  3133. resize();
  3134. ortho.zoom = 1;
  3135. home();
  3136. Object.assign(api, {
  3137. invalidate: invalidate,
  3138. setBodies: setBodies,
  3139. setSketches: setSketches,
  3140. setWorkPlanes: setWorkPlanes,
  3141. selectEdges: selectEdges,
  3142. selectFaces: selectFaces,
  3143. // Solid bodies hidden by the user: [number]
  3144. setHiddenBodies: function (list) {
  3145. hiddenBodies = new Set(list || []);
  3146. applyVisualStyle();
  3147. invalidate();
  3148. },
  3149. setWorkAxes: setWorkAxes,
  3150. setWorkPoints: setWorkPoints,
  3151. startRefPick: startRefPick,
  3152. stopRefPick: stopRefPick,
  3153. // A pick made elsewhere (the model browser) for the open reference
  3154. // pick: taken when it is something the pick wants. Returns true then.
  3155. offerRef: function (pick) {
  3156. if (!refPick) {
  3157. return false;
  3158. }
  3159. const want = refPick.want;
  3160. const fits = pick.kind === 'plane' ? want.planes : pick.kind === 'axis' ? want.axes : pick.kind === 'point' ? want.points : false;
  3161. if (!fits) {
  3162. return false;
  3163. }
  3164. refPick.handler(pick);
  3165. return true;
  3166. },
  3167. isRefPicking: function () {
  3168. return !!refPick;
  3169. },
  3170. // Limit what can be picked: { edges, faces, toggle } or null for everything
  3171. setPickFilter: function (filter) {
  3172. pickFilter = filter;
  3173. setHovered(null);
  3174. },
  3175. // Tangent chains for the active pick filter (see chainOf), or null
  3176. setEdgeChains: function (chains) {
  3177. if (pickFilter) {
  3178. pickFilter.chains = chains;
  3179. drawOverlays();
  3180. }
  3181. },
  3182. coveredEdges: coveredEdges,
  3183. setRegions: setRegions,
  3184. setAxes: setAxes,
  3185. setPreview: setPreview,
  3186. setArrow: setArrow,
  3187. // Faces and edges of the model react to the pointer (true) or not
  3188. setPicking: function (on) {
  3189. interactive = on;
  3190. if (!on) {
  3191. setHovered(null);
  3192. }
  3193. },
  3194. // The face or edge of the model at a screen position, whatever mode is on
  3195. modelItemAt: function (clientX, clientY) {
  3196. return itemUnderPointer({ clientX: clientX, clientY: clientY }, true);
  3197. },
  3198. hoverModel: function (item) {
  3199. setHovered(item || null);
  3200. },
  3201. // The exact edge shapes of a model item: one for an edge, all of
  3202. // them for a face. Edges that are neither straight nor circular are left out.
  3203. curvesOf: function (item) {
  3204. const data = item && bodies[item.body] && bodies[item.body].data;
  3205. if (!data) {
  3206. return [];
  3207. }
  3208. const list = item.type === 'face' ? (data.faces[item.index].edges || []) : [item.index];
  3209. // Each with the edge it is (source), so projected geometry can
  3210. // follow the edge when the model changes
  3211. return list.map(function (i) {
  3212. const e = data.edges[i];
  3213. return e && e.curve ? Object.assign({}, e.curve, { source: { body: item.body, mid: e.mid, length: e.length } }) : null;
  3214. }).filter(Boolean);
  3215. },
  3216. project: project,
  3217. pointOnPlane: pointOnPlane,
  3218. worldPerPixel: worldPerPixel,
  3219. isPicking: function () {
  3220. return !!planeHandler;
  3221. },
  3222. // While sketching the left button draws; middle and right still pan,
  3223. // the wheel zooms, and faces and edges of the model are not picked
  3224. setSketching: function (on) {
  3225. interactive = !on;
  3226. sketching = on;
  3227. groundDirty = true;
  3228. controls.mouseButtons.LEFT = leftButton();
  3229. if (on) {
  3230. setHovered(null);
  3231. if (selection.length) {
  3232. setSelection([]);
  3233. }
  3234. }
  3235. },
  3236. bodyCount: function () {
  3237. return bodies.length;
  3238. },
  3239. selection: function () {
  3240. return selection.map(describeItem);
  3241. },
  3242. clearSelection: function () {
  3243. if (selection.length) {
  3244. setSelection([]);
  3245. }
  3246. },
  3247. lookAlong: lookAlong,
  3248. viewFace: viewFace,
  3249. // The look of the part on show (appearance.js), or null for the default
  3250. setAppearance: function (app) {
  3251. partAppearance = app || null;
  3252. refreshLooks();
  3253. },
  3254. // How models are shown (appearance.js normalizeScene)
  3255. setScene: function (s) {
  3256. sceneOpts = normalizeScene(s);
  3257. applyLighting();
  3258. groundDirty = true;
  3259. refreshLooks();
  3260. },
  3261. // The kernel's description of a picked face (type, centre, area,
  3262. // normal or axis), for appearance.js faceRef
  3263. faceInfo: function (item) {
  3264. const body = item && bodies[item.body];
  3265. return body && body.data.faces ? body.data.faces[item.index] || null : null;
  3266. },
  3267. // Where the camera is, to keep with a document tab, and back
  3268. viewState: currentView,
  3269. setViewState: function (s) {
  3270. if (!s) {
  3271. return;
  3272. }
  3273. animation = null;
  3274. setProjection(s.projection);
  3275. camera.position.fromArray(s.position);
  3276. camera.up.fromArray(s.up);
  3277. controls.target.fromArray(s.target);
  3278. if (camera === ortho) {
  3279. ortho.zoom = s.zoom;
  3280. ortho.updateProjectionMatrix();
  3281. }
  3282. camera.lookAt(controls.target);
  3283. controls.update();
  3284. invalidate();
  3285. },
  3286. // Look from `normal` (the side the camera goes to) with `up` up,
  3287. // the model fitted in the view (drawing views pick a direction so)
  3288. viewFrom: function (normal, up) {
  3289. flyTo(normal, up, true);
  3290. },
  3291. setVisualStyle: setVisualStyle,
  3292. setSection: setSection,
  3293. setSectionHandles: setSectionHandles,
  3294. // What dragging the left button does: "select" (nothing; it picks and
  3295. // draws), "orbit" or "pan"
  3296. setLeftDrag: function (action) {
  3297. leftDrag = action;
  3298. controls.mouseButtons.LEFT = leftButton();
  3299. canvas.style.cursor = hovered ? 'default' : restCursor();
  3300. },
  3301. // Is the left button lent to the view (so tools must leave it alone)?
  3302. isNavigating: function () {
  3303. return leftDrag !== 'select';
  3304. },
  3305. setProjection: setProjection,
  3306. projection: function () {
  3307. return camera === persp ? 'perspective' : 'orthographic';
  3308. },
  3309. home: home,
  3310. zoomAll: zoomAll,
  3311. lookAtPlane: lookAtPlane,
  3312. startPlanePick: startPlanePick,
  3313. stopPlanePick: stopPlanePick,
  3314. setHotPlane: setHotPlane,
  3315. setOriginVisible: setOriginVisible,
  3316. /* ---- assemblies ---- */
  3317. // Pick whole components (body groups) instead of faces and edges
  3318. setComponentMode: function (on) {
  3319. componentMode = !!on;
  3320. setHovered(null);
  3321. if (selection.some(function (item) {
  3322. return (item.type === 'body') !== componentMode;
  3323. })) {
  3324. setSelection([]);
  3325. }
  3326. },
  3327. // Move one body to a new placement without rebuilding anything
  3328. setBodyMatrix: function (index, matrix) {
  3329. if (bodies[index]) {
  3330. placeBody(bodies[index], matrix);
  3331. drawOverlays();
  3332. if (section.mode !== 'none') {
  3333. applySection();
  3334. }
  3335. }
  3336. },
  3337. // Many bodies at once: { index: matrix }
  3338. setBodyMatrices: function (map) {
  3339. Object.keys(map).forEach(function (index) {
  3340. if (bodies[index]) {
  3341. placeBody(bodies[index], map[index]);
  3342. }
  3343. });
  3344. drawOverlays();
  3345. if (section.mode !== 'none') {
  3346. applySection();
  3347. }
  3348. },
  3349. // Select raw items ({ type: "face" | "edge" | "body", body, index });
  3350. // quiet leaves the selection handlers uninformed
  3351. selectItems: function (items, quiet) {
  3352. selection = (items || []).slice();
  3353. drawOverlays();
  3354. if (!quiet) {
  3355. announceSelection();
  3356. }
  3357. },
  3358. // Light up components: { group: "hover" | "selected" }
  3359. setGroupTint: function (map) {
  3360. groupTints = map || {};
  3361. applyTints();
  3362. invalidate();
  3363. },
  3364. // The body under a screen point, and where on it: { body, group, point } or null
  3365. bodyAt: function (clientX, clientY) {
  3366. aim({ clientX: clientX, clientY: clientY });
  3367. const hit = raycaster.intersectObjects(bodies.filter(function (b) {
  3368. return !b.off;
  3369. }).map(function (b) {
  3370. return b.mesh;
  3371. }), false).filter(function (h) {
  3372. return !cutAway(h.point);
  3373. })[0];
  3374. if (!hit) {
  3375. return null;
  3376. }
  3377. const index = hit.object.userData.body;
  3378. return { body: index, group: groupOf(index), point: hit.point.toArray() };
  3379. },
  3380. // The origin plane under a screen point (only while they are shown)
  3381. originPlaneAt: function (clientX, clientY) {
  3382. return planeUnderPointer({ clientX: clientX, clientY: clientY });
  3383. },
  3384. // Where the pointer is on the plane through `point` square to the view
  3385. pointOnViewPlane: function (clientX, clientY, point) {
  3386. aim({ clientX: clientX, clientY: clientY });
  3387. const normal = new THREE.Vector3();
  3388. camera.getWorldDirection(normal);
  3389. const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(normal, new THREE.Vector3().fromArray(point));
  3390. const hit = new THREE.Vector3();
  3391. return raycaster.ray.intersectPlane(plane, hit) ? hit.toArray() : null;
  3392. },
  3393. // The screen directions in the world: right, up and into the screen
  3394. cameraBasis: function () {
  3395. camera.updateMatrixWorld();
  3396. const e = camera.matrixWorld.elements;
  3397. return { right: [e[0], e[1], e[2]], up: [e[4], e[5], e[6]], forward: [-e[8], -e[9], -e[10]] };
  3398. },
  3399. modelBounds: modelBounds,
  3400. sectionSpec: function () {
  3401. return Object.assign({}, section);
  3402. },
  3403. attachGizmo: attachGizmo,
  3404. detachGizmo: detachGizmo,
  3405. isGizmoDragging: function () {
  3406. return gizmoActive && gizmo.dragging;
  3407. },
  3408. setMeasure: setMeasure,
  3409. setMarkers: setMarkers,
  3410. setMeshes: setMeshes
  3411. });
  3412. return api;
  3413. }