app.js 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041
  1. /*
  2. 3D Modeler - application shell
  3. Wires the document, the kernel worker, the viewport, the model browser and
  4. the ribbon together (PROPOSAL.md milestone M1). The document is the single
  5. source of truth: every change to it triggers a rebuild in the worker, and
  6. the viewport and the browser are redrawn from the result.
  7. Three kinds of document share the window (state.env): a part, handled
  8. here, an assembly, handled by js/assembly/assembly.js, and a drawing
  9. (2D views on a sheet), handled by js/drawing/drawing.js. File > New
  10. asks which; opening a file picks by its format. Several documents can
  11. be open, one tab each under the view (see "document tabs" below). The ribbon shows the
  12. tabs of the open kind (ribbon.setMode), and the shared commands (files,
  13. view, Measure, Section View) ask activeDoc() which document they act on.
  14. jQuery and ao_module.js are classic scripts loaded by index.html; they are
  15. reached through window so this module also runs outside the ArozOS desktop.
  16. */
  17. import { createRibbon } from './ribbon.js';
  18. import { createViewport, ORIGIN_PLANES, orbitRing } from './viewport.js';
  19. import { createBrowser } from './browser.js';
  20. import { createKernel } from './kernel/client.js';
  21. import { createDocument } from './document/document.js';
  22. import { sampleDocument } from './document/sample.js';
  23. import { sampleAssembly } from './document/sampleasm.js';
  24. import { sampleDrawing } from './document/sampledrw.js';
  25. import { createAssembly } from './assembly/assembly.js';
  26. import { createDrawing } from './drawing/drawing.js';
  27. import { createMeasure } from './inspect/measure.js';
  28. import { createSectionPanel } from './inspect/section.js';
  29. import { createAppearancePanel } from './features/appearance.js';
  30. import { createPaintPanel } from './features/paint.js';
  31. import { createMaterialPanel, massOf } from './features/material.js';
  32. import { createParameterTable } from './features/paramtable.js';
  33. import { evaluateParameters, applyParameters } from './parameters.js';
  34. import { setScope } from './expr.js';
  35. import { normalizeScene, lightingById } from './appearance.js';
  36. import { toTextureImage, IMAGE_EXTENSIONS } from './io/image.js';
  37. import { askMeshExport } from './io/exportdialog.js';
  38. import { createOffsetBox } from './offsetbox.js';
  39. import * as files from './io/files.js';
  40. import * as native from './io/native.js';
  41. import * as preview from './io/preview.js';
  42. import { createLoading, megabytes, buildText } from './loading.js';
  43. import { toSTL, toSTLText, toOBJ, to3MF, meshCheck, scaled, parseSTL, parseOBJ, encodeMesh, decodeMesh, meshInfo } from './io/exchange.js';
  44. import * as solver from './sketch/solver.js';
  45. import { createSketcher } from './sketch/sketcher.js';
  46. import { addProjected, applyFollow } from './sketch/project.js';
  47. import { createExtrude } from './features/extrude.js';
  48. import { createRevolve } from './features/revolve.js';
  49. import { createShell } from './features/shell.js';
  50. import { createPattern } from './features/pattern.js';
  51. import { createEdgeFeature } from './features/edges.js';
  52. import { createHole } from './features/hole.js';
  53. import { createWorkFeature } from './features/workfeature.js';
  54. import { createRepair } from './features/repair.js';
  55. import { createSweep } from './features/sweep.js';
  56. import { createLoft } from './features/loft.js';
  57. import { createDraft } from './features/draft.js';
  58. import { createCheckPanel } from './inspect/check.js';
  59. import * as sketchModel from './sketch/model.js';
  60. import { sample } from './sketch/geom.js';
  61. import { planeFrame, toWorld, workPlaneFrame, resolveFace, resolveWork, workAxisLine, workPoint } from './kernel/profile.js';
  62. import { icon, openMenu, closeMenu, ask, tell, chooseNew } from './ui.js';
  63. import { createTabBar, freeName } from './tabs.js';
  64. import { validate as validatePart, sketchesOf } from './document/document.js';
  65. import { validateAssembly } from './assembly/document.js';
  66. import { validateDrawing } from './drawing/document.js';
  67. const $ = function (id) {
  68. return document.getElementById(id);
  69. };
  70. const state = {
  71. env: 'part', // the kind of document open: 'part' | 'assembly' | 'drawing'
  72. mode: 'model', // 'model' | 'pick-sketch-plane' | 'pick-lookat' | 'sketch' | 'feature'
  73. rebuildDeferred: false, // the document changed while a sketch was open
  74. rollbackAt: null, // an earlier sketch is edited: the model is shown as it was before it
  75. leftDrag: 'select', // what dragging the left button does: 'select' | 'orbit' | 'pan'
  76. originVisible: false,
  77. kernelReady: false,
  78. fitNext: false, // zoom to the part after the next rebuild (new or opened part)
  79. keepView: false, // a part tab shown again: keep the view it was left with
  80. pickText: null // the prompt while a plane is being picked
  81. };
  82. const doc = createDocument();
  83. /* ================= loading overlay ================= */
  84. // The kernel's start, and each document being opened, from reading its
  85. // file to its first build (loading.js), with the picture saved in the file
  86. const loading = createLoading($('splash'));
  87. const kernelTask = loading.start({ title: 'Starting the modelling kernel', text: 'Downloading...', delay: 0, blocking: true });
  88. let opening = null; // { task, tab, kind } while a document is being opened
  89. let restoring = null; // the task of an assembly or drawing shown again, reading its models
  90. function beginOpening(name) {
  91. endOpening();
  92. opening = { task: loading.start({ title: 'Opening ' + name, text: 'Reading the file' }), tab: null, kind: '' };
  93. return opening;
  94. }
  95. // which: only that opening (a later one may have taken its place)
  96. function endOpening(which) {
  97. if (opening && (!which || opening === which)) {
  98. opening.task.done();
  99. opening = null;
  100. }
  101. }
  102. // How far the assembly or drawing on show is with its models: { text,
  103. // fraction }, or null when everything is loaded
  104. function documentProgress(info) {
  105. const tab = activeTab;
  106. if (opening && (!opening.tab || opening.tab === tab)) {
  107. opening.tab = tab;
  108. if (info) {
  109. opening.task.update(info);
  110. } else {
  111. endOpening(opening);
  112. }
  113. return;
  114. }
  115. if (info) {
  116. if (!restoring) {
  117. restoring = loading.start({ title: 'Loading ' + (tab ? tabName(tab) : ''), delay: 400 });
  118. }
  119. restoring.update(info);
  120. } else if (restoring) {
  121. restoring.done();
  122. restoring = null;
  123. }
  124. }
  125. /* ================= status bar ================= */
  126. function setStatus(text) {
  127. $('status-msg').textContent = text;
  128. }
  129. function setPrompt(text) {
  130. $('prompt').hidden = !text;
  131. $('prompt').textContent = text || '';
  132. }
  133. function setEngine(id, cls, title) {
  134. const el = $(id);
  135. el.classList.remove('ok', 'bad');
  136. if (cls) {
  137. el.classList.add(cls);
  138. }
  139. el.title = title;
  140. }
  141. function mm(value, digits) {
  142. return value.toFixed(digits === undefined ? 2 : digits);
  143. }
  144. function describe(item) {
  145. if (item.kind === 'edge') {
  146. return 'Edge, length ' + mm(item.length) + ' mm';
  147. }
  148. if (item.kind !== 'face' || typeof item.area !== 'number') {
  149. return 'Body'; // a whole component; parts never pick these
  150. }
  151. const names = { plane: 'Planar face', cylinder: 'Cylindrical face', other: 'Face' };
  152. return (names[item.type] || 'Face') + ', area ' + mm(item.area) + ' mm2';
  153. }
  154. /* ================= theme ================= */
  155. function applyTheme(theme) {
  156. const dark = theme === 'dark';
  157. document.body.classList.toggle('dark', dark);
  158. document.querySelector('meta[name=theme-color]').setAttribute('content', dark ? '#1b1d21' : '#f3f4f6');
  159. try {
  160. window.ao_module_setWindowTheme(dark ? 'dark' : 'white');
  161. } catch (e) {
  162. // Not inside an ArozOS float window
  163. }
  164. }
  165. function initTheme() {
  166. if (native.available()) {
  167. // The Mac app follows the system's appearance, also when it changes
  168. const query = window.matchMedia('(prefers-color-scheme: dark)');
  169. applyTheme(query.matches ? 'dark' : 'light');
  170. query.addEventListener('change', function (event) {
  171. applyTheme(event.matches ? 'dark' : 'light');
  172. });
  173. return;
  174. }
  175. const inDesktop = !!window.ao_module_virtualDesktop;
  176. if (!inDesktop && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  177. applyTheme('dark');
  178. }
  179. files.hasBackend().then(function (ok) {
  180. if (!ok) {
  181. return; // the theme preference lives on the server
  182. }
  183. // The stored preference is "darkTheme" / "whiteTheme"
  184. window.ao_module_getSystemThemeColor(function (pref) {
  185. applyTheme(pref === 'darkTheme' || pref === 'dark' ? 'dark' : 'light');
  186. });
  187. });
  188. try {
  189. window.ao_module_onThemeChanged(applyTheme);
  190. } catch (e) {
  191. // Standalone page without ao_module
  192. }
  193. }
  194. /* ================= ribbon, viewport, browser ================= */
  195. const ribbon = createRibbon({ tabs: $('tabs'), panels: $('panels'), openMenu: openMenu }, onCommand);
  196. const viewport = createViewport({
  197. canvas: $('viewport'),
  198. viewCube: $('viewcube-cam'),
  199. triad: $('triad'),
  200. onHoverPlane: function (key) {
  201. browser.setHotPlane(key);
  202. if (state.pickText) {
  203. setStatus(key ? { xy: 'XY Plane', xz: 'XZ Plane', yz: 'YZ Plane' }[key] + ': click to use it' : state.pickText);
  204. }
  205. },
  206. onHover: function (item) {
  207. if (state.env === 'drawing') {
  208. drawing.onHover(item);
  209. return;
  210. }
  211. if (state.env === 'assembly') {
  212. if (!activeInspect) {
  213. assembly.onHover(item);
  214. }
  215. return;
  216. }
  217. if (state.mode === 'model') {
  218. setStatus(item ? describe(item) : selectionText());
  219. } else if (state.pickText) {
  220. // Waiting for a plane: say what the face under the pointer is
  221. setStatus(item ? describe(item) + ': click to use it' : state.pickText);
  222. }
  223. },
  224. onSelect: function (items) {
  225. if (state.env === 'drawing') {
  226. drawing.onSelect(items);
  227. return;
  228. }
  229. if (state.env === 'assembly') {
  230. assembly.onSelect(items);
  231. return;
  232. }
  233. if (state.mode === 'model') {
  234. setStatus(selectionText());
  235. }
  236. }
  237. });
  238. const browser = createBrowser($('tree'), doc, {
  239. onPlaneHover: function (key) {
  240. viewport.setHotPlane(key);
  241. },
  242. // A feature row hovered: outline in the model what it made
  243. onFeatureHover: function (id) {
  244. viewport.setFeatureMark(id);
  245. },
  246. onPlaneClick: function (key) {
  247. // A work feature panel waiting for a plane takes it
  248. if (viewport.offerRef({ kind: 'plane', target: { kind: 'origin', key: key } })) {
  249. return;
  250. }
  251. if (picking()) {
  252. viewport.stopPlanePick();
  253. planePicked({ kind: 'origin', key: key });
  254. }
  255. },
  256. onOriginClick: function (what) {
  257. if (what.axis) {
  258. const d = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }[what.axis];
  259. viewport.offerRef({ kind: 'axis', ref: { ref: 'origin:' + what.axis }, line: { o: [0, 0, 0], d: d } });
  260. } else {
  261. viewport.offerRef({ kind: 'point', ref: { ref: 'origin' }, at: [0, 0, 0] });
  262. }
  263. },
  264. onFeatureSelect: function (id) {
  265. // A work feature panel waiting for a plane, an axis or a point takes
  266. // a work feature clicked in the browser
  267. const work = id ? doc.feature(id) : null;
  268. if (work && !work.suppressed) {
  269. if (work.type === 'plane' && viewport.offerRef({ kind: 'plane', target: { kind: 'work', id: id } })) {
  270. return;
  271. }
  272. const line = work.type === 'axis' ? workAxisLine(work, doc.features()) : null;
  273. if (line && viewport.offerRef({ kind: 'axis', ref: { ref: 'axis', id: id }, line: line })) {
  274. return;
  275. }
  276. const at = work.type === 'point' ? workPoint(work, doc.features()) : null;
  277. if (at && viewport.offerRef({ kind: 'point', ref: { ref: 'point', id: id }, at: at })) {
  278. return;
  279. }
  280. }
  281. // While a pattern or mirror is set up, the browser picks what it repeats
  282. if (activeFeature && activeFeature.tool.pickFeature) {
  283. activeFeature.tool.pickFeature(id);
  284. return;
  285. }
  286. const feature = id && doc.feature(id);
  287. if (feature && state.mode === 'model') {
  288. const status = featureReport[id];
  289. setStatus(status && status.status === 'error' ? feature.name + ': ' + status.message : status && status.note ? feature.name + ': ' + status.note : feature.name);
  290. }
  291. },
  292. onFeatureAction: function (action, id, value) {
  293. const feature = doc.feature(id);
  294. if (!feature) {
  295. return;
  296. }
  297. if (action === 'rename') {
  298. doc.rename(id, value);
  299. } else if (action === 'suppress' || action === 'unsuppress') {
  300. doc.setSuppressed(id, action === 'suppress');
  301. } else if (action === 'hide' || action === 'show') {
  302. doc.setHidden(id, action === 'hide');
  303. setStatus(feature.name + (action === 'hide' ? ' hidden: the eye on its row (or Show in its right click menu) brings it back' : ' shown'));
  304. } else if (action === 'share' || action === 'unshare') {
  305. doc.setShared(id, action === 'share');
  306. setStatus(action === 'share' ? feature.name + ' is shared: its areas are offered again to Extrude, Revolve and Hole'
  307. : feature.name + ' is no longer shared');
  308. } else if (action === 'endhere') {
  309. doc.setEnd(id);
  310. setStatus(endStatus());
  311. } else if (action === 'delete') {
  312. deleteFeature(id);
  313. } else if (action === 'edit' && feature.type === 'sketch') {
  314. openSketch(id);
  315. } else if (action === 'editsketch' && doc.feature(feature.sketch)) {
  316. openSketch(feature.sketch);
  317. } else if (action === 'edit' && FEATURE_HINTS[toolKind(feature)]) {
  318. startFeature(toolKind(feature), id);
  319. } else if (action === 'edit') {
  320. setStatus(feature.name + ' cannot be edited in this version');
  321. }
  322. },
  323. // A row dragged to another place in the history
  324. onMoveFeature: function (id, beforeId, built) {
  325. const feature = doc.feature(id);
  326. const reason = doc.canMove(id, beforeId);
  327. if (!feature) {
  328. return;
  329. }
  330. if (reason) {
  331. setStatus(feature.name + ' cannot go there: ' + reason);
  332. return;
  333. }
  334. if (doc.move(id, beforeId, built)) {
  335. setStatus(feature.name + ' moved' + (doc.features().indexOf(doc.feature(id)) > doc.endIndex() ? ' below End of Part: it is not built until End of Part is moved past it' : ''));
  336. }
  337. },
  338. // End of Part dropped: after a feature, above them all ("") or at the bottom (null)
  339. onMoveEnd: function (afterId) {
  340. doc.setEnd(afterId);
  341. setStatus(endStatus());
  342. },
  343. onBodyVisibility: function (index, hidden) {
  344. doc.setBodyHidden(index, hidden);
  345. setStatus('Solid' + (index + 1) + (hidden ? ' hidden: the eye on its row brings it back' : ' shown'));
  346. },
  347. onHint: function (text) {
  348. setStatus(text || 'Ready');
  349. }
  350. });
  351. // What End of Part leaves out, for the status bar
  352. function endStatus() {
  353. const list = doc.features();
  354. const out = list.length - 1 - doc.endIndex();
  355. return out > 0 ? 'End of Part moved: ' + out + (out === 1 ? ' feature below it is' : ' features below it are') +
  356. ' not built, and new features are added there. Right-click End of Part > Move to End to build them all again.'
  357. : 'End of Part is at the bottom: every feature is built';
  358. }
  359. /* ================= sketcher ================= */
  360. // Ribbon button of each sketch tool, to show which one is active
  361. const TOOL_BUTTONS = {
  362. line: 'sk.line', rect: 'sk.rect', circle: 'sk.circle', arc: 'sk.arcs', arc3: 'sk.arcs', arctan: 'sk.arcs', point: 'sk.point',
  363. fillet: 'sk.fillet', chamfer: 'sk.chamfer', 'con:concentric': 'con.concentric',
  364. mirror: 'sk.mirror', polygon: 'sk.polygon', slot: 'sk.slot',
  365. trim: 'sk.trim', extend: 'sk.extend', dimension: 'sk.dimension', project: 'sk.project',
  366. 'con:coincident': 'con.coincident', 'con:collinear': 'con.collinear', 'con:horizontal': 'con.horizontal', 'con:vertical': 'con.vertical',
  367. 'con:parallel': 'con.parallel', 'con:perpendicular': 'con.perpendicular', 'con:tangent': 'con.tangent',
  368. 'con:equal': 'con.equal', 'con:fix': 'con.fix', 'con:midpoint': 'con.midpoint', 'con:symmetric': 'con.symmetric'
  369. };
  370. let activeTool = 'select';
  371. const sketcher = createSketcher({
  372. stage: $('stage'),
  373. canvas: $('viewport'),
  374. viewport: viewport,
  375. doc: doc,
  376. onPrompt: setPrompt,
  377. onStatus: setStatus,
  378. onState: function (s) {
  379. activeTool = s.tool;
  380. // Several tools share a button (the three arcs): light the one in use
  381. const on = TOOL_BUTTONS[s.tool];
  382. Object.values(TOOL_BUTTONS).forEach(function (button) {
  383. ribbon.setOn(button, button === on);
  384. });
  385. ribbon.setOn('sk.construction', s.construction);
  386. }
  387. });
  388. // Sketches nothing has been built from yet are drawn in the model, so they
  389. // can be seen and picked; the one open in the sketcher draws itself.
  390. function refreshSketches() {
  391. const limit = Math.min(rollbackIndex(), doc.endIndex() + 1);
  392. // A sketch used only by features after the rolled back point (or below
  393. // End of Part) is unused there; a shared one is always drawn
  394. const used = new Set([].concat.apply([], doc.features().filter(function (f, i) {
  395. return i < limit;
  396. }).map(sketchesOf)));
  397. const list = [];
  398. doc.features().forEach(function (feature, i) {
  399. const frame = feature.type === 'sketch' && i <= Math.min(rollbackIndex(), doc.endIndex()) && !feature.hidden ? planeFrame(feature.plane, doc.features()) : null;
  400. if (!frame || feature.suppressed || (used.has(feature.id) && !feature.shared) || feature.id === sketcher.featureId()) {
  401. return;
  402. }
  403. const out = [];
  404. sketchModel.curves(sketchModel.clone(feature)).forEach(function (curve) {
  405. const pts = sample(curve).map(function (p) {
  406. return toWorld(frame, p[0], p[1]);
  407. });
  408. for (let i = 1; i < pts.length; i++) {
  409. out.push(pts[i - 1][0], pts[i - 1][1], pts[i - 1][2], pts[i][0], pts[i][1], pts[i][2]);
  410. }
  411. });
  412. list.push({ id: feature.id, segments: new Float32Array(out) });
  413. });
  414. viewport.setSketches(list);
  415. refreshMeshes();
  416. }
  417. // Reference meshes (STL / OBJ brought in) are drawn pale; decoded once
  418. const decodedMeshes = new Map(); // feature id -> { stored, mesh }
  419. function refreshMeshes() {
  420. const limit = Math.min(rollbackIndex(), doc.endIndex());
  421. const list = [];
  422. doc.features().forEach(function (feature, i) {
  423. if (feature.type !== 'mesh' || feature.suppressed || feature.hidden || i > limit || !feature.data) {
  424. return;
  425. }
  426. let entry = decodedMeshes.get(feature.id);
  427. if (!entry || entry.stored !== feature.data) {
  428. try {
  429. entry = { stored: feature.data, mesh: decodeMesh(feature.data) };
  430. } catch (err) {
  431. entry = { stored: feature.data, mesh: null };
  432. }
  433. decodedMeshes.set(feature.id, entry);
  434. }
  435. if (entry.mesh) {
  436. list.push({ id: feature.id, positions: entry.mesh.positions, indices: entry.mesh.indices });
  437. }
  438. });
  439. viewport.setMeshes(state.env === 'part' ? list : []);
  440. }
  441. // Work planes, axes and points are drawn in the model; the drafts are the
  442. // one being set up in its panel ({ frame } / { line } / { at }, with the
  443. // id of the feature it replaces while editing)
  444. let draftPlane = null;
  445. let draftAxis = null;
  446. let draftPoint = null;
  447. function refreshWorkPlanes() {
  448. const limit = Math.min(rollbackIndex(), doc.endIndex() + 1);
  449. const list = [];
  450. const axes = [];
  451. const points = [];
  452. const features = doc.features();
  453. features.forEach(function (feature, i) {
  454. if (feature.suppressed || feature.hidden || i >= limit) {
  455. return;
  456. }
  457. // One being edited is shown by its draft instead
  458. if (feature.type === 'plane' && !(draftPlane && draftPlane.id === feature.id)) {
  459. const frame = workPlaneFrame(feature, features);
  460. if (frame) {
  461. list.push({ id: feature.id, frame: frame });
  462. }
  463. } else if (feature.type === 'axis' && !(draftAxis && draftAxis.id === feature.id)) {
  464. const line = workAxisLine(feature, features);
  465. if (line) {
  466. axes.push({ id: feature.id, o: line.o, d: line.d });
  467. }
  468. } else if (feature.type === 'point' && !(draftPoint && draftPoint.id === feature.id)) {
  469. const at = workPoint(feature, features);
  470. if (at) {
  471. points.push({ id: feature.id, at: at });
  472. }
  473. }
  474. });
  475. if (draftPlane) {
  476. list.push({ id: null, frame: draftPlane.frame, draft: true });
  477. }
  478. if (draftAxis) {
  479. axes.push({ id: null, o: draftAxis.line.o, d: draftAxis.line.d, draft: true });
  480. }
  481. if (draftPoint) {
  482. points.push({ id: null, at: draftPoint.at, draft: true });
  483. }
  484. viewport.setWorkPlanes(list);
  485. viewport.setWorkAxes(axes);
  486. viewport.setWorkPoints(points);
  487. }
  488. // The coordinate system of a sketch on a picked planar face: X runs level
  489. // (or along world X on a horizontal face), the origin is the point of the
  490. // plane nearest the part origin, so sketch and model coordinates line up.
  491. // Sketches and work planes on faces, where the rebuild found the faces now
  492. function takeFaceFrames(frames, lines) {
  493. Object.keys(frames || {}).forEach(function (id) {
  494. const feature = doc.feature(id);
  495. if (feature) {
  496. resolveFace(feature.type === 'plane' ? feature.base : feature.plane, frames[id]);
  497. }
  498. });
  499. // Work axes (and tangent planes) on edges and round faces, where the
  500. // rebuild found them now
  501. Object.keys(lines || {}).forEach(function (id) {
  502. resolveWork(doc.feature(id), lines[id]);
  503. });
  504. }
  505. function faceFrame(target) {
  506. const n = target.normal;
  507. const d = n[0] * target.origin[0] + n[1] * target.origin[1] + n[2] * target.origin[2];
  508. let x = [1, 0, 0];
  509. if (Math.abs(n[2]) < 0.99) {
  510. const len = Math.hypot(n[0], n[1]);
  511. x = [-n[1] / len, n[0] / len, 0];
  512. }
  513. const y = [n[1] * x[2] - n[2] * x[1], n[2] * x[0] - n[0] * x[2], n[0] * x[1] - n[1] * x[0]];
  514. return { o: [n[0] * d, n[1] * d, n[2] * d], x: x, y: y, n: n };
  515. }
  516. // Where the model is rolled back to while an earlier sketch is edited:
  517. // features after it are not shown (Infinity when nothing is rolled back)
  518. function rollbackIndex() {
  519. if (!state.rollbackAt) {
  520. return Infinity;
  521. }
  522. const i = doc.features().findIndex(function (f) {
  523. return f.id === state.rollbackAt;
  524. });
  525. return i < 0 ? Infinity : i;
  526. }
  527. // Editing a sketch that features come after: show the model as it was
  528. // before the sketch, so later solids, sketches and planes are out of the way
  529. // (and cannot be picked or projected, which would loop back on the sketch)
  530. function rollBackTo(id) {
  531. const features = doc.features();
  532. const at = features.findIndex(function (f) {
  533. return f.id === id;
  534. });
  535. const later = features.slice(at + 1).some(function (f) {
  536. return !f.suppressed;
  537. });
  538. if (at < 0 || !later) {
  539. return;
  540. }
  541. state.rollbackAt = id;
  542. browser.setRollback(id);
  543. refreshWorkPlanes();
  544. kernel.call('rebuild', { document: doc.data(), upto: id }).then(function (result) {
  545. if (state.rollbackAt !== id || state.env !== 'part') {
  546. return; // closed again, or another document is on show
  547. }
  548. takeFaceFrames(result.frames, result.lines);
  549. viewport.setBodies(result.bodies);
  550. }).catch(function (err) {
  551. setStatus('The model could not be rolled back: ' + err.message);
  552. });
  553. }
  554. function openSketch(id) {
  555. if (picking()) {
  556. leaveMode();
  557. }
  558. if (sketcher.isOpen()) {
  559. closeSketch();
  560. }
  561. sketcher.open(id).then(function (ok) {
  562. if (!ok) {
  563. setStatus('This sketch cannot be opened: the plane it was drawn on is missing');
  564. if (state.rebuildDeferred) {
  565. requestRebuild();
  566. }
  567. return;
  568. }
  569. state.mode = 'sketch';
  570. viewport.clearSelection();
  571. viewport.setOriginVisible(false);
  572. rollBackTo(id);
  573. viewport.lookAlong(sketcher.frame().n);
  574. ribbon.setTabVisible('sketch', true);
  575. ribbon.showTab('sketch');
  576. browser.setEditing(id);
  577. refreshSketches();
  578. });
  579. }
  580. // Leave the sketch environment. The model is rebuilt now, not on every
  581. // stroke, because features built from the sketch may be slow to recompute.
  582. function closeSketch() {
  583. if (!sketcher.isOpen()) {
  584. return;
  585. }
  586. sketcher.close();
  587. state.mode = 'model';
  588. viewport.setOriginVisible(state.originVisible);
  589. ribbon.setTabVisible('sketch', false);
  590. ribbon.showTab('model');
  591. browser.setEditing(null);
  592. if (state.rollbackAt) {
  593. // The whole model comes back with the next rebuild (finishSketch,
  594. // or the change that closed the sketch)
  595. state.rollbackAt = null;
  596. state.rebuildDeferred = true;
  597. state.keepView = true; // the solids coming back are not a new part to zoom to
  598. browser.setRollback(null);
  599. refreshSketches();
  600. refreshWorkPlanes();
  601. }
  602. setPrompt('');
  603. setStatus('Ready');
  604. }
  605. /* ================= feature panels ================= */
  606. // What the status bar says while a new feature of each kind is set up
  607. const FEATURE_HINTS = {
  608. extrude: 'Extrude: pick a profile, choose how far it goes (Distance, To a plane, To Next, Through All), then OK',
  609. revolve: 'Revolve: pick a profile and the axis line to turn it about, then OK',
  610. shell: 'Shell: click the faces to leave open, set the wall thickness, then OK',
  611. rectpattern: 'Rectangular Pattern: click the features to repeat in the browser, set the directions, then OK',
  612. circpattern: 'Circular Pattern: click the features to repeat in the browser, pick the axis, then OK',
  613. mirror: 'Mirror: click the features to mirror in the browser (none: the whole solid), pick the plane, then OK',
  614. fillet: 'Fillet: click the edges to round, set the radius (Add a set for edges with another radius), then OK',
  615. chamfer: 'Chamfer: choose the type, click the edges to break, set the sizes, then OK',
  616. hole: 'Hole: place it at sketch points or by two edges (Linear), set the type, size and thread, then OK',
  617. plane: 'Work Plane: pick what it is defined by in the model, set the values, then OK',
  618. axis: 'Work Axis: pick an edge, a round face, two planes or two points, then OK',
  619. point: 'Work Point: pick a corner, type coordinates, or pick an axis and a plane, then OK',
  620. repair: 'Repair: the solid is checked and healed (gaps, slivers, open edges); compare before and after, then OK',
  621. sweep: 'Sweep: pick a profile, then the path (curves of another sketch), then OK',
  622. loft: 'Loft: click a closed area of each section sketch in order, choose Smooth or Ruled, then OK',
  623. draft: 'Draft: click the faces to tilt, pick the fixed plane, set the angle, then OK'
  624. };
  625. let activeFeature = null; // { kind, tool, rolledBack } while a feature panel is open
  626. // The ribbon button of a feature kind
  627. function featureButton(kind) {
  628. return { plane: 'work.plane', axis: 'work.axis', point: 'work.point', rectpattern: 'pat.rect', circpattern: 'pat.circ', mirror: 'pat.mirror' }[kind] || 'feat.' + kind;
  629. }
  630. // The panel kind that edits a feature (patterns come in two kinds)
  631. function toolKind(feature) {
  632. return feature.type === 'pattern' ? (feature.kind === 'circ' ? 'circpattern' : 'rectpattern') : feature.type;
  633. }
  634. // Open a feature panel: for a new feature, or to edit one (featureId).
  635. // While a feature is edited the model is shown as it was before it, so what
  636. // the feature was built on can be seen and picked again.
  637. function startFeature(kind, featureId) {
  638. if (picking()) {
  639. leaveMode();
  640. }
  641. if (sketcher.isOpen()) {
  642. finishSketch(); // as in desktop CAD, a feature command inside a sketch finishes it first
  643. }
  644. // A feature already open (the same one opened twice): closed first, so
  645. // the whole model it asks back for is drawn before this one rolls back
  646. if (activeFeature) {
  647. activeFeature.tool.cancel();
  648. }
  649. const tool = featureTools[kind];
  650. const preselected = viewport.selection();
  651. viewport.clearSelection();
  652. const shown = featureId ? kernel.call('rebuild', { document: doc.data(), upto: featureId }).then(function (result) {
  653. takeFaceFrames(result.frames, result.lines);
  654. viewport.setBodies(result.bodies);
  655. }) : Promise.resolve();
  656. shown.then(function () {
  657. // Fillet and chamfer pick edges of the model; the others must not react to it
  658. viewport.setPicking(['fillet', 'chamfer', 'shell', 'draft', 'rectpattern', 'circpattern', 'mirror'].indexOf(kind) >= 0);
  659. return tool.start(featureId || null, preselected, browser.selected());
  660. }).then(function (ok) {
  661. if (!ok) {
  662. viewport.setPicking(true);
  663. if (featureId) {
  664. requestRebuild(); // put the full model back
  665. }
  666. return;
  667. }
  668. activeFeature = { kind: kind, tool: tool, rolledBack: !!featureId };
  669. state.mode = 'feature';
  670. ribbon.showTab('model');
  671. ribbon.setOn(featureButton(kind), true);
  672. setStatus(featureId ? 'Editing ' + doc.feature(featureId).name + ': change the values, then OK' : FEATURE_HINTS[kind]);
  673. }).catch(function (err) {
  674. setStatus('The feature could not be opened: ' + err.message);
  675. requestRebuild();
  676. });
  677. }
  678. function featureClosed(kind) {
  679. const was = activeFeature;
  680. activeFeature = null;
  681. if (was && was.tool.pickFeature) {
  682. // The browser picked what a pattern repeats; that pick is done with
  683. browser.select(null);
  684. }
  685. state.mode = sketcher.isOpen() ? 'sketch' : 'model';
  686. ribbon.setOn(featureButton(kind), false);
  687. viewport.setPicking(true);
  688. setStatus('Ready');
  689. if (was && was.rolledBack) {
  690. requestRebuild(); // show the whole model again
  691. }
  692. }
  693. function finishSketch() {
  694. // Turn to the face the sketch is on, at an angle, so an extrusion out of
  695. // it shows (also when Extrude is what finished the sketch)
  696. const frame = sketcher.isOpen() ? sketcher.frame() : null;
  697. closeSketch();
  698. refreshSketches();
  699. if (frame && frame.n) {
  700. viewport.viewFace(frame.n);
  701. } else {
  702. viewport.home();
  703. }
  704. if (state.rebuildDeferred) {
  705. requestRebuild();
  706. }
  707. }
  708. function selectionText() {
  709. const items = viewport.selection();
  710. if (!items.length) {
  711. return 'Ready';
  712. }
  713. if (items.length === 1) {
  714. return 'Selected: ' + describe(items[0]);
  715. }
  716. const faces = items.filter(function (i) {
  717. return i.kind === 'face';
  718. }).length;
  719. return 'Selected: ' + faces + ' face' + (faces === 1 ? '' : 's') + ', ' + (items.length - faces) + ' edge' + (items.length - faces === 1 ? '' : 's');
  720. }
  721. /* ================= quick access + navigation bar ================= */
  722. function iconButton(parent, id, iconName, title) {
  723. const button = document.createElement('button');
  724. button.className = 'qa-btn';
  725. button.title = title;
  726. button.innerHTML = icon(iconName);
  727. button.addEventListener('click', function () {
  728. onCommand(id);
  729. });
  730. parent.appendChild(button);
  731. return button;
  732. }
  733. iconButton($('quickaccess'), 'file.new', 'new', 'New');
  734. iconButton($('quickaccess'), 'file.open', 'open', 'Open (Ctrl+O)');
  735. iconButton($('quickaccess'), 'file.save', 'save', 'Save (Ctrl+S)');
  736. const undoButton = iconButton($('quickaccess'), 'edit.undo', 'undo', 'Undo (Ctrl+Z)');
  737. const redoButton = iconButton($('quickaccess'), 'edit.redo', 'redo', 'Redo (Ctrl+Y)');
  738. $('viewcube-home').addEventListener('click', function () {
  739. onCommand('nav.home');
  740. });
  741. iconButton($('navbar'), 'nav.zoomall', 'zoomall', 'Zoom All');
  742. iconButton($('navbar'), 'nav.home', 'home', 'Home View');
  743. iconButton($('navbar'), 'nav.lookat', 'lookat', 'Look At');
  744. const orbitButton = iconButton($('navbar'), 'nav.orbit', 'orbit', 'Orbit: drag with the left button inside the circle to turn the view, outside it to roll the view (or hold F4; Shift + middle button turns it)');
  745. const panButton = iconButton($('navbar'), 'nav.pan', 'pan', 'Pan: drag with the left button to move the view (or drag with the middle button)');
  746. // Lend the left button to the view ('orbit' or 'pan'), or give it back ('select')
  747. function setLeftDrag(mode) {
  748. state.leftDrag = mode;
  749. viewport.setLeftDrag(mode);
  750. ribbon.setOn('nav.pan', mode === 'pan');
  751. ribbon.setOn('nav.orbit', mode === 'orbit');
  752. orbitButton.classList.toggle('on', mode === 'orbit');
  753. panButton.classList.toggle('on', mode === 'pan');
  754. drawOrbitMark();
  755. }
  756. // Orbit and Pan are for looking around. Commands that only move the
  757. // camera or restyle the view leave them on; any other command gives the
  758. // left button back to selecting, so the tool it starts can pick at once
  759. // (a chamfer its edges, a sketch its plane). So does working in a tool's
  760. // panel or in the model browser: a click on a chamfer's edge selector
  761. // means the next click in the view picks an edge.
  762. const VIEW_ONLY_COMMANDS = /^(nav\.(pan|orbit|zoomall|home)|style\.|proj\.|view\.origin$)/;
  763. function releaseLeftButton() {
  764. if (state.leftDrag === 'select') {
  765. return;
  766. }
  767. const was = state.leftDrag;
  768. heldOrbit = null; // letting go of F4 later brings nothing back
  769. setLeftDrag('select');
  770. setStatus((was === 'orbit' ? 'Orbit' : 'Pan') + ' off: the left button selects again');
  771. }
  772. ['pointerdown', 'focusin'].forEach(function (type) {
  773. document.addEventListener(type, function (event) {
  774. const target = event.target;
  775. if (state.leftDrag !== 'select' && target && target.closest && target.closest('.props, #browser')) {
  776. releaseLeftButton();
  777. }
  778. }, true);
  779. });
  780. // The circle shown over the model while the left button orbits: four
  781. // ticks outside it at the quarters and a small cross in the middle. Its
  782. // zones (inside, outside, the ticks) are in viewport.js orbitRing().
  783. function drawOrbitMark() {
  784. const mark = $('orbit-mark');
  785. // An SVG element has no `hidden` property: set the attribute itself
  786. const off = state.leftDrag !== 'orbit';
  787. mark.toggleAttribute('hidden', off);
  788. if (off) {
  789. return;
  790. }
  791. const w = $('stage').clientWidth;
  792. const h = $('stage').clientHeight;
  793. const ring = orbitRing(w, h);
  794. const cx = ring.cx;
  795. const cy = ring.cy;
  796. const r = ring.r;
  797. const t = ring.tick;
  798. const c = 30;
  799. mark.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  800. mark.innerHTML = '<circle cx="' + cx + '" cy="' + cy + '" r="' + r + '"/>' +
  801. '<path d="M' + cx + ' ' + (cy - r - t) + 'V' + (cy - r) + 'M' + cx + ' ' + (cy + r) + 'V' + (cy + r + t) +
  802. 'M' + (cx - r - t) + ' ' + cy + 'H' + (cx - r) + 'M' + (cx + r) + ' ' + cy + 'H' + (cx + r + t) +
  803. 'M' + (cx - c) + ' ' + cy + 'H' + (cx + c) + 'M' + cx + ' ' + (cy - c) + 'V' + (cy + c) + '"/>';
  804. }
  805. if (window.ResizeObserver) {
  806. new ResizeObserver(drawOrbitMark).observe($('stage'));
  807. }
  808. /* ================= document -> rebuild -> display ================= */
  809. let featureReport = {};
  810. let rebuildRunning = false;
  811. let rebuildWanted = false;
  812. let lastFailed = false;
  813. let lastFailureText = ''; // what the status bar said about them
  814. // The document the shared commands (files, undo, title) act on
  815. function activeDoc() {
  816. return state.env === 'assembly' ? assembly.doc : state.env === 'drawing' ? drawing.doc : doc;
  817. }
  818. // What each kind of document is saved as
  819. const EXT = { part: '.aopart', assembly: '.aoasm', drawing: '.aodrw' };
  820. const KIND_NAMES = { part: 'part', assembly: 'assembly', drawing: 'drawing' };
  821. /* ================= document tabs ================= */
  822. // Every open document has a tab under the view (js/tabs.js). The shown one
  823. // lives in its environment's document (doc, assembly.doc, drawing.doc); the
  824. // others are kept as snapshots, undo history and view included, and come
  825. // back when their tab is clicked. Each tab has its own key space in the
  826. // kernel, so its solids, assembly parts and drawing views are found cached
  827. // when it is shown again. Assemblies and drawings read the parts they use
  828. // through files.readPath, which hands out a document open in a tab as it is
  829. // there (unsaved edits too): showing their tab again brings the edits in.
  830. const tabs = []; // { id, kind, snap, view }
  831. let activeTab = null;
  832. let tabSeq = 0;
  833. const tabBar = createTabBar($('doctabs'), {
  834. onSelect: function (id) {
  835. switchTo(tabById(id));
  836. },
  837. onClose: function (id) {
  838. const tab = tabById(id);
  839. if (tab) {
  840. closeTab(tab);
  841. }
  842. },
  843. onNew: function () {
  844. newDocument();
  845. }
  846. });
  847. function tabById(id) {
  848. return tabs.filter(function (t) {
  849. return t.id === id;
  850. })[0] || null;
  851. }
  852. function docOf(kind) {
  853. return kind === 'assembly' ? assembly.doc : kind === 'drawing' ? drawing.doc : doc;
  854. }
  855. function tabName(tab) {
  856. return tab === activeTab ? docOf(tab.kind).name : tab.snap ? tab.snap.name : '';
  857. }
  858. function tabPath(tab) {
  859. return tab === activeTab ? docOf(tab.kind).path : tab.snap ? tab.snap.path : '';
  860. }
  861. function tabDirty(tab) {
  862. return tab === activeTab ? docOf(tab.kind).isDirty() : !!tab.snap && tab.snap.data !== tab.snap.saved;
  863. }
  864. function tabData(tab) {
  865. return tab === activeTab ? docOf(tab.kind).data() : JSON.parse(tab.snap.data);
  866. }
  867. function renderTabs() {
  868. tabBar.render(tabs.map(function (t) {
  869. return { id: t.id, kind: t.kind, name: tabName(t), path: files.displayPath(tabPath(t)), dirty: tabDirty(t) };
  870. }), activeTab ? activeTab.id : null);
  871. scheduleAutosave();
  872. }
  873. /* ================= autosave ================= */
  874. // Unsaved documents are copied to the browser's storage a moment after each
  875. // change, so a crash or a closed browser tab does not lose them: the next
  876. // start offers them back. Each window has an entry of its own and keeps an
  877. // "alive" stamp fresh while it runs, so a window still open elsewhere is
  878. // never offered (PROPOSAL.md 14.8, 14.26).
  879. const AUTOSAVE_PREFIX = '3dmodeler.autosave.';
  880. const AUTOSAVE_KEY = AUTOSAVE_PREFIX + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
  881. const AUTOSAVE_STALE = 15000; // ms without an alive stamp: that window is gone
  882. let autosaveTimer = null;
  883. let autosaveOn = false; // this window has an entry
  884. let autosaveClosed = false; // closed on purpose: nothing more is kept
  885. function autosaveStore() {
  886. try {
  887. return window.localStorage || null;
  888. } catch (e) {
  889. return null; // storage blocked: no autosave
  890. }
  891. }
  892. function writeAutosave() {
  893. clearTimeout(autosaveTimer);
  894. autosaveTimer = null;
  895. const store = autosaveStore();
  896. if (!store || autosaveClosed) {
  897. return;
  898. }
  899. const dirty = tabs.filter(tabDirty);
  900. try {
  901. if (!dirty.length) {
  902. dropAutosave(AUTOSAVE_KEY);
  903. autosaveOn = false;
  904. return;
  905. }
  906. store.setItem(AUTOSAVE_KEY, JSON.stringify({
  907. time: Date.now(),
  908. tabs: dirty.map(function (t) {
  909. return { kind: t.kind, name: tabName(t), path: tabPath(t), text: JSON.stringify(tabData(t)) };
  910. })
  911. }));
  912. store.setItem(AUTOSAVE_KEY + '.alive', String(Date.now()));
  913. autosaveOn = true;
  914. } catch (e) {
  915. // full or blocked: this change is not kept
  916. }
  917. }
  918. function dropAutosave(key) {
  919. const store = autosaveStore();
  920. try {
  921. if (store) {
  922. store.removeItem(key);
  923. store.removeItem(key + '.alive');
  924. }
  925. } catch (e) {
  926. // nothing to drop
  927. }
  928. }
  929. function scheduleAutosave() {
  930. if (!autosaveTimer) {
  931. autosaveTimer = setTimeout(writeAutosave, 1500);
  932. }
  933. }
  934. // The alive stamp, while this window has unsaved work stored
  935. setInterval(function () {
  936. const store = autosaveStore();
  937. if (autosaveOn && store) {
  938. try {
  939. store.setItem(AUTOSAVE_KEY + '.alive', String(Date.now()));
  940. } catch (e) {
  941. // storage went away
  942. }
  943. }
  944. }, 5000);
  945. // Entries left by windows that are gone: [{ key, time, tabs }]
  946. function orphanedAutosaves() {
  947. const store = autosaveStore();
  948. const out = [];
  949. if (!store) {
  950. return out;
  951. }
  952. try {
  953. for (let i = 0; i < store.length; i++) {
  954. const key = store.key(i);
  955. if (!key || key.indexOf(AUTOSAVE_PREFIX) !== 0 || /\.alive$/.test(key) || key === AUTOSAVE_KEY) {
  956. continue;
  957. }
  958. const alive = Number(store.getItem(key + '.alive')) || 0;
  959. if (Date.now() - alive < AUTOSAVE_STALE) {
  960. out.pending = true; // another window still open, or one that just stopped
  961. continue;
  962. }
  963. try {
  964. const entry = JSON.parse(store.getItem(key));
  965. if (entry && Array.isArray(entry.tabs) && entry.tabs.length) {
  966. out.push({ key: key, time: entry.time, tabs: entry.tabs });
  967. continue;
  968. }
  969. } catch (e) {
  970. // unreadable: dropped below
  971. }
  972. out.push({ key: key, tabs: [] });
  973. }
  974. } catch (e) {
  975. return [];
  976. }
  977. return out;
  978. }
  979. // On start: offer what a crashed or closed window did not save. An entry
  980. // whose stamp is still fresh is looked at again once it would be stale.
  981. let autosaveChecks = 0;
  982. function offerAutosaves() {
  983. const found = orphanedAutosaves();
  984. if (found.pending && ++autosaveChecks < 2) {
  985. setTimeout(offerAutosaves, AUTOSAVE_STALE + 1000);
  986. }
  987. const usable = found.filter(function (f) {
  988. return f.tabs.length;
  989. });
  990. found.filter(function (f) {
  991. return !f.tabs.length;
  992. }).forEach(function (f) {
  993. dropAutosave(f.key);
  994. });
  995. if (!usable.length) {
  996. return;
  997. }
  998. const docs = [].concat.apply([], usable.map(function (f) {
  999. return f.tabs;
  1000. }));
  1001. const when = Math.max.apply(null, usable.map(function (f) {
  1002. return f.time || 0;
  1003. }));
  1004. const names = docs.map(function (d) {
  1005. return d.name + (d.path ? ' (' + files.displayPath(d.path) + ')' : ' (never saved)');
  1006. });
  1007. ask('Restore unsaved work?', '3D Modeler was closed' + (when ? ' at ' + new Date(when).toLocaleString() : '') +
  1008. ' with changes that were not saved:\n\n' + names.join('\n') +
  1009. '\n\nRestore opens them in tabs, still unsaved, so you can look and save them. Discard throws them away.', [
  1010. { label: 'Discard', value: false },
  1011. { label: 'Restore', value: true, primary: true }
  1012. ], null).then(function (answer) {
  1013. if (answer === null) {
  1014. return; // asked again next time
  1015. }
  1016. if (answer) {
  1017. let restored = 0;
  1018. docs.forEach(function (d) {
  1019. try {
  1020. if (loadDocument(JSON.parse(d.text), d.name, d.path)) {
  1021. docOf(d.kind).markUnsaved();
  1022. restored++;
  1023. }
  1024. } catch (e) {
  1025. // a document that cannot be read is skipped
  1026. }
  1027. });
  1028. refreshChrome();
  1029. setStatus('Restored ' + restored + (restored === 1 ? ' document' : ' documents') + ': save to keep the changes');
  1030. }
  1031. usable.forEach(function (f) {
  1032. dropAutosave(f.key);
  1033. });
  1034. });
  1035. }
  1036. // An empty document nobody has touched: a file opened next takes its place
  1037. function isPristine(tab) {
  1038. if (tab !== activeTab || tabDirty(tab) || tabPath(tab)) {
  1039. return false;
  1040. }
  1041. if (tab.kind === 'assembly') {
  1042. return !assembly.doc.components().length;
  1043. }
  1044. if (tab.kind === 'drawing') {
  1045. return !drawing.doc.views().length && !drawing.doc.annotations().length;
  1046. }
  1047. return !doc.features().length;
  1048. }
  1049. // Put away whatever is open in the shown document before another is shown
  1050. function leaveDocument() {
  1051. closeInspect(true);
  1052. if (activeFeature) {
  1053. activeFeature.tool.cancel();
  1054. }
  1055. appearanceTool.cancel();
  1056. paintTool.cancel();
  1057. if (picking()) {
  1058. leaveMode();
  1059. }
  1060. if (sketcher.isOpen()) {
  1061. closeSketch();
  1062. }
  1063. if (state.env === 'assembly') {
  1064. assembly.stopTools();
  1065. } else if (state.env === 'drawing') {
  1066. drawing.stopTools();
  1067. }
  1068. setLeftDrag('select');
  1069. viewport.setSection('none');
  1070. ribbon.setLabel('view.section', 'Section View');
  1071. viewport.setPreview(null);
  1072. viewport.clearSelection();
  1073. setPrompt('');
  1074. }
  1075. // F5 Previous View: the views before each change of view, newest last
  1076. // (viewport.onViewChange); started over with every tab switch
  1077. const viewHistory = [];
  1078. viewport.onViewChange = function (view) {
  1079. viewHistory.push(view);
  1080. if (viewHistory.length > 30) {
  1081. viewHistory.shift();
  1082. }
  1083. };
  1084. // Keep the shown document (and where it was looked at) in its tab
  1085. function stash() {
  1086. viewHistory.length = 0;
  1087. if (activeTab) {
  1088. activeTab.snap = docOf(activeTab.kind).snapshot();
  1089. activeTab.view = activeTab.kind === 'drawing' ? drawing.viewState() : viewport.viewState();
  1090. }
  1091. }
  1092. // "Sample Part", then "Sample Part 2" while the first is still open
  1093. function sampleName(base) {
  1094. const names = tabs.map(tabName);
  1095. let name = base;
  1096. for (let n = 2; names.indexOf(name) >= 0; n++) {
  1097. name = base + ' ' + n;
  1098. }
  1099. return name;
  1100. }
  1101. // Show a tab's document: a new one (fresh: { data, name, path }) or the
  1102. // snapshot it was kept as
  1103. function enter(tab, fresh) {
  1104. activeTab = tab;
  1105. if (tab.kind === 'part') {
  1106. kernel.call('useRebuilder', { key: 'part:' + tab.id }).catch(function () {
  1107. // The kernel failed to start; the status bar says so
  1108. });
  1109. state.fitNext = !!fresh;
  1110. state.keepView = !fresh;
  1111. if (fresh) {
  1112. doc.reset(fresh.data, fresh.name, fresh.path);
  1113. state.reportOnOpen = fresh.data ? doc.data() : null;
  1114. } else {
  1115. doc.restore(tab.snap);
  1116. }
  1117. } else if (tab.kind === 'assembly') {
  1118. assembly.setKeySpace(tab.id);
  1119. if (fresh) {
  1120. assembly.doc.reset(fresh.data, fresh.name, fresh.path);
  1121. } else {
  1122. assembly.doc.restore(tab.snap);
  1123. }
  1124. } else {
  1125. drawing.setKeySpace(tab.id);
  1126. if (fresh) {
  1127. drawing.doc.reset(fresh.data, fresh.name, fresh.path);
  1128. } else {
  1129. drawing.doc.restore(tab.snap);
  1130. }
  1131. }
  1132. tab.snap = null;
  1133. setEnv(tab.kind);
  1134. // Parts and drawings pick faces and edges, never whole components
  1135. if (tab.kind !== 'assembly') {
  1136. viewport.setComponentMode(false);
  1137. }
  1138. if (!fresh && tab.view) {
  1139. if (tab.kind === 'drawing') {
  1140. drawing.setViewState(tab.view);
  1141. } else {
  1142. viewport.setViewState(tab.view);
  1143. }
  1144. }
  1145. refreshChrome();
  1146. }
  1147. function switchTo(tab) {
  1148. if (!tab || tab === activeTab) {
  1149. return;
  1150. }
  1151. leaveDocument();
  1152. stash();
  1153. enter(tab, null);
  1154. setStatus(tabName(tab) + (tabPath(tab) ? ' (' + files.displayPath(tabPath(tab)) + ')' : ''));
  1155. }
  1156. // Open a document in a tab of its own: a file already open shows its tab,
  1157. // and an untouched empty document gives its place
  1158. function openTab(kind, data, name, path) {
  1159. if (path) {
  1160. const open = tabs.filter(function (t) {
  1161. return tabPath(t) === path;
  1162. })[0];
  1163. if (open) {
  1164. switchTo(open);
  1165. return open;
  1166. }
  1167. }
  1168. leaveDocument();
  1169. let tab = activeTab && isPristine(activeTab) ? activeTab : null;
  1170. if (tab) {
  1171. tab.kind = kind;
  1172. tab.view = null;
  1173. } else {
  1174. stash();
  1175. tab = { id: 't' + (++tabSeq), kind: kind, snap: null, view: null };
  1176. tabs.push(tab);
  1177. }
  1178. enter(tab, { data: data, name: name, path: path });
  1179. return tab;
  1180. }
  1181. function removeTab(tab) {
  1182. const i = tabs.indexOf(tab);
  1183. if (i < 0) {
  1184. return;
  1185. }
  1186. const wasShown = tab === activeTab;
  1187. if (wasShown) {
  1188. leaveDocument();
  1189. }
  1190. tabs.splice(i, 1);
  1191. // Free what the kernel kept for it
  1192. kernel.call('dropRebuilder', { key: 'part:' + tab.id }).catch(function () {
  1193. // The kernel is gone
  1194. });
  1195. assembly.forget(tab.id);
  1196. drawing.forget(tab.id);
  1197. if (wasShown) {
  1198. activeTab = null;
  1199. const next = tabs[Math.min(i, tabs.length - 1)];
  1200. if (next) {
  1201. enter(next, null);
  1202. } else {
  1203. const fresh = { id: 't' + (++tabSeq), kind: 'part', snap: null, view: null };
  1204. tabs.push(fresh);
  1205. enter(fresh, { data: null, name: 'Part1', path: '' });
  1206. }
  1207. }
  1208. renderTabs();
  1209. }
  1210. function closeTab(tab) {
  1211. if (tab !== activeTab && !tabDirty(tab)) {
  1212. removeTab(tab);
  1213. return;
  1214. }
  1215. // Show it, so the question is about what is on the screen
  1216. switchTo(tab);
  1217. confirmDiscard().then(function (ok) {
  1218. if (ok) {
  1219. removeTab(tab);
  1220. }
  1221. });
  1222. }
  1223. // Assemblies and drawings read the documents open in tabs as they are
  1224. files.setOpenDocuments(function (path) {
  1225. const tab = tabs.filter(function (t) {
  1226. return tabPath(t) === path;
  1227. })[0];
  1228. return tab ? { data: tabData(tab), name: tabName(tab) } : null;
  1229. });
  1230. function refreshChrome() {
  1231. const d = activeDoc();
  1232. const title = d.name + (d.isDirty() ? ' *' : '');
  1233. $('doctitle').textContent = title;
  1234. undoButton.disabled = !d.canUndo();
  1235. redoButton.disabled = !d.canRedo();
  1236. try {
  1237. window.ao_module_setWindowTitle('3D Modeler - ' + title);
  1238. } catch (e) {
  1239. // Not inside an ArozOS float window
  1240. }
  1241. if (native.available()) {
  1242. // The Mac window: its title, the close button's unsaved dot, the
  1243. // file in the title bar, and which File menu items apply
  1244. document.title = d.name;
  1245. native.windowInfo({ edited: tabs.some(tabDirty), path: d.path, kind: state.env });
  1246. }
  1247. renderTabs();
  1248. }
  1249. // Only one rebuild runs at a time. Changes made meanwhile collapse into one
  1250. // further rebuild of the then current document.
  1251. function requestRebuild() {
  1252. if (rebuildRunning) {
  1253. rebuildWanted = true;
  1254. return;
  1255. }
  1256. rebuildRunning = true;
  1257. rebuildWanted = false;
  1258. state.rebuildDeferred = false;
  1259. const asked = doc.data();
  1260. // The first build of a part that is being opened shows how far it is
  1261. // (the document's reset asks for it before the tab is known)
  1262. const shown = opening && opening.kind === 'part' && (!opening.tab || opening.tab === activeTab) ? opening : null;
  1263. if (shown) {
  1264. shown.tab = activeTab;
  1265. shown.task.update({ text: 'Building the part', fraction: null });
  1266. }
  1267. kernel.call('rebuild', { document: asked }, shown ? function (info) {
  1268. shown.task.update(buildText(info));
  1269. } : null).then(function (result) {
  1270. if (state.env !== 'part') {
  1271. return; // an assembly is on show; the (empty) part waits
  1272. }
  1273. const opened = state.reportOnOpen === asked;
  1274. if (opened) {
  1275. state.reportOnOpen = null;
  1276. }
  1277. featureReport = result.features;
  1278. takeFaceFrames(result.frames, result.lines);
  1279. followModel(result.projections);
  1280. // A feature or an earlier sketch being edited keeps its rolled back
  1281. // view; closing it asks again
  1282. if (!(activeFeature && activeFeature.rolledBack) && !state.rollbackAt) {
  1283. const first = !viewport.bodyCount() && result.bodies.length > 0;
  1284. viewport.setBodies(result.bodies);
  1285. refreshWorkPlanes(); // their size follows the part
  1286. if (first && !state.fitNext && !state.keepView) {
  1287. viewport.zoomAll(); // the first solid of the part: bring it into view
  1288. }
  1289. if (result.bodies.length) {
  1290. state.keepView = false;
  1291. }
  1292. }
  1293. browser.render(featureReport, result.bodies.length);
  1294. if (state.fitNext) {
  1295. state.fitNext = false;
  1296. viewport.home();
  1297. }
  1298. const failed = doc.features().filter(function (f) {
  1299. return featureReport[f.id] && featureReport[f.id].status === 'error';
  1300. });
  1301. const hadFailures = lastFailed;
  1302. lastFailed = failed.length > 0;
  1303. if (failed.length && opened) {
  1304. reportOpenFailures(failed);
  1305. }
  1306. if (failed.length) {
  1307. lastFailureText = failed.length === 1 ? failed[0].name + ' could not be built: ' + featureReport[failed[0].id].message
  1308. : failed.length + ' features could not be built, see the model browser';
  1309. setStatus(lastFailureText);
  1310. } else if (hadFailures && state.mode === 'model' && $('status-msg').textContent === lastFailureText) {
  1311. setStatus('Ready'); // clear the error text once the part builds again (not a newer message)
  1312. }
  1313. // A solid that does not close up (or one the mesher patched) is
  1314. // said once, when it turns up
  1315. const unhealthy = result.bodies.some(function (b) {
  1316. return b.health && (b.health.open || b.health.multiple || b.health.empty || b.health.patched);
  1317. });
  1318. if (unhealthy && !state.unhealthy && !failed.length) {
  1319. setStatus('The solid has open edges or faces that did not mesh cleanly: Inspect > Check Geometry shows where, 3D Model > Repair fixes it');
  1320. }
  1321. state.unhealthy = unhealthy;
  1322. checkPanel.refresh();
  1323. }).catch(function (err) {
  1324. setStatus('Rebuild failed: ' + err.message);
  1325. }).then(function () {
  1326. if (shown) {
  1327. endOpening(shown);
  1328. }
  1329. rebuildRunning = false;
  1330. if (rebuildWanted) {
  1331. requestRebuild();
  1332. }
  1333. });
  1334. }
  1335. // A part that was just opened and has features that cannot be built: say
  1336. // which and why at once, rather than leaving it to red rows in the tree
  1337. function reportOpenFailures(failed) {
  1338. const lines = failed.slice(0, 8).map(function (f) {
  1339. return f.name + ': ' + featureReport[f.id].message;
  1340. });
  1341. if (failed.length > 8) {
  1342. lines.push('and ' + (failed.length - 8) + ' more');
  1343. }
  1344. tell(failed.length === 1 ? 'A feature could not be built' : failed.length + ' features could not be built',
  1345. doc.name + ' opened, but ' + (failed.length === 1 ? 'this feature fails' : 'these features fail') + ':\n\n' + lines.join('\n') +
  1346. '\n\nThey are marked red in the model browser. Edit them, Suppress them, or drag End of Part above them to work on the rest of the part.');
  1347. }
  1348. doc.onChange(function (reason) {
  1349. // Every size box understands the part's parameter names
  1350. setScope(evaluateParameters(doc.data().parameters).values);
  1351. if (state.env === 'part') {
  1352. viewport.setHiddenBodies(doc.data().hiddenBodies || []);
  1353. }
  1354. if (reason === 'visual') {
  1355. // Hidden, shown or shared: nothing to rebuild, nothing to close
  1356. refreshChrome();
  1357. browser.render();
  1358. refreshSketches();
  1359. refreshWorkPlanes();
  1360. return;
  1361. }
  1362. refreshChrome();
  1363. if (reason === 'amend') {
  1364. // The app's own follow-up (projected geometry following the model):
  1365. // rebuild, but leave open panels and the sketcher alone
  1366. browser.render();
  1367. refreshSketches();
  1368. refreshWorkPlanes();
  1369. if (sketcher.isOpen()) {
  1370. state.rebuildDeferred = true;
  1371. } else {
  1372. requestRebuild();
  1373. }
  1374. return;
  1375. }
  1376. if (appearanceTool.isOpen() && reason !== 'saved') {
  1377. appearanceTool.cancel(); // undo or another part pulled the look from under the panel
  1378. }
  1379. if (paintTool.isOpen() && reason !== 'saved') {
  1380. paintTool.cancel();
  1381. }
  1382. if (state.env === 'part') {
  1383. viewport.setAppearance(doc.data().appearance || null);
  1384. }
  1385. if (activeFeature) {
  1386. activeFeature.tool.cancel(); // undo, redo or a new part pulled the model from under the panel
  1387. }
  1388. if (sketcher.isOpen()) {
  1389. // Another part was loaded, the open sketch was deleted or undone away,
  1390. // or undo / redo changed it under the sketcher
  1391. const gone = reason === 'reset' || reason === 'restore' || !doc.feature(sketcher.featureId());
  1392. if (gone || ((reason === 'undo' || reason === 'redo') && !sketcher.reload())) {
  1393. closeSketch();
  1394. }
  1395. }
  1396. browser.render();
  1397. refreshSketches();
  1398. refreshWorkPlanes();
  1399. if (reason === 'saved') {
  1400. return;
  1401. }
  1402. if (sketcher.isOpen()) {
  1403. state.rebuildDeferred = true;
  1404. } else {
  1405. requestRebuild();
  1406. }
  1407. });
  1408. /* ================= files ================= */
  1409. function fail(title, err) {
  1410. setStatus(title + ': ' + err.message);
  1411. return tell(title, err.message);
  1412. }
  1413. // Resolves to true when it is fine to throw the current document away
  1414. function confirmDiscard() {
  1415. const d = activeDoc();
  1416. if (!d.isDirty()) {
  1417. return Promise.resolve(true);
  1418. }
  1419. return ask('Unsaved changes', 'Save the changes to ' + d.name + ' first?', [
  1420. { label: 'Cancel', value: 'cancel' },
  1421. { label: 'Do Not Save', value: 'discard' },
  1422. { label: 'Save', value: 'save', primary: true }
  1423. ], 'cancel').then(function (answer) {
  1424. if (answer === 'discard') {
  1425. return true;
  1426. }
  1427. return answer === 'save' ? saveDocument(false) : false;
  1428. });
  1429. }
  1430. // Switch the window between the part, assembly and drawing environments.
  1431. // What was open in the other one is put away; its document stays (the tab
  1432. // it belongs to was stashed before, see enter()).
  1433. function setEnv(env) {
  1434. if (state.env === env) {
  1435. return;
  1436. }
  1437. const was = state.env;
  1438. closeInspect(true);
  1439. if (activeFeature) {
  1440. activeFeature.tool.cancel();
  1441. }
  1442. if (picking()) {
  1443. leaveMode();
  1444. }
  1445. if (sketcher.isOpen()) {
  1446. closeSketch();
  1447. }
  1448. setLeftDrag('select');
  1449. viewport.setSection('none');
  1450. ribbon.setLabel('view.section', 'Section View');
  1451. viewport.setPreview(null);
  1452. viewport.clearSelection();
  1453. // Put away what was open
  1454. if (was === 'assembly') {
  1455. assembly.deactivate();
  1456. } else if (was === 'drawing') {
  1457. drawing.deactivate();
  1458. showSheetChrome(false);
  1459. }
  1460. viewport.setBodies([]);
  1461. viewport.setHiddenBodies(env === 'part' ? doc.data().hiddenBodies || [] : []);
  1462. state.env = env;
  1463. refreshMeshes(); // a part's reference meshes only show in the part
  1464. ribbon.setMode(env);
  1465. ribbon.setTabVisible('sketch', false);
  1466. $('tree').hidden = env !== 'part';
  1467. $('asm-tree').hidden = env !== 'assembly';
  1468. $('drw-tree').hidden = env !== 'drawing';
  1469. $('browser-head').textContent = { part: 'Model', assembly: 'Assembly', drawing: 'Drawing' }[env];
  1470. // Only a part shows through the shared body material; assemblies and
  1471. // drawings give each body its own
  1472. viewport.setAppearance(env === 'part' ? doc.data().appearance || null : null);
  1473. if (env === 'assembly') {
  1474. assembly.activate();
  1475. ribbon.showTab('assemble');
  1476. } else if (env === 'drawing') {
  1477. drawing.activate();
  1478. ribbon.showTab('drawviews');
  1479. } else {
  1480. ribbon.showTab('model');
  1481. requestRebuild();
  1482. }
  1483. refreshChrome();
  1484. }
  1485. // While a drawing shows its sheet the 3D view's own controls are put away;
  1486. // the Drawing View panel brings the 3D view back to pick a direction
  1487. function showSheetChrome(sheet) {
  1488. $('stage').classList.toggle('sheet-mode', !!sheet);
  1489. }
  1490. // A part, an assembly or a drawing, by its format, in a tab of its own.
  1491. // picture: the one saved in the file (io/preview.js), shown while it loads
  1492. function loadDocument(data, name, path, picture) {
  1493. const kind = data && data.format === 'aodrw' ? 'drawing' : data && data.format === 'aoasm' ? 'assembly' : 'part';
  1494. let clean = null;
  1495. try {
  1496. if (data) {
  1497. const copy = preview.stripPreview(JSON.parse(JSON.stringify(data)));
  1498. clean = kind === 'drawing' ? validateDrawing(copy) : kind === 'assembly' ? validateAssembly(copy) : validatePart(copy);
  1499. }
  1500. } catch (err) {
  1501. endOpening();
  1502. fail('The ' + KIND_NAMES[kind] + ' could not be opened', err);
  1503. return false;
  1504. }
  1505. // A file open in a tab already only shows that tab; an empty part has
  1506. // nothing to build
  1507. const already = path && tabs.some(function (t) {
  1508. return tabPath(t) === path;
  1509. });
  1510. if (clean && !already) {
  1511. if (!opening) {
  1512. beginOpening(name + EXT[kind]);
  1513. }
  1514. opening.task.update({ title: 'Opening ' + name + EXT[kind], text: 'Building the ' + KIND_NAMES[kind], fraction: null, preview: picture || '' });
  1515. opening.tab = null; // the tab openTab gives
  1516. opening.kind = kind;
  1517. } else {
  1518. endOpening();
  1519. }
  1520. const which = opening;
  1521. const tab = openTab(kind, clean, name, path);
  1522. if (which && which === opening) {
  1523. which.tab = tab;
  1524. // An assembly or drawing with nothing to read is there at once
  1525. const env = kind === 'assembly' ? assembly : kind === 'drawing' ? drawing : null;
  1526. if (env && !env.isLoading()) {
  1527. endOpening(which);
  1528. }
  1529. }
  1530. return true;
  1531. }
  1532. // The model a new drawing starts from: the part or assembly that was open
  1533. // (by its file when it is saved, else kept inside the drawing), or null
  1534. function drawingSuggestion() {
  1535. const copy = function (d) {
  1536. return JSON.parse(JSON.stringify(d));
  1537. };
  1538. if (state.env === 'part' && doc.features().some(function (f) {
  1539. return f.type !== 'sketch' && f.type !== 'plane';
  1540. })) {
  1541. return { data: copy(doc.data()), name: doc.name, path: doc.isDirty() ? '' : doc.path };
  1542. }
  1543. if (state.env === 'assembly' && assembly.doc.components().length) {
  1544. return { data: copy(assembly.doc.data()), name: assembly.doc.name, path: assembly.doc.isDirty() ? '' : assembly.doc.path };
  1545. }
  1546. return null;
  1547. }
  1548. // A new document in a tab of its own (the open ones stay open)
  1549. function newDocument() {
  1550. chooseNew().then(function (kind) {
  1551. if (!kind) {
  1552. return;
  1553. }
  1554. const names = tabs.map(tabName);
  1555. if (kind === 'drawing') {
  1556. // The part or assembly on show is what the drawing starts from
  1557. const suggest = drawingSuggestion();
  1558. openTab('drawing', null, freeName('Drawing', names), '');
  1559. drawing.startNew(suggest);
  1560. } else if (kind === 'assembly') {
  1561. openTab('assembly', null, freeName('Assembly', names), '');
  1562. setStatus('New assembly: Assemble > Place puts in the first part, which is grounded at the origin');
  1563. } else {
  1564. openTab('part', null, freeName('Part', names), '');
  1565. setStatus('New part: Start 2D Sketch on an origin plane');
  1566. }
  1567. });
  1568. }
  1569. function openDocument() {
  1570. let reading = null;
  1571. files.open(function (name) {
  1572. reading = beginOpening(name);
  1573. }).then(function (file) {
  1574. if (file && loadDocument(file.data, file.name, file.path, file.preview)) {
  1575. setStatus('Opened ' + (files.displayPath(file.path) || file.name));
  1576. } else if (!file) {
  1577. endOpening(reading);
  1578. }
  1579. }).catch(function (err) {
  1580. endOpening(reading);
  1581. fail('The part could not be opened', err);
  1582. });
  1583. }
  1584. // The picture saved in the file, which the ArozOS File Manager shows as
  1585. // its thumbnail (io/preview.js): a drawing's sheet, else the solids as the
  1586. // view looks at them. Resolves to a JPEG data URL, or null without one.
  1587. function documentPreview() {
  1588. let canvas = null;
  1589. try {
  1590. canvas = state.env === 'drawing' ? drawing.previewCanvas(preview.PREVIEW_SIDE)
  1591. : viewport.capturePreview(preview.PREVIEW_SIDE);
  1592. } catch (err) {
  1593. canvas = null; // the file is saved without its picture
  1594. }
  1595. return preview.encode(canvas);
  1596. }
  1597. // Resolves to true when the part (or assembly) was written
  1598. function saveDocument(askWhere) {
  1599. const d = activeDoc();
  1600. const ext = EXT[state.env];
  1601. const kind = state.env;
  1602. // The picture is taken now, as the document is on screen; encoding it
  1603. // runs in a worker and gives up rather than hold the save up for long
  1604. return documentPreview().then(function (picture) {
  1605. // Assemblies and drawings write their links relative to where they land
  1606. const text = d.serializeFor ? function (target) {
  1607. return preview.withPreview(d.serializeFor(target), picture);
  1608. } : preview.withPreview(d.serialize(), picture);
  1609. return files.save(text, d.name, d.path, askWhere, ext);
  1610. }).then(function (saved) {
  1611. if (!saved) {
  1612. return false;
  1613. }
  1614. d.name = saved.name;
  1615. d.path = saved.path;
  1616. d.markSaved();
  1617. setStatus(saved.path ? 'Saved to ' + files.displayPath(saved.path) : 'Downloaded ' + saved.name + ext);
  1618. return true;
  1619. }).catch(function (err) {
  1620. fail('The ' + KIND_NAMES[kind] + ' could not be saved', err);
  1621. return false;
  1622. });
  1623. }
  1624. /* ================= inspect ================= */
  1625. // The mass from the part's material (Appearance > Material), or an example
  1626. function massLines(volume) {
  1627. const mass = massOf(volume, doc.data().material);
  1628. return mass ? ['Mass: ' + mass.text + ' in ' + mass.material]
  1629. : ['Mass = volume x density of your material, for example PLA 1.24 g/cm3: ' + mm(volume / 1000 * 1.24, 2) + ' g.',
  1630. 'Appearance > Material sets the material of the part.'];
  1631. }
  1632. // The threads of the part's holes, as notes (threads are not modelled)
  1633. function threadNotes() {
  1634. const lines = [];
  1635. doc.features().forEach(function (f) {
  1636. if (f.type === 'hole' && !f.suppressed && f.thread && f.thread.designation) {
  1637. const sketch = doc.feature(f.sketch);
  1638. const count = sketch ? sketchModel.holePoints(sketch).length : 0;
  1639. lines.push(f.name + ': ' + count + ' x ' + f.thread.designation + (f.thread.depth ? ', ' + mm(f.thread.depth, 2) + ' mm deep' : ', through'));
  1640. }
  1641. });
  1642. return lines.length ? ['', 'Threads (notes, not in the volume):'].concat(lines) : [];
  1643. }
  1644. function showMassProperties() {
  1645. if (!viewport.bodyCount()) {
  1646. setStatus('There is no solid to measure yet');
  1647. return;
  1648. }
  1649. kernel.call('massProperties').then(function (m) {
  1650. const line = function (label, values, unit) {
  1651. return label + ': ' + values.map(function (v) {
  1652. return mm(v, 3);
  1653. }).join(' x ') + ' ' + unit;
  1654. };
  1655. tell('Mass Properties of ' + doc.name, [
  1656. 'Solid bodies: ' + m.bodies,
  1657. line('Volume', [m.volume], 'mm3') + ' (' + mm(m.volume / 1000, 3) + ' cm3)',
  1658. line('Surface area', [m.area], 'mm2'),
  1659. line('Overall size (X x Y x Z)', m.size, 'mm'),
  1660. 'Centre of gravity: X ' + mm(m.centre[0], 3) + ', Y ' + mm(m.centre[1], 3) + ', Z ' + mm(m.centre[2], 3) + ' mm',
  1661. ''
  1662. ].concat(massLines(m.volume)).concat(threadNotes()).join('\n'));
  1663. }).catch(function (err) {
  1664. fail('The part could not be measured', err);
  1665. });
  1666. }
  1667. // Measure and Section View: panels shared by parts and assemblies
  1668. let activeInspect = null; // { kind: "measure" | "section", tool }
  1669. function partDistance(a, b) {
  1670. const ref = function (item) {
  1671. return item.kind === 'edge' ? { type: 'edge', body: item.body, mid: item.mid, length: item.length }
  1672. : { type: 'face', body: item.body, index: item.index };
  1673. };
  1674. return kernel.call('distance', { a: ref(a), b: ref(b) });
  1675. }
  1676. function startInspect(kind, arg) {
  1677. closeInspect(true);
  1678. if (sketcher.isOpen()) {
  1679. finishSketch();
  1680. }
  1681. if (activeFeature) {
  1682. activeFeature.tool.cancel();
  1683. }
  1684. if (state.env === 'assembly') {
  1685. assembly.stopTools();
  1686. }
  1687. const tool = kind === 'section' ? sectionPanel : kind === 'check' ? checkPanel : state.env === 'assembly' ? measureAssembly : measurePart;
  1688. if (!viewport.bodyCount()) {
  1689. setStatus(kind === 'section' ? 'There is nothing to cut yet' : kind === 'check' ? 'There is nothing to check yet' : 'There is nothing to measure yet');
  1690. return;
  1691. }
  1692. if (tool.start(arg)) {
  1693. activeInspect = { kind: kind, tool: tool };
  1694. ribbon.setOn('ins.measure', kind === 'measure');
  1695. ribbon.setOn('ins.check', kind === 'check');
  1696. setStatus(kind === 'measure' ? 'Measure: click a face or an edge, then a second one' : kind === 'check' ? 'Check Geometry: checking the solid'
  1697. : 'Section View: pick the plane and drag its position');
  1698. }
  1699. }
  1700. // Put an open Measure or Section panel away (a section is kept)
  1701. function closeInspect(keep) {
  1702. if (activeInspect) {
  1703. if (activeInspect.kind === 'section' && keep) {
  1704. activeInspect.tool.accept();
  1705. } else {
  1706. activeInspect.tool.cancel();
  1707. }
  1708. }
  1709. }
  1710. function inspectClosed(kind) {
  1711. if (!activeInspect || activeInspect.kind !== kind) {
  1712. return;
  1713. }
  1714. activeInspect = null;
  1715. ribbon.setOn('ins.measure', false);
  1716. ribbon.setOn('ins.check', false);
  1717. if (state.env === 'assembly') {
  1718. viewport.setComponentMode(true);
  1719. }
  1720. if (kind === 'section') {
  1721. const mode = viewport.sectionSpec().mode;
  1722. ribbon.setLabel('view.section', mode === 'none' ? 'Section View' : 'Section: ' + { half: 'Half', quarter: 'Quarter', threequarter: '3/4' }[mode]);
  1723. }
  1724. setStatus('Ready');
  1725. }
  1726. /* ================= import and export ================= */
  1727. // How fine the triangles of a mesh export are (the largest gap allowed
  1728. // between a curved face and its triangles, and between neighbours) is
  1729. // picked in io/exportdialog.js, which shows the size each choice makes
  1730. const MESH_TEXT = {
  1731. stl: 'STL keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.',
  1732. obj: 'OBJ keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.',
  1733. '3mf': '3MF keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.'
  1734. };
  1735. function exportPart(format) {
  1736. if (!viewport.bodyCount()) {
  1737. setStatus('There is nothing to export yet');
  1738. return;
  1739. }
  1740. const name = activeDoc().name;
  1741. const base = name + '.' + format;
  1742. let made;
  1743. if (state.env === 'assembly' && (format === 'step' || format === 'brep')) {
  1744. setStatus('Writing ' + format.toUpperCase() + '...');
  1745. made = assembly.exportContent(format);
  1746. } else if (format === 'step' || format === 'brep') {
  1747. setStatus('Writing ' + format.toUpperCase() + '...');
  1748. made = kernel.call('exportText', { format: format }).then(function (out) {
  1749. return { text: out.text };
  1750. });
  1751. } else {
  1752. const choices = [{ key: 'units', label: 'Units', items: [{ id: 'mm', label: 'Millimetres' }, { id: 'in', label: 'Inches' }] }];
  1753. if (format === 'stl') {
  1754. choices.push({ key: 'encoding', label: 'Encoding', items: [{ id: 'binary', label: 'Binary (small)' }, { id: 'ascii', label: 'ASCII text' }] });
  1755. }
  1756. made = askMeshExport({
  1757. title: 'Export ' + format.toUpperCase(),
  1758. text: MESH_TEXT[format],
  1759. format: format,
  1760. choices: choices,
  1761. // The whole file at one fineness: its size is shown, and it is
  1762. // what is saved when that fineness is exported
  1763. make: function (level, picked) {
  1764. const quality = { deflection: level.deflection, angle: level.angle };
  1765. const meshed = state.env === 'assembly' ? assembly.exportContent(format, quality) : kernel.call('mesh', quality);
  1766. return meshed.then(function (raw) {
  1767. // Inches: every coordinate over 25.4 (the file has no unit of its own)
  1768. const out = Object.assign({}, raw, { bodies: scaled(raw.bodies, picked && picked.units === 'in' ? 1 / 25.4 : 1) });
  1769. let triangles = 0;
  1770. out.bodies.forEach(function (b) {
  1771. triangles += b.indices.length / 3;
  1772. });
  1773. let content;
  1774. const units = picked && picked.units === 'in' ? 'in' : 'mm';
  1775. if (format === 'obj') {
  1776. content = { text: toOBJ(out.bodies, name, units) };
  1777. } else if (format === 'stl' && picked && picked.encoding === 'ascii') {
  1778. content = { text: toSTLText(out.bodies, name) };
  1779. } else {
  1780. content = { bytes: format === 'stl' ? toSTL(out.bodies, units) : to3MF(out.bodies, units) };
  1781. }
  1782. const size = content.text !== undefined ? new Blob([content.text]).size : content.bytes.length;
  1783. // What a slicer will say: each solid checked on its own
  1784. let open = 0;
  1785. let multiple = 0;
  1786. out.bodies.forEach(function (b) {
  1787. const check = meshCheck(b);
  1788. open += check.open;
  1789. multiple += check.multiple;
  1790. });
  1791. const warning = open || multiple ? 'Not watertight: ' + [open ? open + ' open' : '', multiple ? multiple + ' non-manifold' : ''].filter(Boolean).join(' and ') +
  1792. ' edges. Inspect > Check Geometry shows where' : '';
  1793. return { content: content, size: size, triangles: triangles, warning: warning };
  1794. });
  1795. }
  1796. }).then(function (chosen) {
  1797. if (chosen) {
  1798. setStatus('Saving ' + format.toUpperCase() + ' (' + chosen.level.label.toLowerCase() + ')...');
  1799. }
  1800. return chosen ? chosen.content : null;
  1801. });
  1802. }
  1803. made.then(function (content) {
  1804. return content ? files.saveAs(base, content) : null;
  1805. }).then(function (saved) {
  1806. setStatus(saved ? (saved.path ? 'Exported to ' + files.displayPath(saved.path) : 'Downloaded ' + saved.name) : 'Ready');
  1807. }).catch(function (err) {
  1808. fail('The part could not be exported', err);
  1809. });
  1810. }
  1811. // A STEP file becomes a feature of its own that later features build on.
  1812. // file: { name, text }
  1813. function addImport(file) {
  1814. setStatus('Reading ' + file.name + '...');
  1815. return kernel.call('importInfo', { text: file.text }).then(function (info) {
  1816. const id = doc.newId();
  1817. const name = doc.newName('import');
  1818. doc.change('Import ' + file.name, function (d) {
  1819. d.features.push({ id: id, type: 'import', name: name, format: 'step', source: file.name, data: file.text });
  1820. });
  1821. state.fitNext = true;
  1822. setStatus('Imported ' + info.solids + (info.solids === 1 ? ' solid' : ' solids') + ' from ' + file.name);
  1823. });
  1824. }
  1825. function importStep() {
  1826. files.openOther(['step', 'stp'], false).then(function (file) {
  1827. return file ? addImport(file) : null;
  1828. }).catch(function (err) {
  1829. fail('The file could not be imported', err);
  1830. });
  1831. }
  1832. // An STL or OBJ file becomes a reference mesh: drawn pale to model around,
  1833. // not a solid (the kernel ignores it; it is not exported or weighed)
  1834. const MESH_WARN_BYTES = 8 * 1024 * 1024;
  1835. function importMesh(format) {
  1836. files.openOther([format], format === 'stl').then(function (file) {
  1837. if (!file) {
  1838. return null;
  1839. }
  1840. setStatus('Reading ' + file.name + '...');
  1841. const mesh = format === 'stl' ? parseSTL(file.bytes) : parseOBJ(file.text);
  1842. const data = encodeMesh(mesh);
  1843. const size = data.positions.length + data.indices.length;
  1844. const info = meshInfo(mesh);
  1845. const go = size < MESH_WARN_BYTES ? Promise.resolve(true) : ask('Large mesh', file.name + ' has ' + info.triangles.toLocaleString('en-US') +
  1846. ' triangles and adds about ' + Math.round(size / 1048576) + ' MB to the part file. Bring it in anyway?',
  1847. [{ label: 'Cancel', value: false }, { label: 'Bring In', value: true, primary: true }], false);
  1848. return go.then(function (ok) {
  1849. if (!ok) {
  1850. setStatus('Ready');
  1851. return;
  1852. }
  1853. const id = doc.newId();
  1854. const name = doc.newName('mesh');
  1855. doc.change('Bring in ' + file.name, function (d) {
  1856. d.features.push({ id: id, type: 'mesh', name: name, format: format, source: file.name, data: data });
  1857. });
  1858. const span = info.max.map(function (v, k) {
  1859. return +(v - info.min[k]).toFixed(2);
  1860. });
  1861. setStatus(name + ': ' + file.name + ', ' + info.triangles.toLocaleString('en-US') + ' triangles, ' + span.join(' x ') +
  1862. ' mm. A reference to model around: it is not a solid and is not exported.');
  1863. });
  1864. }).catch(function (err) {
  1865. fail('The mesh could not be brought in', err);
  1866. });
  1867. }
  1868. function deleteFeature(id) {
  1869. const feature = doc.feature(id);
  1870. const dependents = doc.dependents(id);
  1871. const go = !dependents.length ? Promise.resolve(true) : ask('Delete ' + feature.name,
  1872. dependents.map(function (f) {
  1873. return f.name;
  1874. }).join(', ') + (dependents.length === 1 ? ' is' : ' are') + ' built from it and will be deleted too.',
  1875. [{ label: 'Cancel', value: false }, { label: 'Delete', value: true, primary: true }], false);
  1876. go.then(function (ok) {
  1877. if (ok) {
  1878. doc.remove(id);
  1879. }
  1880. });
  1881. }
  1882. // The desktop calls ao_module_close() when the window's close button is
  1883. // pressed: unsaved work is asked about first.
  1884. const closeWindow = window.ao_module_closeHandler;
  1885. // Resolves to true when the window may close: nothing unsaved, or the
  1886. // person said so
  1887. function confirmCloseAll() {
  1888. closeInspect(true);
  1889. const dirty = tabs.filter(tabDirty);
  1890. if (!dirty.length) {
  1891. return Promise.resolve(true);
  1892. }
  1893. if (dirty.length === 1 && dirty[0] === activeTab) {
  1894. return confirmDiscard();
  1895. }
  1896. return ask('Unsaved changes', dirty.map(tabName).join(', ') + (dirty.length === 1 ? ' has' : ' have') +
  1897. ' changes that are not saved. Close 3D Modeler anyway?', [
  1898. { label: 'Close Without Saving', value: true },
  1899. { label: 'Cancel', value: false, primary: true }
  1900. ], false);
  1901. }
  1902. // Closed on purpose (saved, or not saved on purpose): nothing to restore
  1903. function closingOnPurpose() {
  1904. clearTimeout(autosaveTimer);
  1905. autosaveTimer = null;
  1906. autosaveClosed = true;
  1907. autosaveOn = false;
  1908. dropAutosave(AUTOSAVE_KEY);
  1909. }
  1910. window.ao_module_close = function () {
  1911. confirmCloseAll().then(function (ok) {
  1912. if (ok) {
  1913. closingOnPurpose();
  1914. }
  1915. if (ok && typeof closeWindow === 'function') {
  1916. closeWindow();
  1917. }
  1918. });
  1919. };
  1920. // The page goes away (closed, reloaded): its entry is stale at once, so the
  1921. // next start offers it without waiting for the stamp to age
  1922. window.addEventListener('pagehide', function () {
  1923. if (autosaveTimer || autosaveOn) {
  1924. writeAutosave(); // a change of the last moment too
  1925. }
  1926. if (autosaveOn) {
  1927. try {
  1928. autosaveStore().setItem(AUTOSAVE_KEY + '.alive', '0');
  1929. } catch (e) {
  1930. // storage went away
  1931. }
  1932. }
  1933. });
  1934. window.addEventListener('beforeunload', function (event) {
  1935. // Covers a browser tab; inside the desktop the handler above runs first
  1936. if (tabs.some(tabDirty) && !window.ao_module_virtualDesktop) {
  1937. event.preventDefault();
  1938. }
  1939. });
  1940. /* ================= commands ================= */
  1941. function picking() {
  1942. return state.mode === 'pick-sketch-plane' || state.mode === 'pick-lookat' || state.mode === 'pick-workplane';
  1943. }
  1944. function leaveMode() {
  1945. viewport.stopPlanePick();
  1946. state.pickText = null;
  1947. ribbon.setOn('sketch.start', false);
  1948. ribbon.setOn('nav.lookat', false);
  1949. ribbon.setOn('work.plane', false);
  1950. setPrompt('');
  1951. state.mode = sketcher.isOpen() ? 'sketch' : 'model';
  1952. }
  1953. // The plane reference a sketch or work plane stores for a picked target.
  1954. // A face also remembers its normal and the point clicked, so the sketch
  1955. // (or work plane) can follow the face when an earlier feature moves it
  1956. function referenceOf(target) {
  1957. return target.kind === 'origin' ? { ref: 'origin:' + target.key }
  1958. : target.kind === 'work' ? { ref: 'plane', id: target.id }
  1959. : target.point ? { ref: 'face', frame: faceFrame(target), face: target.name ? { normal: target.normal, point: target.point, name: target.name } : { normal: target.normal, point: target.point } }
  1960. : { ref: 'face', frame: faceFrame(target) };
  1961. }
  1962. /* ---- dragging a plane into an offset sketch plane (planedrag.js) ---- */
  1963. const offsetBox = createOffsetBox($('stage'));
  1964. function offsetFrame(target, offset) {
  1965. const base = planeFrame(referenceOf(target), doc.features());
  1966. return base ? {
  1967. o: [base.o[0] + base.n[0] * offset, base.o[1] + base.n[1] * offset, base.o[2] + base.n[2] * offset],
  1968. x: base.x, y: base.y, n: base.n
  1969. } : null;
  1970. }
  1971. function showOffsetDraft(target, offset) {
  1972. const frame = offsetFrame(target, offset);
  1973. draftPlane = frame ? { frame: frame, id: null } : null;
  1974. refreshWorkPlanes();
  1975. }
  1976. const SKETCH_PLANE_DRAG = {
  1977. frameOf: function (target) {
  1978. return planeFrame(referenceOf(target), doc.features());
  1979. },
  1980. move: function (target, offset, at) {
  1981. showOffsetDraft(target, offset);
  1982. offsetBox.show(at[0], at[1], offset);
  1983. setStatus('Offset ' + offset + ' mm: release, then type the exact distance');
  1984. },
  1985. end: function (target, offset, at) {
  1986. leaveMode();
  1987. showOffsetDraft(target, offset);
  1988. setPrompt('Enter the offset of the new sketch plane');
  1989. offsetBox.edit(at[0], at[1], offset, function (value) {
  1990. showOffsetDraft(target, value);
  1991. }).then(function (value) {
  1992. draftPlane = null;
  1993. refreshWorkPlanes();
  1994. setPrompt('');
  1995. if (value === null) {
  1996. setStatus('Ready');
  1997. } else if (Math.abs(value) < 1e-9) {
  1998. planePicked(target); // no offset: a sketch on the plane itself
  1999. } else {
  2000. sketchOnOffsetPlane(target, value);
  2001. }
  2002. });
  2003. }
  2004. };
  2005. // A work plane offset from the target and a new sketch on it, one undo step
  2006. function sketchOnOffsetPlane(target, offset) {
  2007. const planeId = doc.newId();
  2008. let k = Number(planeId.slice(1)) + 1;
  2009. while (doc.feature('f' + k)) {
  2010. k++;
  2011. }
  2012. const sketchId = 'f' + k;
  2013. const planeName = doc.newName('plane');
  2014. const sketchName = doc.newName('sketch');
  2015. doc.change('Sketch on ' + planeName, function (d) {
  2016. d.features.push({ id: planeId, type: 'plane', name: planeName, base: referenceOf(target), offset: offset });
  2017. d.features.push({ id: sketchId, type: 'sketch', name: sketchName, plane: { ref: 'plane', id: planeId }, geometry: [], constraints: [] });
  2018. });
  2019. setStatus(planeName + ' made ' + offset + ' mm from the plane; sketching on it');
  2020. openSketch(sketchId);
  2021. }
  2022. // target: { kind: "origin", key }, { kind: "face", body, face, origin, normal }
  2023. // or { kind: "work", id } for a work plane feature
  2024. function planePicked(target) {
  2025. state.pickText = null;
  2026. const work = target.kind === 'work' ? doc.feature(target.id) : null;
  2027. const label = target.kind === 'origin' ? ORIGIN_PLANES[target.key].label : work ? work.name : 'the selected face';
  2028. const reference = referenceOf(target);
  2029. const turn = function () {
  2030. if (target.kind === 'origin') {
  2031. viewport.lookAtPlane(target.key);
  2032. } else {
  2033. viewport.lookAlong(work ? workPlaneFrame(work, doc.features()).n : target.normal);
  2034. }
  2035. };
  2036. if (state.mode === 'pick-workplane') {
  2037. // The base of a new work plane: hand it to the panel
  2038. leaveMode();
  2039. featureTools.plane.prepare(reference);
  2040. startFeature('plane', null);
  2041. return;
  2042. }
  2043. if (state.mode === 'pick-lookat') {
  2044. leaveMode();
  2045. turn();
  2046. setStatus('Looking at ' + label);
  2047. return;
  2048. }
  2049. // A new sketch on the picked plane, opened in the sketcher
  2050. leaveMode();
  2051. const id = doc.newId();
  2052. const plane = reference;
  2053. // A sketch on a face starts with the edges of that face as reference
  2054. // geometry, so new geometry can be snapped, constrained and dimensioned
  2055. // to the model (and the face outline can bound a profile)
  2056. const start = { geometry: [], constraints: [] };
  2057. if (target.kind === 'face') {
  2058. viewport.curvesOf({ type: 'face', body: target.body, index: target.face }).forEach(function (curve) {
  2059. addProjected(start, plane.frame, curve);
  2060. });
  2061. }
  2062. doc.change('Create sketch', function (d) {
  2063. d.features.push({ id: id, type: 'sketch', name: doc.newName('sketch'), plane: plane, geometry: start.geometry, constraints: [] });
  2064. });
  2065. openSketch(id);
  2066. }
  2067. function startPlanePick(mode, button, what) {
  2068. state.mode = mode;
  2069. ribbon.setOn(button, true);
  2070. // Orbit or Pan would keep the left button: the pick (and dragging an
  2071. // offset plane off the one picked) needs it back
  2072. if (state.leftDrag !== 'select') {
  2073. setLeftDrag('select');
  2074. }
  2075. // With a solid in the part the user picks one of its planar faces; the
  2076. // origin planes are only offered in an empty part (or from the browser)
  2077. const text = viewport.bodyCount() ? 'Select a planar face ' + what : 'Select plane ' + what;
  2078. state.pickText = text;
  2079. setPrompt(text);
  2080. setStatus(text);
  2081. // Start 2D Sketch: dragging off a plane makes an offset plane to sketch on
  2082. viewport.startPlanePick(planePicked, mode === 'pick-workplane', mode === 'pick-sketch-plane' ? SKETCH_PLANE_DRAG : null);
  2083. }
  2084. function runSelfTest() {
  2085. if (!state.kernelReady) {
  2086. setStatus('The modelling kernel is still loading');
  2087. return;
  2088. }
  2089. setStatus('Running kernel self-test...');
  2090. kernel.call('selftest').then(function (out) {
  2091. const s = out.stats;
  2092. setStatus('Kernel self-test passed: extrude, hole, fillet and chamfer in ' + s.buildMs + ' ms, ' + s.faces + ' faces, ' +
  2093. s.triangles + ' triangles, volume ' + s.volume.toFixed(1) + ' mm3, STEP export ' + (s.stepBytes / 1024).toFixed(1) + ' KB');
  2094. }).catch(function (err) {
  2095. setStatus('Kernel self-test failed: ' + err.message);
  2096. });
  2097. }
  2098. function onCommand(id) {
  2099. closeMenu();
  2100. if (offsetBox.isOpen()) {
  2101. offsetBox.hide(); // another command: the offset plane is dropped
  2102. }
  2103. // The scene (lighting, shadows, ...) changes how things look, nothing more
  2104. if (sceneCommand(id)) {
  2105. return;
  2106. }
  2107. if (!VIEW_ONLY_COMMANDS.test(id)) {
  2108. releaseLeftButton();
  2109. }
  2110. const wasPicking = picking() ? state.mode : null;
  2111. if (wasPicking) {
  2112. leaveMode();
  2113. }
  2114. // Any command other than looking around puts an open feature panel away
  2115. const wasFeature = activeFeature ? activeFeature.kind : null;
  2116. if (activeFeature && !/^(nav|view|style|proj)\./.test(id)) {
  2117. activeFeature.tool.cancel();
  2118. }
  2119. // ... and an open Measure or Section panel (a section stays on)
  2120. const wasInspect = activeInspect ? activeInspect.kind : null;
  2121. if (activeInspect && !/^(nav|view|style|proj)\./.test(id)) {
  2122. closeInspect(true);
  2123. }
  2124. // ... and the Appearance panel (its own button toggles it)
  2125. const wasAppearance = appearanceTool.isOpen();
  2126. if (wasAppearance && !/^(nav|view|style|proj)\./.test(id)) {
  2127. appearanceTool.cancel();
  2128. }
  2129. const wasPaint = paintTool.isOpen();
  2130. if (wasPaint && !/^(nav|view|style|proj)\./.test(id)) {
  2131. paintTool.cancel();
  2132. }
  2133. const wasMaterial = materialTool.isOpen();
  2134. if (wasMaterial && !/^(nav|view|style|proj)\./.test(id)) {
  2135. materialTool.cancel();
  2136. }
  2137. const wasParams = paramTable.isOpen();
  2138. if (wasParams && !/^(nav|view|style|proj)\./.test(id)) {
  2139. paramTable.cancel();
  2140. }
  2141. if (id === 'manage.params') {
  2142. if (!wasParams && state.env === 'part') {
  2143. if (sketcher.isOpen()) {
  2144. finishSketch();
  2145. }
  2146. paramTable.start();
  2147. ribbon.setOn('manage.params', true);
  2148. }
  2149. return;
  2150. }
  2151. if (state.env === 'assembly' && assembly.command(id)) {
  2152. return;
  2153. }
  2154. if (state.env === 'drawing' && drawing.command(id)) {
  2155. return;
  2156. }
  2157. if (id === 'app.appearance') {
  2158. if (!wasAppearance && state.env === 'part') {
  2159. if (sketcher.isOpen()) {
  2160. finishSketch();
  2161. }
  2162. appearanceTool.start();
  2163. ribbon.setOn('app.appearance', true);
  2164. }
  2165. return;
  2166. }
  2167. if (id === 'app.material') {
  2168. if (!wasMaterial && state.env === 'part') {
  2169. if (sketcher.isOpen()) {
  2170. finishSketch();
  2171. }
  2172. materialTool.start();
  2173. ribbon.setOn('app.material', true);
  2174. }
  2175. return;
  2176. }
  2177. if (id === 'app.paint') {
  2178. if (!wasPaint && state.env === 'part') {
  2179. if (sketcher.isOpen()) {
  2180. finishSketch();
  2181. }
  2182. if (paintTool.start()) {
  2183. ribbon.setOn('app.paint', true);
  2184. }
  2185. }
  2186. return;
  2187. }
  2188. if (id === 'sketch.start') {
  2189. if (wasPicking === 'pick-sketch-plane' || state.mode === 'sketch') {
  2190. return; // second click cancels the pick; already sketching does nothing
  2191. }
  2192. startPlanePick('pick-sketch-plane', 'sketch.start', 'to create sketch');
  2193. } else if (id === 'nav.lookat') {
  2194. if (wasPicking !== 'pick-lookat') {
  2195. startPlanePick('pick-lookat', 'nav.lookat', 'to look at');
  2196. }
  2197. } else if (id === 'sketch.finish') {
  2198. finishSketch();
  2199. } else if (id === 'work.plane' || id === 'plane.offset') {
  2200. // First the plane or face to offset from, then the panel
  2201. if (wasPicking !== 'pick-workplane' && wasFeature !== 'plane') {
  2202. if (sketcher.isOpen()) {
  2203. finishSketch();
  2204. }
  2205. startPlanePick('pick-workplane', 'work.plane', 'to offset a work plane from');
  2206. }
  2207. } else if (id.indexOf('plane.') === 0) {
  2208. // The other kinds of work plane pick their references in the panel
  2209. featureTools.plane.prepareKind(id.slice(6));
  2210. startFeature('plane', null);
  2211. } else if (id === 'work.axis' || id === 'work.point') {
  2212. if (wasFeature !== id.slice(5)) {
  2213. startFeature(id.slice(5), null);
  2214. }
  2215. } else if (id.indexOf('pat.') === 0) {
  2216. const kind = { rect: 'rectpattern', circ: 'circpattern', mirror: 'mirror' }[id.slice(4)];
  2217. if (kind && wasFeature !== kind) {
  2218. startFeature(kind, null);
  2219. }
  2220. } else if (id.indexOf('feat.') === 0 && featureTools[id.slice(5)]) {
  2221. if (wasFeature !== id.slice(5)) {
  2222. startFeature(id.slice(5), null); // a second click on the button only closed the panel
  2223. }
  2224. } else if (state.mode === 'sketch' && id === 'sk.construction') {
  2225. sketcher.toggleConstruction();
  2226. } else if (state.mode === 'sketch' && id.indexOf('con.') === 0) {
  2227. // A second click on the active constraint tool puts it away
  2228. if (activeTool === 'con:' + id.slice(4)) {
  2229. sketcher.setTool('select');
  2230. } else {
  2231. sketcher.constrain(id.slice(4));
  2232. }
  2233. } else if (state.mode === 'sketch' && id.indexOf('sk.') === 0 && TOOL_BUTTONS[id.slice(3)]) {
  2234. const tool = id.slice(3);
  2235. sketcher.setTool(activeTool === tool ? 'select' : tool);
  2236. } else if (id === 'nav.zoomall') {
  2237. viewport.zoomAll();
  2238. } else if (id === 'nav.home') {
  2239. viewport.home();
  2240. } else if (id === 'view.origin') {
  2241. state.originVisible = !state.originVisible;
  2242. ribbon.setOn('view.origin', state.originVisible);
  2243. viewport.setOriginVisible(state.originVisible);
  2244. } else if (id === 'section.end') {
  2245. // "End Section View" puts the model back whole
  2246. viewport.setSection('none');
  2247. ribbon.setLabel('view.section', 'Section View');
  2248. setStatus('Section view ended');
  2249. } else if (id.indexOf('section.') === 0) {
  2250. startInspect('section', id.slice(8));
  2251. } else if (id === 'nav.pan' || id === 'nav.orbit') {
  2252. // Clicking the active one gives the left button back to selecting
  2253. const mode = id.slice(4);
  2254. setLeftDrag(state.leftDrag === mode ? 'select' : mode);
  2255. setStatus(state.leftDrag === 'select' ? 'Ready' : (mode === 'orbit' ? 'Orbit: drag inside the circle to turn, outside it to roll, on a tick to turn about one axis' : 'Pan: drag with the left button') +
  2256. '. Esc, the button again or any tool gives it back to selecting.');
  2257. } else if (id === 'ins.mass') {
  2258. showMassProperties();
  2259. } else if (id === 'ins.measure') {
  2260. if (wasInspect !== 'measure') {
  2261. startInspect('measure');
  2262. }
  2263. } else if (id === 'ins.check') {
  2264. if (wasInspect !== 'check') {
  2265. startInspect('check');
  2266. }
  2267. } else if (id.indexOf('style.') === 0) {
  2268. viewport.setVisualStyle(id.slice(6));
  2269. } else if (id.indexOf('proj.') === 0) {
  2270. viewport.setProjection(id.slice(5));
  2271. ribbon.setLabel('view.projection', id === 'proj.perspective' ? 'Perspective' : 'Orthographic');
  2272. } else if (id === 'diag.selftest') {
  2273. runSelfTest();
  2274. } else if (id === 'file.new') {
  2275. newDocument();
  2276. } else if (id === 'file.open') {
  2277. openDocument();
  2278. } else if (id === 'file.save') {
  2279. saveDocument(false);
  2280. } else if (id === 'file.saveas') {
  2281. saveDocument(true);
  2282. } else if (id.indexOf('export.') === 0) {
  2283. exportPart(id.slice(7));
  2284. } else if (id === 'import.step') {
  2285. importStep();
  2286. } else if (id === 'import.stl' || id === 'import.obj') {
  2287. importMesh(id.slice(7));
  2288. } else if (id === 'file.sample') {
  2289. loadDocument(sampleDocument(), sampleName('Sample Part'), '');
  2290. } else if (id === 'file.sampledrw') {
  2291. if (loadDocument(sampleDrawing(), sampleName('Sample Drawing'), '')) {
  2292. setStatus('Sample Drawing: views of the sample part and assembly with dimensions. Double click anything to edit it; Annotate > Dimension adds more.');
  2293. }
  2294. } else if (id === 'file.sampleasm') {
  2295. if (loadDocument(sampleAssembly(), sampleName('Sample Assembly'), '')) {
  2296. setStatus('Sample Assembly: a plate, two inserted pins and a block mated and flush. Try Free Move on a pin, or Inspect > Degrees of Freedom.');
  2297. }
  2298. } else if (id === 'edit.undo' || id === 'edit.redo') {
  2299. const label = id === 'edit.undo' ? activeDoc().undo() : activeDoc().redo();
  2300. if (label) {
  2301. setStatus((id === 'edit.undo' ? 'Undo: ' : 'Redo: ') + label);
  2302. }
  2303. } else {
  2304. const command = ribbon.find(id);
  2305. if (command && command.planned) {
  2306. setStatus(command.label + ' is not built yet. Planned for ' + command.planned + ', see PROPOSAL.md.');
  2307. } else {
  2308. setStatus('This command is not built yet, see PROPOSAL.md.');
  2309. }
  2310. }
  2311. }
  2312. document.addEventListener('keydown', function (event) {
  2313. const typing = event.target instanceof Element && event.target.closest('input, textarea');
  2314. if (typing || document.querySelector('.veil')) {
  2315. return; // typing in a field, or a dialog is open
  2316. }
  2317. if (appearanceTool.isOpen() && event.key === 'Escape') {
  2318. appearanceTool.cancel();
  2319. event.preventDefault();
  2320. return;
  2321. }
  2322. if (paintTool.isOpen() && event.key === 'Escape') {
  2323. paintTool.cancel();
  2324. event.preventDefault();
  2325. return;
  2326. }
  2327. if (offsetBox.isOpen() && event.key === 'Escape') {
  2328. offsetBox.hide();
  2329. event.preventDefault();
  2330. return;
  2331. }
  2332. if (activeInspect && activeInspect.tool.handleKey(event)) {
  2333. event.preventDefault();
  2334. return;
  2335. }
  2336. if (state.env === 'assembly' && !(event.ctrlKey || event.metaKey) && assembly.handleKey(event)) {
  2337. event.preventDefault();
  2338. return;
  2339. }
  2340. if (state.env === 'drawing' && !(event.ctrlKey || event.metaKey) && drawing.handleKey(event)) {
  2341. event.preventDefault();
  2342. return;
  2343. }
  2344. if (state.mode === 'feature' && activeFeature && activeFeature.tool.handleKey(event)) {
  2345. event.preventDefault();
  2346. return;
  2347. }
  2348. // An open sketch gets the first go: typed sizes, Esc, Delete
  2349. if (state.mode === 'sketch' && sketcher.handleKey(event)) {
  2350. event.preventDefault();
  2351. return;
  2352. }
  2353. const ctrl = event.ctrlKey || event.metaKey;
  2354. const key = event.key.toLowerCase();
  2355. let command = null;
  2356. if (ctrl && key === 'z') {
  2357. command = event.shiftKey ? 'edit.redo' : 'edit.undo';
  2358. } else if (ctrl && key === 'y') {
  2359. command = 'edit.redo';
  2360. } else if (ctrl && key === 's') {
  2361. command = event.shiftKey ? 'file.saveas' : 'file.save';
  2362. } else if (ctrl && key === 'o') {
  2363. command = 'file.open';
  2364. } else if (key === 'home') {
  2365. command = 'nav.home';
  2366. }
  2367. if (command) {
  2368. event.preventDefault();
  2369. onCommand(command);
  2370. return;
  2371. }
  2372. if (key === 'f5' && !ctrl && state.env !== 'drawing') {
  2373. // Previous View, as in desktop CAD (the browser's reload is Ctrl+F5 / Ctrl+R)
  2374. event.preventDefault();
  2375. const view = viewHistory.pop();
  2376. if (view) {
  2377. viewport.setViewState(view);
  2378. setStatus('Previous view' + (viewHistory.length ? '' : ': this was the first one kept'));
  2379. } else {
  2380. setStatus('No previous view: the view has not changed yet');
  2381. }
  2382. return;
  2383. }
  2384. if (key === 'f6' && state.env !== 'drawing') {
  2385. event.preventDefault();
  2386. onCommand('nav.home'); // Home View
  2387. return;
  2388. }
  2389. if (key === 'f4' && !event.repeat && state.leftDrag !== 'orbit') {
  2390. // Held down, F4 turns the left button into orbit, as in desktop CAD
  2391. event.preventDefault();
  2392. heldOrbit = state.leftDrag;
  2393. setLeftDrag('orbit');
  2394. return;
  2395. }
  2396. if (key === 'escape' && state.leftDrag !== 'select') {
  2397. setLeftDrag('select');
  2398. setStatus('Ready');
  2399. return;
  2400. }
  2401. if (key === 'escape') {
  2402. closeMenu();
  2403. if (picking()) {
  2404. leaveMode();
  2405. setStatus('Ready');
  2406. } else if (state.mode === 'model') {
  2407. viewport.clearSelection();
  2408. }
  2409. } else if (state.env === 'part' && state.mode === 'model' && browser.selected()) {
  2410. if (key === 'delete') {
  2411. deleteFeature(browser.selected());
  2412. } else if (key === 'f2') {
  2413. event.preventDefault();
  2414. browser.startRename(browser.selected());
  2415. }
  2416. }
  2417. });
  2418. let heldOrbit = null; // what the left button did before F4 was pressed
  2419. document.addEventListener('keyup', function (event) {
  2420. if (event.key === 'F4' && heldOrbit !== null) {
  2421. setLeftDrag(heldOrbit);
  2422. heldOrbit = null;
  2423. }
  2424. });
  2425. /* ================= engines ================= */
  2426. const kernel = createKernel({
  2427. onProgress: function (info) {
  2428. if (info.step === 'download') {
  2429. kernelTask.update({
  2430. text: 'Downloading the modelling kernel: ' + megabytes(info.loaded, info.total),
  2431. fraction: info.total > 0 ? info.loaded / info.total : null
  2432. });
  2433. } else if (info.step === 'compile') {
  2434. kernelTask.update({ text: 'Preparing the modelling kernel', fraction: null });
  2435. }
  2436. },
  2437. onReady: function (ms) {
  2438. state.kernelReady = true;
  2439. setEngine('status-kernel', 'ok', 'OpenCascade geometry kernel ready (started in ' + (ms / 1000).toFixed(1) + ' s)');
  2440. kernelTask.done();
  2441. },
  2442. onFailed: function (error) {
  2443. setEngine('status-kernel', 'bad', 'The geometry kernel failed to start: ' + error);
  2444. endOpening();
  2445. kernelTask.update({ title: 'The modelling kernel could not be loaded', text: error, error: true });
  2446. setStatus('The modelling kernel could not be loaded: ' + error);
  2447. }
  2448. });
  2449. function featureOptions(kind) {
  2450. return {
  2451. kind: kind,
  2452. stage: $('stage'),
  2453. viewport: viewport,
  2454. kernel: kernel,
  2455. doc: doc,
  2456. onStatus: setStatus,
  2457. // The plane reference of a picked plane or face (To, Linear holes)
  2458. referenceOf: referenceOf,
  2459. onClose: function () {
  2460. featureClosed(kind);
  2461. }
  2462. };
  2463. }
  2464. const featureTools = {
  2465. extrude: createExtrude(featureOptions('extrude')),
  2466. revolve: createRevolve(featureOptions('revolve')),
  2467. shell: createShell(featureOptions('shell')),
  2468. rectpattern: createPattern(Object.assign(featureOptions('rectpattern'), { kind: 'rect' })),
  2469. circpattern: createPattern(Object.assign(featureOptions('circpattern'), { kind: 'circ' })),
  2470. mirror: createPattern(Object.assign(featureOptions('mirror'), { kind: 'mirror' })),
  2471. fillet: createEdgeFeature(featureOptions('fillet')),
  2472. chamfer: createEdgeFeature(featureOptions('chamfer')),
  2473. hole: createHole(featureOptions('hole')),
  2474. plane: createWorkFeature('plane', workOptions('plane')),
  2475. axis: createWorkFeature('axis', workOptions('axis')),
  2476. point: createWorkFeature('point', workOptions('point')),
  2477. repair: createRepair(featureOptions('repair')),
  2478. sweep: createSweep(featureOptions('sweep')),
  2479. loft: createLoft(featureOptions('loft')),
  2480. draft: createDraft(featureOptions('draft'))
  2481. };
  2482. // The work feature panels show what they set up as drafts, and take plane
  2483. // picks as the references sketches use
  2484. function workOptions(kind) {
  2485. return Object.assign(featureOptions(kind), {
  2486. referenceOf: referenceOf,
  2487. onDraft: function (draft, editing) {
  2488. const id = editing || null;
  2489. draftPlane = draft && draft.frame ? { frame: draft.frame, id: id } : null;
  2490. draftAxis = draft && draft.line ? { line: draft.line, id: id } : null;
  2491. draftPoint = draft && draft.at ? { at: draft.at, id: id } : null;
  2492. refreshWorkPlanes();
  2493. }
  2494. });
  2495. }
  2496. // The assembly environment (js/assembly/), and the Measure and Section
  2497. // View panels both environments share
  2498. const assembly = createAssembly({
  2499. viewport: viewport,
  2500. kernel: kernel,
  2501. files: files,
  2502. ribbon: ribbon,
  2503. stage: $('stage'),
  2504. canvas: $('viewport'),
  2505. tree: $('asm-tree'),
  2506. setStatus: setStatus,
  2507. setPrompt: setPrompt,
  2508. ask: ask,
  2509. tell: tell,
  2510. onChange: refreshChrome,
  2511. // Open Part: the part's file in a tab of this window
  2512. onProgress: documentProgress,
  2513. openPath: function (path) {
  2514. const reading = beginOpening(String(path).split('/').pop());
  2515. files.readPath(path).then(function (file) {
  2516. if (loadDocument(file.data, file.name, file.path, file.preview)) {
  2517. setStatus('Opened ' + files.displayPath(path) + ' in a tab. Changes show in the assembly when its tab is shown again.');
  2518. }
  2519. }).catch(function (err) {
  2520. endOpening(reading);
  2521. fail('The part could not be opened', err);
  2522. });
  2523. }
  2524. });
  2525. const drawing = createDrawing({
  2526. onProgress: documentProgress,
  2527. viewport: viewport,
  2528. kernel: kernel,
  2529. files: files,
  2530. ribbon: ribbon,
  2531. stage: $('stage'),
  2532. canvas: $('viewport'),
  2533. sheetHost: $('sheet-stage'),
  2534. tree: $('drw-tree'),
  2535. setStatus: setStatus,
  2536. setPrompt: setPrompt,
  2537. ask: ask,
  2538. tell: tell,
  2539. openMenu: openMenu,
  2540. onCommand: function (id) {
  2541. onCommand(id);
  2542. },
  2543. onChange: refreshChrome,
  2544. onShow3D: function (on) {
  2545. showSheetChrome(!on);
  2546. }
  2547. });
  2548. const measurePart = createMeasure({
  2549. stage: $('stage'),
  2550. viewport: viewport,
  2551. onStatus: setStatus,
  2552. measure: partDistance,
  2553. onClose: function () {
  2554. inspectClosed('measure');
  2555. }
  2556. });
  2557. // Inspect > Check Geometry; its Repair... button opens the Repair feature
  2558. const checkPanel = createCheckPanel({
  2559. stage: $('stage'),
  2560. viewport: viewport,
  2561. kernel: kernel,
  2562. onStatus: setStatus,
  2563. onRepair: function () {
  2564. startFeature('repair', null);
  2565. },
  2566. onClose: function () {
  2567. inspectClosed('check');
  2568. }
  2569. });
  2570. const measureAssembly = createMeasure({
  2571. stage: $('stage'),
  2572. viewport: viewport,
  2573. onStatus: setStatus,
  2574. components: true,
  2575. measure: function (a, b) {
  2576. return assembly.measure(a, b);
  2577. },
  2578. name: function (item) {
  2579. return assembly.nameOf(item);
  2580. },
  2581. onClose: function () {
  2582. inspectClosed('measure');
  2583. }
  2584. });
  2585. const appearanceTool = createAppearancePanel({
  2586. stage: $('stage'),
  2587. viewport: viewport,
  2588. doc: doc,
  2589. onStatus: setStatus,
  2590. onClose: function () {
  2591. ribbon.setOn('app.appearance', false);
  2592. },
  2593. // A picture for the Image finish, made smaller and kept in the part
  2594. pickImage: function () {
  2595. return files.openOther(IMAGE_EXTENSIONS, true).then(function (file) {
  2596. return file ? toTextureImage(file.bytes, file.name) : null;
  2597. });
  2598. }
  2599. });
  2600. // Projected sketch geometry follows its model edges (PROPOSAL.md 14.5 C):
  2601. // the rebuild reports projected curves whose edges moved; they are moved
  2602. // in the sketch, the sketch is solved again (headless) so what is tied to
  2603. // them follows, and the part rebuilds. Not an undo step of its own. A
  2604. // sketch that cannot be solved that way keeps its geometry (said once).
  2605. let followPasses = 0;
  2606. const followSaid = new Set();
  2607. function followModel(projections) {
  2608. const ids = Object.keys(projections || {}).filter(function (id) {
  2609. return doc.feature(id) && !(sketcher.isOpen() && sketcher.featureId() === id) &&
  2610. !followSaid.has(id + JSON.stringify(projections[id]));
  2611. });
  2612. if (!ids.length) {
  2613. followPasses = 0;
  2614. return;
  2615. }
  2616. if (++followPasses > 4) {
  2617. followPasses = 0;
  2618. setStatus('Projected sketch geometry could not settle on the model; open the sketch to check it');
  2619. return;
  2620. }
  2621. if (!headlessSolver) {
  2622. headlessSolver = solver.createSolver();
  2623. }
  2624. headlessSolver.then(function (s) {
  2625. const said = [];
  2626. doc.amend(function (d) {
  2627. ids.forEach(function (id) {
  2628. const sketch = d.features.find(function (f) {
  2629. return f.id === id;
  2630. });
  2631. if (!sketch) {
  2632. return;
  2633. }
  2634. const before = JSON.stringify(sketch.geometry);
  2635. const out = applyFollow(sketch, projections[id]);
  2636. if (out.lost.length) {
  2637. followSaid.add(id + JSON.stringify(projections[id]));
  2638. said.push(sketch.name + ': ' + (out.lost.length === 1 ? 'a projected edge is' : out.lost.length + ' projected edges are') +
  2639. ' no longer in the model and stay' + (out.lost.length === 1 ? 's' : '') + ' where ' + (out.lost.length === 1 ? 'it was' : 'they were'));
  2640. }
  2641. if (out.moved && !s.solve(sketch).ok) {
  2642. // The constraints cannot be met with the edges where they
  2643. // are now: keep the sketch as it was
  2644. sketch.geometry = JSON.parse(before);
  2645. followSaid.add(id + JSON.stringify(projections[id]));
  2646. said.push(sketch.name + ' cannot follow the model: its constraints cannot be met with the edges where they are now. Open it to fix them');
  2647. }
  2648. });
  2649. });
  2650. if (said.length) {
  2651. setStatus(said[0]);
  2652. }
  2653. }).catch(function (err) {
  2654. setStatus('Projected sketch geometry could not follow the model: ' + err.message);
  2655. });
  2656. }
  2657. // Manage > Parameters. OK works every kept formula out again and solves
  2658. // the sketches whose dimensions changed (the sketch solver, headless), as
  2659. // one undo step; a sketch that cannot meet its new sizes keeps its old ones
  2660. let headlessSolver = null;
  2661. const paramTable = createParameterTable({
  2662. stage: $('stage'),
  2663. doc: doc,
  2664. onStatus: setStatus,
  2665. onClose: function () {
  2666. ribbon.setOn('manage.params', false);
  2667. },
  2668. onApply: function (list) {
  2669. if (!headlessSolver) {
  2670. headlessSolver = solver.createSolver();
  2671. }
  2672. headlessSolver.then(function (s) {
  2673. const problems = [];
  2674. doc.change('Parameters', function (d) {
  2675. if (list.length) {
  2676. d.parameters = list;
  2677. } else {
  2678. delete d.parameters;
  2679. }
  2680. const before = {};
  2681. d.features.forEach(function (f) {
  2682. if (f.type === 'sketch') {
  2683. before[f.id] = (f.constraints || []).map(function (c) {
  2684. return c.value;
  2685. });
  2686. }
  2687. });
  2688. const out = applyParameters(d);
  2689. problems.push.apply(problems, out.problems);
  2690. out.sketches.forEach(function (id) {
  2691. const sketch = d.features.find(function (f) {
  2692. return f.id === id;
  2693. });
  2694. // Only the dimensions whose value changed move anything
  2695. const changed = (sketch.constraints || []).filter(function (c, i) {
  2696. return c.value !== before[id][i];
  2697. }).map(function (c) {
  2698. return c.id;
  2699. });
  2700. const solved = s.solveChange(sketch, changed);
  2701. if (!solved.ok) {
  2702. (sketch.constraints || []).forEach(function (c, i) {
  2703. c.value = before[id][i];
  2704. });
  2705. problems.push(sketch.name + ' cannot meet its dimensions with these values: it keeps its old sizes');
  2706. }
  2707. });
  2708. });
  2709. setStatus(problems.length ? problems[0] + (problems.length > 1 ? ' (and ' + (problems.length - 1) + ' more)' : '')
  2710. : 'Parameters applied' + (list.length ? ': ' + list.length + (list.length === 1 ? ' parameter' : ' parameters') : ''));
  2711. }).catch(function (err) {
  2712. fail('The parameters could not be applied', err);
  2713. });
  2714. }
  2715. });
  2716. const materialTool = createMaterialPanel({
  2717. stage: $('stage'),
  2718. doc: doc,
  2719. onStatus: setStatus,
  2720. onClose: function () {
  2721. ribbon.setOn('app.material', false);
  2722. }
  2723. });
  2724. const paintTool = createPaintPanel({
  2725. stage: $('stage'),
  2726. viewport: viewport,
  2727. doc: doc,
  2728. onStatus: setStatus,
  2729. onClose: function () {
  2730. ribbon.setOn('app.paint', false);
  2731. }
  2732. });
  2733. /* ================= the scene (Appearance tab) ================= */
  2734. // How this viewer likes to see models; kept in this browser, not in parts
  2735. const SCENE_KEY = '3dmodeler.scene';
  2736. let sceneOpts = normalizeScene(null);
  2737. try {
  2738. sceneOpts = normalizeScene(JSON.parse(window.localStorage.getItem(SCENE_KEY) || 'null'));
  2739. } catch (e) {
  2740. // No storage (private window, blocked site data): the defaults
  2741. }
  2742. function applyScene(save) {
  2743. viewport.setScene(sceneOpts);
  2744. ribbon.setOn('scene.reflections', sceneOpts.reflections);
  2745. ribbon.setOn('scene.shadows', sceneOpts.shadows);
  2746. ribbon.setOn('scene.ground', sceneOpts.ground);
  2747. ribbon.setOn('scene.textures', sceneOpts.textures);
  2748. if (save) {
  2749. try {
  2750. window.localStorage.setItem(SCENE_KEY, JSON.stringify(sceneOpts));
  2751. } catch (e) {
  2752. // Not kept: it still applies until the window closes
  2753. }
  2754. }
  2755. }
  2756. const SCENE_FLAGS = {
  2757. 'scene.reflections': ['reflections', 'Reflections'],
  2758. 'scene.shadows': ['shadows', 'Ground shadow'],
  2759. 'scene.ground': ['ground', 'Ground plane'],
  2760. 'scene.textures': ['textures', 'Textures']
  2761. };
  2762. function sceneCommand(id) {
  2763. const flag = SCENE_FLAGS[id];
  2764. if (flag) {
  2765. sceneOpts[flag[0]] = !sceneOpts[flag[0]];
  2766. applyScene(true);
  2767. setStatus(flag[1] + (sceneOpts[flag[0]] ? ' on' : ' off'));
  2768. return true;
  2769. }
  2770. if (id.indexOf('light.') === 0) {
  2771. sceneOpts.lighting = lightingById(id.slice(6)).id;
  2772. applyScene(true);
  2773. setStatus('Lighting: ' + lightingById(sceneOpts.lighting).label);
  2774. return true;
  2775. }
  2776. return false;
  2777. }
  2778. applyScene(false);
  2779. const sectionPanel = createSectionPanel({
  2780. stage: $('stage'),
  2781. viewport: viewport,
  2782. onStatus: setStatus,
  2783. onClose: function () {
  2784. inspectClosed('section');
  2785. }
  2786. });
  2787. solver.selfTest().then(function (result) {
  2788. if (result.ok) {
  2789. setEngine('status-solver', 'ok', 'planegcs sketch solver ready (test sketch solved in ' + result.ms.toFixed(1) + ' ms)');
  2790. } else {
  2791. setEngine('status-solver', 'bad', 'The sketch solver returned a wrong answer on its test sketch');
  2792. }
  2793. }).catch(function (err) {
  2794. setEngine('status-solver', 'bad', 'The sketch solver failed to start: ' + (err && err.message ? err.message : err));
  2795. });
  2796. /* ================= start ================= */
  2797. // The first tab: an empty part, until a file is opened into its place
  2798. const firstTab = { id: 't' + (++tabSeq), kind: 'part', snap: null, view: null };
  2799. tabs.push(firstTab);
  2800. activeTab = firstTab;
  2801. kernel.call('useRebuilder', { key: 'part:' + firstTab.id }).catch(function () {
  2802. // The kernel failed to start; the status bar says so
  2803. });
  2804. initTheme();
  2805. browser.render();
  2806. refreshSketches();
  2807. refreshWorkPlanes();
  2808. ribbon.setMode('part');
  2809. refreshChrome();
  2810. ribbon.showTab('model');
  2811. // Unsaved work of a window that crashed, was reloaded or was closed
  2812. setTimeout(offerAutosaves, 600);
  2813. // A file handed over from outside the window: the File Manager's "Open
  2814. // with 3D Modeler", or in the Mac app Finder, the Dock and Open Recent
  2815. function openHandedOver(path) {
  2816. if (/\.(step|stp)$/i.test(path)) {
  2817. // A STEP file opened with 3D Modeler starts a new part with it imported
  2818. return files.readText(path).then(function (file) {
  2819. loadDocument(null, file.name.replace(/\.[^.]+$/, ''), '');
  2820. return addImport(file);
  2821. }).catch(function (err) {
  2822. fail('The file could not be imported', err);
  2823. });
  2824. }
  2825. // A part, an assembly or a drawing: loadDocument goes by the file's format
  2826. const reading = beginOpening(String(path).split('/').pop());
  2827. return files.readPath(path).then(function (file) {
  2828. if (loadDocument(file.data, file.name, file.path, file.preview)) {
  2829. setStatus('Opened ' + files.displayPath(file.path));
  2830. }
  2831. }).catch(function (err) {
  2832. endOpening(reading);
  2833. fail('The file could not be opened', err);
  2834. });
  2835. }
  2836. const launch = files.launchPath();
  2837. if (launch) {
  2838. openHandedOver(launch);
  2839. }
  2840. /* ================= the Mac app (io/native.js) ================= */
  2841. // The menu bar items the page carries out. Undo and Redo in a text field
  2842. // being typed in act on the typing, as the keys do.
  2843. const MENU_COMMANDS = /^(file\.(new|open|save|saveas)|import\.step|export\.(step|stl|obj|3mf|brep)|dexport\.(pdf|dxf|svg|png)|nav\.(home|zoomall))$/;
  2844. function nativeMenu(command) {
  2845. const el = document.activeElement;
  2846. const typing = el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);
  2847. if ((command === 'edit.undo' || command === 'edit.redo') && typing) {
  2848. document.execCommand(command === 'edit.undo' ? 'undo' : 'redo');
  2849. return;
  2850. }
  2851. if (document.querySelector('.veil')) {
  2852. return; // a question is open: it is answered first, as with the keys
  2853. }
  2854. if (command === 'tab.close') {
  2855. if (activeTab) {
  2856. closeTab(activeTab);
  2857. }
  2858. } else if (command === 'edit.undo' || command === 'edit.redo' || MENU_COMMANDS.test(command)) {
  2859. onCommand(command);
  2860. }
  2861. }
  2862. // Files waiting in the shell, one tab each, in the order they came
  2863. function takeHandedOver() {
  2864. native.takeOpened().then(function (list) {
  2865. return list.reduce(function (chain, file) {
  2866. return chain.then(function () {
  2867. return openHandedOver(file.path);
  2868. });
  2869. }, Promise.resolve());
  2870. }).catch(function (err) {
  2871. fail('The file could not be opened', err);
  2872. });
  2873. }
  2874. if (native.available()) {
  2875. native.handle({
  2876. // The close button or Quit: true closes now; otherwise the page asks
  2877. // and tells the shell what the person chose
  2878. requestClose: function () {
  2879. if (!tabs.some(tabDirty)) {
  2880. closingOnPurpose();
  2881. return true;
  2882. }
  2883. confirmCloseAll().then(function (ok) {
  2884. if (ok) {
  2885. closingOnPurpose();
  2886. return native.closeWindow();
  2887. }
  2888. return native.closeCancelled();
  2889. }).catch(function () {
  2890. native.closeCancelled();
  2891. });
  2892. return false;
  2893. },
  2894. menu: nativeMenu,
  2895. opened: takeHandedOver
  2896. });
  2897. takeHandedOver();
  2898. }