diff --git a/apps/web/public/assets/sketchforge/sketchforge-logo-white.png b/apps/web/public/assets/sketchforge/sketchforge-logo-white.png new file mode 100644 index 0000000..55101c3 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketchforge-logo-white.png differ diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 6a1bc3c..30d79a8 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -57,6 +57,339 @@ button { display: block; } +.editor-loading-screen { + position: fixed; + inset: 0; + z-index: 200; + min-width: 320px; + overflow: hidden; + background: #f8fafb; + animation: editor-loading-enter 160ms ease-out both; +} + +.editor-skeleton-shimmer { + position: relative; + display: block; + overflow: hidden; + background: #dce5eb; + border-radius: 5px; +} + +.editor-skeleton-shimmer::after { + position: absolute; + inset: 0; + content: ""; + background: linear-gradient( + 105deg, + transparent 18%, + rgba(255, 255, 255, 0.34) 38%, + rgba(255, 255, 255, 0.78) 50%, + rgba(255, 255, 255, 0.34) 62%, + transparent 82% + ); + transform: translateX(-115%); + animation: editor-skeleton-shimmer 1.55s ease-in-out infinite; +} + +.editor-loading-toolbar { + position: absolute; + inset: 0 0 auto 0; + z-index: 1; + height: var(--editor-toolbar-height); + background: #f2f6f8; + border-bottom: 1px solid #d2dce5; + box-shadow: 0 1px 2px rgba(32, 54, 72, 0.05); +} + +.editor-loading-tabs { + position: absolute; + top: 0; + left: 10px; + display: flex; + width: 209px; + height: 32px; + align-items: center; + gap: 22px; + padding: 0 14px; +} + +.editor-loading-tabs span:first-child { + width: 76px; + height: 8px; + border-radius: 999px; +} + +.editor-loading-tabs span:last-child { + width: 54px; + height: 7px; + border-radius: 999px; +} + +.editor-loading-tool-groups { + position: absolute; + inset: 32px 0 0 0; + display: flex; + align-items: stretch; + background: #f4f7f9; + border-top: 1px solid #dde5eb; +} + +.editor-loading-tool-cluster { + display: flex; + height: var(--editor-toolbar-tools-height); +} + +.editor-loading-toolbar-spacer { + min-width: 0; + flex: 1; +} + +.editor-loading-tool-section { + position: relative; + height: var(--editor-toolbar-tools-height); + flex: 0 0 auto; + background: linear-gradient(90deg, rgba(255, 255, 255, 0.45), rgba(255, 255, 255, 0.08) 44%, rgba(210, 222, 232, 0.16)); + border-right: 1px solid #d7e0e8; +} + +.editor-loading-tool-section.home { width: 88.8px; } +.editor-loading-tool-section.clipboard { width: 178.8px; } +.editor-loading-tool-section.history { width: 92.8px; } +.editor-loading-tool-section.shapes { width: 82px; } +.editor-loading-tool-section.visibility { width: 92.8px; } +.editor-loading-tool-section.combine { width: 135.8px; } +.editor-loading-tool-section.modify { width: 221.8px; } +.editor-loading-tool-section.arrange { width: 92.8px; } +.editor-loading-tool-section.manage { width: 152px; } + +.editor-loading-section-label { + position: absolute; + top: 7px; + left: 50%; + width: min(64px, calc(100% - 18px)); + height: 7px; + border-radius: 999px; + transform: translateX(-50%); +} + +.editor-loading-section-controls { + position: absolute; + top: 28px; + left: 50%; + display: flex; + transform: translateX(-50%); +} + +.editor-loading-tool-section.manage .editor-loading-section-controls { + gap: 5px; +} + +.editor-loading-tool { + width: 43px; + height: 43px; + flex: 0 0 43px; + border-radius: 8px; +} + +.editor-loading-tool-section.shapes .editor-loading-tool { + width: 45px; + flex-basis: 45px; +} + +.editor-loading-tool-section:nth-child(even) .editor-skeleton-shimmer::after, +.editor-loading-tool-cluster:last-child .editor-loading-tool-section:nth-child(odd) .editor-skeleton-shimmer::after { + animation-delay: -520ms; +} + +.editor-loading-model .editor-skeleton-shimmer::after { + animation-delay: -960ms; +} + +.editor-loading-body { + position: absolute; + inset: var(--editor-toolbar-height) 0 0 0; + display: flex; + min-height: 0; +} + +.editor-loading-viewport { + position: relative; + width: 100%; + height: 100%; + overflow: hidden; + background-color: #f7fafb; + background-image: + linear-gradient(rgba(136, 180, 198, 0.12) 1px, transparent 1px), + linear-gradient(90deg, rgba(136, 180, 198, 0.12) 1px, transparent 1px); + background-position: center; + background-size: 28px 28px; +} + +.editor-loading-viewport::after { + position: absolute; + top: 52%; + left: 50%; + width: min(64vw, 760px); + height: min(48vw, 520px); + content: ""; + background: radial-gradient(ellipse, rgba(80, 119, 138, 0.09), transparent 68%); + transform: translate(-50%, -50%); +} + +.editor-loading-view-cube { + position: absolute; + top: 22px; + left: 28px; + z-index: 2; + width: 82px; + height: 82px; +} + +.editor-loading-view-cube span { + position: absolute; + border-radius: 5px; +} + +.editor-loading-cube-top { + top: 3px; + left: 13px; + width: 56px; + height: 39px; + clip-path: polygon(50% 0, 100% 38%, 50% 100%, 0 38%); +} + +.editor-loading-cube-left { + top: 28px; + left: 9px; + width: 35px; + height: 48px; + clip-path: polygon(0 0, 100% 21%, 100% 100%, 0 79%); +} + +.editor-loading-cube-right { + top: 28px; + left: 44px; + width: 35px; + height: 48px; + clip-path: polygon(0 21%, 100% 0, 100% 79%, 0 100%); +} + +.editor-loading-model { + position: absolute; + top: 51%; + left: 48%; + z-index: 2; + width: 182px; + height: 160px; + transform: translate(-50%, -50%); +} + +.editor-loading-model span { + position: absolute; + border-radius: 8px; + box-shadow: 0 10px 24px rgba(48, 77, 94, 0.08); +} + +.editor-loading-model-top { + top: 9px; + left: 24px; + width: 132px; + height: 66px; + clip-path: polygon(50% 0, 100% 44%, 50% 100%, 0 44%); +} + +.editor-loading-model-front { + top: 66px; + left: 24px; + width: 66px; + height: 78px; + clip-path: polygon(0 0, 100% 27%, 100% 100%, 0 72%); +} + +.editor-loading-model-side { + top: 66px; + left: 90px; + width: 66px; + height: 78px; + clip-path: polygon(0 27%, 100% 0, 100% 72%, 0 100%); +} + +.editor-loading-viewport-controls { + position: absolute; + top: 173px; + left: 10px; + z-index: 2; + display: grid; + width: 56px; + height: 241px; + padding: 5px 6px; + align-content: start; + gap: 2px; + background: rgba(255, 255, 255, 0.84); + border: 1px solid #d7e1e8; + border-radius: 18px; + box-shadow: 0 4px 14px rgba(32, 55, 72, 0.12); +} + +.editor-loading-viewport-controls span { + width: 44px; + height: 43px; + border-radius: 9px; +} + +.editor-loading-viewport-controls span:last-child { + margin-top: 4px; +} + +.editor-loading-status { + position: absolute; + bottom: 18px; + left: 64px; + z-index: 2; + width: 70px; + height: 37px; + border-radius: 3px; +} + +.editor-loading-snap { + position: absolute; + right: 12px; + bottom: 11px; + z-index: 2; + width: 75px; + height: 22px; + border-radius: 2px; +} + +@keyframes editor-loading-enter { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes editor-skeleton-shimmer { + 0% { transform: translateX(-115%); } + 58%, + 100% { transform: translateX(115%); } +} + +@media (max-width: 720px) { + .editor-loading-toolbar-spacer { + min-width: 80px; + } +} + +@media (prefers-reduced-motion: reduce) { + .editor-loading-screen { + animation: none; + } + + .editor-skeleton-shimmer::after { + animation: none; + opacity: 0.45; + transform: translateX(20%); + } +} + .dashboard-shell { width: 100vw; height: 100vh; @@ -71,51 +404,71 @@ button { top: 0; z-index: 8; display: grid; - grid-template-columns: minmax(210px, 280px) minmax(180px, 1fr) auto; - gap: 18px; + grid-template-columns: minmax(210px, 1fr) minmax(280px, 620px) minmax(210px, 1fr); + gap: 28px; align-items: center; + width: 100%; + height: 64px; min-height: 64px; - padding: 10px 22px; - background: rgba(250, 252, 253, 0.96); - border-bottom: 1px solid #d8e1e8; - box-shadow: 0 1px 4px rgba(28, 49, 68, 0.08); + padding: 0 14px; + color: #ffffff; + background: #0e69f1; + border-bottom: 0; + box-shadow: none; + font-family: Arial, Helvetica, sans-serif; } .dashboard-brand { display: inline-flex; + width: max-content; min-width: 0; align-items: center; - gap: 10px; - color: #213c55; + gap: 11px; + color: #ffffff; background: transparent; cursor: pointer; + text-decoration: none; } .dashboard-brand img { - width: 42px; - height: 42px; display: block; + width: 46px; + height: 46px; + object-fit: contain; } .dashboard-brand span { overflow: hidden; - font-size: 18px; - font-weight: 800; + font-size: 20px; + font-weight: 750; + letter-spacing: -0.02em; text-overflow: ellipsis; white-space: nowrap; } +.dashboard-brand:hover { + opacity: 0.82; +} + +.dashboard-brand:focus-visible, +.dashboard-primary:focus-visible { + outline: 3px solid #ffce47; + outline-offset: 4px; +} + .dashboard-search { display: flex; + width: 100%; min-width: 0; height: 40px; align-items: center; gap: 8px; padding: 0 12px; - color: #6a7d8f; - background: #edf3f7; - border: 1px solid #d3dee7; - border-radius: 6px; + color: #5f7387; + background: #ffffff; + border: 1px solid rgba(255, 255, 255, 0.78); + border-radius: 7px; + box-shadow: 0 2px 8px rgba(7, 48, 113, 0.16); } .dashboard-search input { @@ -143,20 +496,22 @@ button { .dashboard-primary { display: inline-flex; - height: 40px; + justify-self: end; + height: 42px; align-items: center; gap: 7px; justify-content: center; - padding: 0 16px; - color: white; - background: #009cde; - border-radius: 6px; - box-shadow: 0 2px 5px rgba(0, 114, 164, 0.24); + padding: 0 18px; + color: #0e69f1; + background: #ffffff; + border-radius: 7px; + box-shadow: none; cursor: pointer; + font-weight: 750; } .dashboard-primary:hover { - background: #008dcc; + background: #edf4ff; } .dashboard-layout { @@ -166,9 +521,14 @@ button { } .dashboard-sidebar { + position: sticky; + top: 64px; display: flex; flex-direction: column; justify-content: space-between; + align-self: start; + width: 100%; + height: calc(100vh - 64px); padding: 18px 12px; background: #ffffff; border-right: 1px solid #d9e3ea; @@ -205,8 +565,8 @@ button { .dashboard-nav-item:hover, .dashboard-nav-item.active { - color: #0a6f9b; - background: #e8f6fc; + color: #0e69f1; + background: #edf4ff; } .dashboard-nav-item:focus { @@ -214,7 +574,7 @@ button { } .dashboard-nav-item:focus-visible { - box-shadow: inset 0 0 0 2px #52bfe9; + box-shadow: inset 0 0 0 2px #0e69f1; } .dashboard-settings-button { @@ -272,14 +632,14 @@ button { .dashboard-action-tile:hover, .project-card:hover { - border-color: #98d9ee; + border-color: #8bbaf7; box-shadow: 0 5px 15px rgba(32, 61, 82, 0.12); transform: translateY(-1px); } .dashboard-action-tile.create { - border-color: #8fd9f1; - background: #f4fcff; + border-color: #8bbaf7; + background: #f5f8ff; } .dashboard-action-icon { @@ -289,7 +649,7 @@ button { height: 44px; place-items: center; color: #ffffff; - background: #00aeea; + background: #0e69f1; border-radius: 8px; } @@ -896,6 +1256,9 @@ button { @media (max-width: 860px) { .dashboard-topbar { grid-template-columns: 1fr auto; + height: auto; + padding: 8px 12px; + gap: 10px 14px; } .dashboard-search { @@ -907,8 +1270,11 @@ button { } .dashboard-sidebar { + position: static; display: flex; flex-direction: row; + align-self: stretch; + height: auto; gap: 8px; padding: 10px; border-right: 0; @@ -3407,7 +3773,7 @@ button { flex-direction: column; gap: 2px; padding: 5px; - background: rgba(255, 255, 255, 0.86); + background: #f4f7f9; border: 1px solid rgba(194, 209, 219, 0.9); border-radius: 17px; box-shadow: 0 10px 30px rgba(32, 64, 84, 0.14), 0 2px 6px rgba(32, 64, 84, 0.08); @@ -4107,6 +4473,8 @@ button { width: 320px; max-height: none; overflow-y: auto; + -ms-overflow-style: none; + scrollbar-width: none; color: #243d56; background: rgba(244, 246, 248, 0.96); border-left: 1px solid #d8e0e7; @@ -4122,11 +4490,9 @@ button { .shape-inspector.sketch-revolve-inspector, .shape-inspector.gear-inspector { overflow-anchor: none; - scrollbar-width: none; } -.shape-inspector.sketch-revolve-inspector::-webkit-scrollbar, -.shape-inspector.gear-inspector::-webkit-scrollbar { +.shape-inspector::-webkit-scrollbar { display: none; } @@ -5010,14 +5376,185 @@ button { accent-color: #0098c7; } -.workspace-color-button { +.workspace-grid-color-row { + align-items: start; +} + +.workspace-grid-color-row > span { + padding-top: 10px; +} + +.workspace-color-control { + position: relative; + display: grid; + width: min(100%, 286px); justify-self: end; - width: 22px; - height: 22px; - background: var(--workspace-bg); - border: 1px solid #b7c5cf; - border-radius: 2px; + gap: 8px; +} + +.workspace-color-trigger { + display: grid; + width: 100%; + height: 42px; + grid-template-columns: 28px minmax(0, 1fr) 16px; + align-items: center; + gap: 10px; + padding: 0 11px; + color: #354e64; + background: #f7fafc; + border: 1px solid #cbd8e1; + border-radius: 9px; cursor: pointer; + font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace; + font-size: 12px; + font-weight: 800; + letter-spacing: 0.03em; + text-align: left; + transition: background 140ms ease, border-color 140ms ease, box-shadow 140ms ease; +} + +.workspace-color-trigger:hover, +.workspace-color-trigger[aria-expanded="true"] { + background: #ffffff; + border-color: #70bad2; + box-shadow: 0 0 0 3px rgba(14, 156, 204, 0.11); +} + +.workspace-color-trigger svg { + justify-self: end; + transition: transform 150ms ease; +} + +.workspace-color-trigger svg.open { + transform: rotate(180deg); +} + +.workspace-color-swatch { + width: 26px; + height: 26px; + border: 2px solid #ffffff; + border-radius: 7px; + box-shadow: 0 0 0 1px rgba(39, 65, 83, 0.24), 0 2px 5px rgba(28, 52, 70, 0.18); +} + +.workspace-color-popover { + position: fixed; + z-index: 100; + width: 286px; + visibility: hidden; + display: grid; + gap: 12px; + padding: 13px; + background: #ffffff; + border: 1px solid #ccd9e2; + border-radius: 12px; + box-shadow: 0 14px 34px rgba(24, 48, 67, 0.2); +} + +.workspace-hex-color-picker.react-colorful { + width: 100%; + height: 176px; +} + +.workspace-hex-color-picker .react-colorful__saturation { + border-bottom: 0; + border-radius: 8px 8px 4px 4px; +} + +.workspace-hex-color-picker .react-colorful__hue { + height: 14px; + margin-top: 10px; + border-radius: 999px; +} + +.workspace-hex-color-picker .react-colorful__pointer { + width: 18px; + height: 18px; + border-width: 3px; + box-shadow: 0 1px 5px rgba(20, 40, 58, 0.3); +} + +.workspace-color-presets { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 8px; +} + +.workspace-color-presets button { + width: 100%; + aspect-ratio: 1; + padding: 0; + border: 2px solid #ffffff; + border-radius: 7px; + cursor: pointer; + box-shadow: 0 0 0 1px rgba(35, 59, 77, 0.2); + transition: transform 120ms ease, box-shadow 120ms ease; +} + +.workspace-color-presets button:hover { + transform: translateY(-1px); +} + +.workspace-color-presets button.selected { + box-shadow: 0 0 0 2px #0e91bd, 0 0 0 5px rgba(14, 145, 189, 0.14); +} + +.workspace-color-popover-footer { + display: grid; + grid-template-columns: minmax(0, 1fr) 38px; + gap: 8px; +} + +.workspace-color-popover-footer label { + display: grid; + grid-template-columns: 35px minmax(0, 1fr); + align-items: center; + min-width: 0; + height: 38px; + overflow: hidden; + color: #718395; + background: #f5f8fa; + border: 1px solid #ccd8e1; + border-radius: 8px; + font-size: 10px; + font-weight: 900; +} + +.workspace-color-popover-footer label > span { + text-align: center; +} + +.workspace-color-popover-footer input { + min-width: 0; + height: 100%; + padding: 0 10px; + color: #294358; + background: #ffffff; + border: 0; + border-left: 1px solid #d7e1e8; + outline: 0; + font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace; + font-size: 12px; + font-weight: 800; + text-transform: uppercase; +} + +.workspace-color-reset { + display: grid; + width: 38px; + height: 38px; + place-items: center; + color: #466177; + background: #f5f8fa; + border: 1px solid #ccd8e1; + border-radius: 8px; + cursor: pointer; +} + +.workspace-color-reset:hover { + color: #087fa6; + background: #ebf7fb; + border-color: #91c8d9; } .workspace-range { @@ -5045,6 +5582,62 @@ button { font-weight: 700; } +.workspace-history-setting { + display: grid; + gap: 12px; + max-width: 560px; +} + +.workspace-history-range-control { + padding: 4px 8px 0; +} + +.workspace-history-range-control input { + width: 100%; + accent-color: #0fa7cf; +} + +.workspace-history-labels { + display: grid; + grid-template-columns: repeat(5, 1fr); + color: #718697; + font-size: 11px; + font-weight: 750; + text-align: center; +} + +.workspace-history-labels .active { + color: #087f9f; +} + +.workspace-history-custom { + display: grid; + grid-template-columns: 145px minmax(120px, 180px); + gap: 12px; + align-items: center; + color: #29475e; + font-size: 13px; + font-weight: 750; +} + +.workspace-history-custom input { + min-width: 0; + padding: 8px 10px; + color: #203b50; + background: #fff; + border: 1px solid #b8c8d2; + border-radius: 6px; + font: inherit; +} + +.workspace-history-note { + margin: 2px 0 0; + color: #718697; + font-size: 12px; + font-weight: 650; + line-height: 1.45; +} + .workspace-select select { width: 100%; height: 26px; @@ -5678,3 +6271,677 @@ button { height: 24px; } } + +html[data-theme="dark"] { + --background: #101820; + --foreground: #d8e6f1; + --topbar: #16212b; + --subbar: #1b2732; + --panel: #17232d; + --tile: #1b2833; + --tile-hover: #223341; + --border: #304250; + --border-strong: #405665; + --muted: #52697a; + --muted-strong: #7890a1; + --nav-text: #d1e0eb; + --shadow: 0 3px 12px rgba(0, 0, 0, 0.32); +} + +html[data-theme="dark"] body, +html[data-theme="dark"] .dashboard-shell, +html[data-theme="dark"] .sketchforge-editor, +html[data-theme="dark"] .editor-body, +html[data-theme="dark"] .workplane-stage { + color: var(--foreground); + background: var(--background); +} + +html[data-theme="dark"] .dashboard-topbar { + color: #ffffff; + background: #0e69f1; + border-color: transparent; + box-shadow: none; +} + +html[data-theme="dark"] .dashboard-sidebar, +html[data-theme="dark"] .dashboard-action-tile, +html[data-theme="dark"] .project-card, +html[data-theme="dark"] .dashboard-select, +html[data-theme="dark"] .dashboard-segmented, +html[data-theme="dark"] .shared-projects-refresh, +html[data-theme="dark"] .project-empty, +html[data-theme="dark"] .project-card-menu, +html[data-theme="dark"] .dashboard-confirm-dialog, +html[data-theme="dark"] .dashboard-settings-panel { + color: #d4e3ee; + background: #17232d; + border-color: #304351; +} + +html[data-theme="dark"] .dashboard-brand, +html[data-theme="dark"] .dashboard-section-header h1, +html[data-theme="dark"] .dashboard-coming-soon, +html[data-theme="dark"] .project-card-title, +html[data-theme="dark"] .project-empty strong, +html[data-theme="dark"] .dashboard-confirm-dialog header strong, +html[data-theme="dark"] .dashboard-confirm-dialog p span, +html[data-theme="dark"] .dashboard-version-row strong { + color: #e1edf5; +} + +html[data-theme="dark"] .dashboard-section-header span, +html[data-theme="dark"] .project-card-meta, +html[data-theme="dark"] .dashboard-import-notice, +html[data-theme="dark"] .dashboard-setting-row, +html[data-theme="dark"] .dashboard-version-row, +html[data-theme="dark"] .dashboard-confirm-dialog p { + color: #9eb1c0; +} + +html[data-theme="dark"] .dashboard-setting-row input:disabled { + color: #a9bbc9; + background: #1e2c37; + border-color: #344856; +} + +html[data-theme="dark"] .dashboard-setting-row input, +html[data-theme="dark"] .dashboard-setting-row select, +html[data-theme="dark"] .dashboard-rename-dialog input, +html[data-theme="dark"] .dashboard-confirm-cancel, +html[data-theme="dark"] .dashboard-confirm-dialog header button { + color: #d8e6f1; + background: #111b23; + border-color: #3a4e5d; +} + +html[data-theme="dark"] .dashboard-topbar .dashboard-brand { + color: #ffffff; +} + +html[data-theme="dark"] .dashboard-topbar .dashboard-search { + color: #5f7387; + background: #ffffff; + border-color: rgba(255, 255, 255, 0.78); +} + +html[data-theme="dark"] .dashboard-topbar .dashboard-search input { + color: #243d56; + background: transparent; + border: 0; +} + +html[data-theme="dark"] .dashboard-nav-item, +html[data-theme="dark"] .dashboard-settings-button, +html[data-theme="dark"] .dashboard-select, +html[data-theme="dark"] .dashboard-segmented button, +html[data-theme="dark"] .project-menu-trigger { + color: #afc1ce; +} + +html[data-theme="dark"] .dashboard-nav-item:hover, +html[data-theme="dark"] .dashboard-nav-item.active, +html[data-theme="dark"] .project-card-menu button:hover, +html[data-theme="dark"] .project-card-menu button:focus-visible { + color: #8bbaf7; + background: rgba(14, 105, 241, 0.2); +} + +html[data-theme="dark"] .project-menu-trigger { + background: rgba(20, 31, 40, 0.95); + border-color: #3b4e5b; +} + +html[data-theme="dark"] .dashboard-action-tile.create { + color: #e4edff; + background: rgba(14, 105, 241, 0.14); + border-color: #3f79cc; +} + +html[data-theme="dark"] .dashboard-action-tile:not(.create) .dashboard-action-icon, +html[data-theme="dark"] .dashboard-settings-panel header button { + color: #bcd0dc; + background: #22323e; +} + +html[data-theme="dark"] .project-preview { + background: #20313c; +} + +html[data-theme="dark"] .secondary-toolbar, +html[data-theme="dark"] .toolbar-mode-content, +html[data-theme="dark"] .sketch-toolbar-ribbon { + color: #d2e0ea; + background: #1a2630; + border-color: #30424f; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035), 0 1px 3px rgba(0, 0, 0, 0.25); +} + +html[data-theme="dark"] .editor-nav-group, +html[data-theme="dark"] .toolbar-section, +html[data-theme="dark"] .toolbar-mode-content, +html[data-theme="dark"] .toolbar-workspace-tabs { + border-color: #334652; +} + +html[data-theme="dark"] .nav-icon, +html[data-theme="dark"] .menu-button, +html[data-theme="dark"] .mode-tab, +html[data-theme="dark"] .toolbar-icon, +html[data-theme="dark"] .shape-menu-trigger, +html[data-theme="dark"] .toolbar-workspace-tabs button, +html[data-theme="dark"] .toolbar-section-label { + color: #b7c9d6; +} + +html[data-theme="dark"] .nav-icon:hover, +html[data-theme="dark"] .mode-tab:hover, +html[data-theme="dark"] .toolbar-icon:not(.disabled):hover, +html[data-theme="dark"] .shape-menu-trigger:hover, +html[data-theme="dark"] .shape-menu-trigger.active, +html[data-theme="dark"] .toolbar-workspace-tabs button:hover { + color: #e5f4fc; + background: #273946; +} + +html[data-theme="dark"] .shape-menu-dropdown, +html[data-theme="dark"] .top-action-panel, +html[data-theme="dark"] .edge-modifier-panel, +html[data-theme="dark"] .camera-controls, +html[data-theme="dark"] .ruler-tool-popover, +html[data-theme="dark"] .editor-toast, +html[data-theme="dark"] .snap-menu { + color: #d4e3ed; + background: rgba(20, 31, 40, 0.97); + border-color: #3a4d5b; + box-shadow: 0 14px 38px rgba(0, 0, 0, 0.34); +} + +html[data-theme="dark"] .shape-menu-item, +html[data-theme="dark"] .top-action-body button, +html[data-theme="dark"] .top-action-body .open-skf-project-button, +html[data-theme="dark"] .top-action-body .import-drop-zone, +html[data-theme="dark"] .edge-modifier-target, +html[data-theme="dark"] .edge-modifier-quick-actions button, +html[data-theme="dark"] .edge-modifier-footer .secondary, +html[data-theme="dark"] .edge-modifier-field select { + color: #c7d8e4; + background: #1b2a35; + border-color: #3a4f5e; +} + +html[data-theme="dark"] .shape-menu-item:hover, +html[data-theme="dark"] .top-action-body button:hover, +html[data-theme="dark"] .top-action-body .import-drop-zone:hover, +html[data-theme="dark"] .edge-modifier-header button:hover, +html[data-theme="dark"] .snap-menu button:hover, +html[data-theme="dark"] .snap-menu .selected { + background: #253946; +} + +html[data-theme="dark"] .camera-controls button, +html[data-theme="dark"] .snap-menu button, +html[data-theme="dark"] .snap-row { + color: #c0d1dc; +} + +html[data-theme="dark"] .camera-controls button:hover { + color: #ecf8ff; + background: rgba(46, 70, 84, 0.9); + border-color: #4c6979; +} + +html[data-theme="dark"] .shape-inspector { + color: #d3e1ea; + background: rgba(20, 30, 39, 0.97); + border-color: #334753; + box-shadow: -3px 0 14px rgba(0, 0, 0, 0.28); +} + +html[data-theme="dark"] .shape-inspector-header, +html[data-theme="dark"] .shape-state-card, +html[data-theme="dark"] .color-card, +html[data-theme="dark"] .property-card, +html[data-theme="dark"] .shape-floating-controls, +html[data-theme="dark"] .shape-mini-tools { + color: #d2e1eb; + background: rgba(25, 38, 48, 0.98); + border-color: #344956; +} + +html[data-theme="dark"] .property-card-header, +html[data-theme="dark"] .color-card-header { + color: #d8e6ef; +} + +html[data-theme="dark"] .gear-type-property, +html[data-theme="dark"] .range-property, +html[data-theme="dark"] .range-property-name, +html[data-theme="dark"] .text-property, +html[data-theme="dark"] .select-property, +html[data-theme="dark"] .range-value-unit, +html[data-theme="dark"] .color-value { + color: #afc3d0; +} + +html[data-theme="dark"] .gear-type-options button { + color: #b8cad5; + background: #0f1921; + border-color: #3a4e5c; +} + +html[data-theme="dark"] .gear-type-options button:hover:not(:disabled) { + color: #e0f2fa; + background: #1d303b; + border-color: #4f7181; +} + +html[data-theme="dark"] .gear-type-options button.selected { + color: #70d8f3; + background: #132832; + border-color: #31a8cc; + box-shadow: 0 0 0 2px rgba(49, 168, 204, 0.14); +} + +html[data-theme="dark"] .transform-guides line { + stroke: rgba(207, 225, 234, 0.86); +} + +html[data-theme="dark"] .transform-guides #dimension-arrow path { + fill: rgba(222, 237, 244, 0.94); +} + +html[data-theme="dark"] .inspector-snap-dock { + background: linear-gradient(180deg, rgba(20, 30, 39, 0), rgba(20, 30, 39, 0.98) 18px, rgba(20, 30, 39, 0.98)); + border-color: #334753; +} + +html[data-theme="dark"] .property-card-header:hover, +html[data-theme="dark"] .shape-control-cluster button:hover, +html[data-theme="dark"] .inspector-header-icon:hover, +html[data-theme="dark"] .shape-state-card button:not(:disabled):hover { + background: #263945; +} + +html[data-theme="dark"] .range-value-control, +html[data-theme="dark"] .range-value-control input, +html[data-theme="dark"] .snap-select, +html[data-theme="dark"] .shape-control-cluster button { + color: #d3e2ec; + background: #111b23; + border-color: #3a4e5c; +} + +html[data-theme="dark"] .workspace-modal-card { + color: #d6e5ef; + background: #15212a; + border-color: #3a4d5a; + box-shadow: 0 18px 52px rgba(0, 0, 0, 0.5); +} + +html[data-theme="dark"] .workspace-modal-content, +html[data-theme="dark"] .workspace-modal-body, +html[data-theme="dark"] .workspace-modal-footer { + background: #15212a; +} + +html[data-theme="dark"] .workspace-modal-body, +html[data-theme="dark"] .export-dialog-body { + scrollbar-color: #526b79 #15212a; +} + +html[data-theme="dark"] .workspace-modal-body::-webkit-scrollbar, +html[data-theme="dark"] .export-dialog-body::-webkit-scrollbar { + width: 10px; +} + +html[data-theme="dark"] .workspace-modal-body::-webkit-scrollbar-track, +html[data-theme="dark"] .export-dialog-body::-webkit-scrollbar-track { + background: #15212a; +} + +html[data-theme="dark"] .workspace-modal-body::-webkit-scrollbar-thumb, +html[data-theme="dark"] .export-dialog-body::-webkit-scrollbar-thumb { + background: #526b79; + border: 2px solid #15212a; + border-radius: 999px; +} + +html[data-theme="dark"] .workspace-modal-backdrop { + background: rgba(3, 8, 12, 0.48); +} + +html[data-theme="dark"] .workspace-modal-header, +html[data-theme="dark"] .workspace-section-heading, +html[data-theme="dark"] .workspace-toggle, +html[data-theme="dark"] .workspace-range, +html[data-theme="dark"] .workspace-modal-footer { + border-color: #344854; +} + +html[data-theme="dark"] .workspace-settings-nav { + background: #111b23; + border-color: #344854; +} + +html[data-theme="dark"] .workspace-settings-nav button, +html[data-theme="dark"] .workspace-dimensions label, +html[data-theme="dark"] .workspace-range small, +html[data-theme="dark"] .workspace-history-labels, +html[data-theme="dark"] .workspace-history-note, +html[data-theme="dark"] .workspace-global-note, +html[data-theme="dark"] .workspace-section-heading span { + color: #91a7b7; +} + +html[data-theme="dark"] .workspace-settings-nav button:hover { + color: #d9eaf4; + background: #20313c; +} + +html[data-theme="dark"] .workspace-settings-nav button.active { + color: #73d8f4; + background: #1d303b; + border-color: #3d5968; + box-shadow: none; +} + +html[data-theme="dark"] .workspace-section-heading strong, +html[data-theme="dark"] .workspace-history-custom { + color: #dceaf3; +} + +html[data-theme="dark"] .workspace-select select, +html[data-theme="dark"] .workspace-dimensions input, +html[data-theme="dark"] .workspace-history-custom input { + color: #d8e6ef; + background: #0f1921; + border-color: #3c505d; +} + +html[data-theme="dark"] .workspace-color-trigger { + color: #d4e3ed; + background: #0f1921; + border-color: #3c505d; +} + +html[data-theme="dark"] .workspace-color-trigger:hover, +html[data-theme="dark"] .workspace-color-trigger[aria-expanded="true"] { + background: #182a34; + border-color: #4a8296; + box-shadow: 0 0 0 3px rgba(75, 177, 208, 0.11); +} + +html[data-theme="dark"] .workspace-color-swatch, +html[data-theme="dark"] .workspace-color-presets button { + border-color: #dbe8ef; + box-shadow: 0 0 0 1px rgba(7, 13, 17, 0.8); +} + +html[data-theme="dark"] .workspace-color-popover { + background: #111d25; + border-color: #3b505d; + box-shadow: 0 14px 34px rgba(0, 0, 0, 0.44); +} + +html[data-theme="dark"] .workspace-color-popover-footer label, +html[data-theme="dark"] .workspace-color-reset { + color: #9eb3c1; + background: #182832; + border-color: #3b505d; +} + +html[data-theme="dark"] .workspace-color-popover-footer input { + color: #dceaf2; + background: #0d171e; + border-color: #3b505d; +} + +html[data-theme="dark"] .workspace-color-reset:hover { + color: #73d8f4; + background: #203642; + border-color: #4a8296; +} + +html[data-theme="dark"] .make-default-button { + color: #d8e6ef; + background: #1b2a35; + border-color: #3c505d; +} + +html[data-theme="dark"] .workspace-modal-header button:hover, +html[data-theme="dark"] .make-default-button:hover { + background: #253946; +} + +html[data-theme="dark"] .tool-group, +html[data-theme="dark"] .tool-group.right { + border-color: #40515d; +} + +html[data-theme="dark"] .toolbar-section { + background: linear-gradient(90deg, #25343e, #1e2c35 48%, #293943); + border-color: #465964; +} + +html[data-theme="dark"] .toolbar-section-label { + color: #c4d2dc; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.72); +} + +html[data-theme="dark"] .toolbar-workspace-tabs button.active { + color: #dff5ff; + background: #253640; + border-bottom-color: #42c7eb; +} + +html[data-theme="dark"] .sketch-workspace-stage { + background: #101820; +} + +html[data-theme="dark"] .sketch-plate-background { + fill: #18303a; +} + +html[data-theme="dark"] .sketch-plate-border { + stroke: #43b8d7; +} + +html[data-theme="dark"] .sketch-grid .minor { + stroke: rgba(91, 166, 187, 0.34); +} + +html[data-theme="dark"] .sketch-grid .major { + stroke: rgba(91, 185, 210, 0.58); +} + +html[data-theme="dark"] .sketch-grid .axis { + stroke: #6bcae3; +} + +html[data-theme="dark"] .sketch-grid-settings { + background: rgba(20, 32, 41, 0.94); + border-color: #3a4d5a; +} + +html[data-theme="dark"] .sketch-command-button { + color: #c3d3de; +} + +html[data-theme="dark"] .sketch-command-button.primary { + color: #63d2f1; +} + +html[data-theme="dark"] .sketch-command-button.cancel { + color: #f08d98; +} + +html[data-theme="dark"] .sketch-command-button:hover:not(:disabled), +html[data-theme="dark"] .sketch-create-menu-trigger.active { + color: #ecf9ff; + background: #29404d; + border-color: #466574; +} + +html[data-theme="dark"] .sketch-command-button.disabled, +html[data-theme="dark"] .sketch-command-button:disabled { + color: #9aafbd; + opacity: 0.54; +} + +html[data-theme="dark"] .sketch-create-dropdown { + background: rgba(20, 32, 41, 0.99); + border-color: #3a4d5a; + box-shadow: 0 12px 28px rgba(0, 0, 0, 0.38); +} + +html[data-theme="dark"] .sketch-create-dropdown button { + color: #d6e5ee; +} + +html[data-theme="dark"] .sketch-create-dropdown button:hover, +html[data-theme="dark"] .sketch-create-dropdown button:focus-visible { + background: #29404d; +} + +html[data-theme="dark"] .sketch-create-dropdown span { + color: #9db1bf; +} + +html[data-theme="dark"] .toolbar-icon:not(.disabled) .toolbar-command-icon, +html[data-theme="dark"] .toolbar-icon:not(.disabled) .toolbar-user-art-icon, +html[data-theme="dark"] .toolbar-icon:not(.disabled) .toolbar-sprite-icon, +html[data-theme="dark"] .toolbar-icon:not(.disabled) .vector-toolbar-sprite-icon, +html[data-theme="dark"] .shape-menu-trigger .vector-toolbar-sprite-icon, +html[data-theme="dark"] .action-buttons button .vector-toolbar-sprite-icon { + filter: grayscale(0.72) brightness(1.65) contrast(0.92) drop-shadow(0 1px 1px rgba(0, 0, 0, 0.55)); + opacity: 0.96; +} + +html[data-theme="dark"] .toolbar-icon.disabled .toolbar-command-icon, +html[data-theme="dark"] .toolbar-icon.disabled .toolbar-sprite-icon, +html[data-theme="dark"] .toolbar-icon.disabled .vector-toolbar-sprite-icon { + filter: grayscale(1) brightness(1.4); + opacity: 0.24; +} + +html[data-theme="dark"] .toolbar-icon:not(.disabled):hover .toolbar-command-icon, +html[data-theme="dark"] .toolbar-icon:not(.disabled):hover .toolbar-sprite-icon, +html[data-theme="dark"] .toolbar-icon:not(.disabled):hover .vector-toolbar-sprite-icon, +html[data-theme="dark"] .shape-menu-trigger:hover .vector-toolbar-sprite-icon { + filter: grayscale(0.35) brightness(1.85) contrast(1) drop-shadow(0 0 5px rgba(62, 199, 235, 0.32)); +} + +html[data-theme="dark"] .action-buttons button { + color: #c9d9e4; + background: #1d2b34; + border-color: #435661; + box-shadow: 0 5px 16px rgba(0, 0, 0, 0.3); +} + +html[data-theme="dark"] .shape-menu-title, +html[data-theme="dark"] .export-action-panel header, +html[data-theme="dark"] .import-action-panel header { + color: #d8e8f1; + background: linear-gradient(180deg, #22323c, #1a2831); + border-color: #3a4d59; +} + +html[data-theme="dark"] .import-action-panel .top-action-body { + background: #142028; +} + +html[data-theme="dark"] .export-dialog-body { + background: #142028; +} + +html[data-theme="dark"] .export-setting-section, +html[data-theme="dark"] .export-dialog-footer { + background: #182630; + border-color: #344854; +} + +html[data-theme="dark"] .export-file-section label, +html[data-theme="dark"] .export-section-heading strong, +html[data-theme="dark"] .export-format-summary strong { + color: #d8e8f1; +} + +html[data-theme="dark"] .export-file-input-wrap { + background: #0f1921; + border-color: #3c505d; +} + +html[data-theme="dark"] .export-file-input-wrap:focus-within { + background: #111d25; + border-color: #24b8dc; +} + +html[data-theme="dark"] .export-file-input { + color: #d8e6ef; +} + +html[data-theme="dark"] .export-file-input-wrap > span, +html[data-theme="dark"] .export-section-heading > div > span, +html[data-theme="dark"] .export-format-summary span, +html[data-theme="dark"] .export-format-summary p { + color: #91a7b7; +} + +html[data-theme="dark"] .export-scope-badge { + color: #74d8f2; + background: #15323d; + border-color: #28566a; +} + +html[data-theme="dark"] .export-format-slider, +html[data-theme="dark"] .export-format-summary { + background: #111d25; + border-color: #344854; +} + +html[data-theme="dark"] .export-format-slider::before { + background: #263b47; + border-color: #438198; + box-shadow: 0 2px 7px rgba(0, 0, 0, 0.28); +} + +html[data-theme="dark"] .export-format-slider button { + color: #91a7b7; +} + +html[data-theme="dark"] .export-format-slider button:hover { + color: #d8e8f1; +} + +html[data-theme="dark"] .export-format-slider button[aria-checked="true"] { + color: #72d9f4; +} + +html[data-theme="dark"] .cube-face { + color: #b8cbd7; + background: rgba(31, 46, 56, 0.94); + border-color: #536873; + box-shadow: inset 0 0 0 1px rgba(173, 207, 221, 0.08); +} + +html[data-theme="dark"] .cube-top { + color: #d7e6ee; + background: rgba(42, 60, 70, 0.96); +} + +html[data-theme="dark"] .cube-bottom { + color: #8299a8; + background: rgba(21, 33, 42, 0.94); +} + +html[data-theme="dark"] .cube-face:hover, +html[data-theme="dark"] .cube-face:focus-visible { + color: #edfbff; + border-color: #68c6df; + box-shadow: inset 0 0 0 1px rgba(109, 204, 228, 0.2), 0 0 0 2px rgba(80, 190, 220, 0.16); +} + +html[data-theme="dark"] .grid-settings { + color: #a9bdca; +} diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 061fcf1..b79278c 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -3,10 +3,12 @@ import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; +import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme"; import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; import { createLocalId } from "@/lib/localIds"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; -import { importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; +import { hydrateProjectShapeState, type ImportedMeshResource } from "@/lib/projectShapePersistence"; +import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; import { importExtensionSupported } from "@/lib/stlImport"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; @@ -55,20 +57,50 @@ type ProjectShapeCacheEntry = { type ProjectShapeRecord = { id: string; revision: number; - shapes: WorkplaneShape[]; + skfPackage?: Uint8Array; + shapes?: WorkplaneShape[]; history?: EditorHistoryEntry[]; historyIndex?: number; assets?: ProjectAsset[]; + meshResourceIds?: string[]; + assetResourceIds?: string[]; updatedAt: number; }; +type ProjectShapeSaveContext = { + projectName: string; + createdAt: number; + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + placementElevation: number; +}; + +type ProjectShapeResourceRecord = + | { + id: string; + projectId: string; + resourceId: string; + kind: "mesh"; + mesh: ImportedMeshResource; + } + | { + id: string; + projectId: string; + resourceId: string; + kind: "asset"; + asset: ProjectAsset; + }; + const PROJECTS_STORAGE_KEY = "sketchForge.projects"; const PROJECT_SHAPES_DB_NAME = "sketchForge.projectShapes"; const PROJECT_SHAPES_STORE_NAME = "projectShapes"; +const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources"; const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode"; const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder"; const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"]; const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true"; +const EDITOR_SKELETON_MIN_DURATION_MS = 320; +const knownProjectResourceKeys = new Map>(); function formatUpdated(timestamp: number) { const age = Date.now() - timestamp; @@ -101,6 +133,35 @@ function projectShapeCacheEntry( }; } +function projectShapeCacheEntryFromEditor( + revision: number, + shapes: WorkplaneShape[], + history: EditorHistoryEntry[], + historyIndex: number, + assets: ProjectAsset[], +): ProjectShapeCacheEntry { + if (history.length === 0) { + return projectShapeCacheEntry(revision, shapes, history, historyIndex, assets); + } + return { + revision, + shapes, + history, + historyIndex: Math.min(Math.max(0, historyIndex), history.length - 1), + assets: dedupeProjectAssets(assets), + }; +} + +function projectShapeSaveContext(project: Pick): ProjectShapeSaveContext { + return { + projectName: project.name, + createdAt: project.createdAt, + workspace: normalizeWorkspaceSettings(project.workspace), + snapGrid: normalizeSnapGrid(project.snapGrid), + placementElevation: Number.isFinite(project.placementElevation) ? project.placementElevation ?? 0 : 0, + }; +} + function openProjectShapesDb() { return new Promise((resolve, reject) => { if (typeof window === "undefined" || !window.indexedDB) { @@ -108,34 +169,123 @@ function openProjectShapesDb() { return; } - const request = window.indexedDB.open(PROJECT_SHAPES_DB_NAME, 1); + const request = window.indexedDB.open(PROJECT_SHAPES_DB_NAME, 3); request.onupgradeneeded = () => { const database = request.result; if (!database.objectStoreNames.contains(PROJECT_SHAPES_STORE_NAME)) { database.createObjectStore(PROJECT_SHAPES_STORE_NAME, { keyPath: "id" }); } + if (!database.objectStoreNames.contains(PROJECT_SHAPE_RESOURCES_STORE_NAME)) { + database.createObjectStore(PROJECT_SHAPE_RESOURCES_STORE_NAME, { keyPath: "id" }); + } }; request.onerror = () => reject(request.error ?? new Error("Could not open project shape storage")); request.onsuccess = () => resolve(request.result); }); } +function projectResourceKey(kind: ProjectShapeResourceRecord["kind"], resourceId: string) { + return `${kind}:${resourceId}`; +} + +function projectResourceRecordId(projectId: string, kind: ProjectShapeResourceRecord["kind"], resourceId: string) { + return `${projectId}:${projectResourceKey(kind, resourceId)}`; +} + async function loadProjectShapes(projectId: string) { const database = await openProjectShapesDb(); - return new Promise((resolve, reject) => { + const record = await new Promise((resolve, reject) => { const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readonly"); const request = transaction.objectStore(PROJECT_SHAPES_STORE_NAME).get(projectId); request.onerror = () => reject(request.error ?? new Error("Could not load project shapes")); request.onsuccess = () => resolve((request.result as ProjectShapeRecord | undefined) ?? null); - transaction.oncomplete = () => database.close(); - transaction.onerror = () => { - database.close(); - reject(transaction.error ?? new Error("Could not load project shapes")); - }; + transaction.onerror = () => reject(transaction.error ?? new Error("Could not load project shapes")); }); + if (!record) { + database.close(); + return null; + } + if (record.skfPackage) { + database.close(); + const restored = await importSkfProject(record.skfPackage); + return { + ...record, + shapes: restored.shapes, + history: restored.history, + historyIndex: restored.historyIndex, + assets: restored.assets, + }; + } + + const meshResourceIds = record.meshResourceIds ?? []; + const assetResourceIds = record.assetResourceIds ?? []; + if (meshResourceIds.length === 0 && assetResourceIds.length === 0) { + database.close(); + return { + ...record, + shapes: record.shapes ?? [], + }; + } + + const resourceRecords = await new Promise((resolve, reject) => { + const transaction = database.transaction(PROJECT_SHAPE_RESOURCES_STORE_NAME, "readonly"); + const store = transaction.objectStore(PROJECT_SHAPE_RESOURCES_STORE_NAME); + const records: ProjectShapeResourceRecord[] = []; + const requests = [ + ...meshResourceIds.map((resourceId) => store.get(projectResourceRecordId(projectId, "mesh", resourceId))), + ...assetResourceIds.map((resourceId) => store.get(projectResourceRecordId(projectId, "asset", resourceId))), + ]; + requests.forEach((request) => { + request.onsuccess = () => { + if (request.result) records.push(request.result as ProjectShapeResourceRecord); + }; + request.onerror = () => { + transaction.abort(); + }; + }); + transaction.oncomplete = () => resolve(records); + transaction.onerror = () => reject(transaction.error ?? new Error("Could not load project shape resources")); + transaction.onabort = () => reject(transaction.error ?? new Error("Could not load project shape resources")); + }); + database.close(); + + const meshResources = new Map(); + const assets: ProjectAsset[] = []; + resourceRecords.forEach((resource) => { + if (resource.kind === "mesh") meshResources.set(resource.resourceId, resource.mesh); + else assets.push(resource.asset); + }); + if (meshResources.size !== meshResourceIds.length || assets.length !== assetResourceIds.length) { + throw new Error("Project shape resources are incomplete"); + } + knownProjectResourceKeys.set(projectId, new Set([ + ...meshResourceIds.map((resourceId) => projectResourceKey("mesh", resourceId)), + ...assetResourceIds.map((resourceId) => projectResourceKey("asset", resourceId)), + ])); + const hydrated = hydrateProjectShapeState(record.shapes ?? [], record.history, meshResources); + return { + ...record, + shapes: hydrated.shapes, + history: hydrated.history, + assets, + }; } -async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry) { +async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry, context: ProjectShapeSaveContext) { + const skfPackage = await exportSkfProject({ + projectId, + projectName: context.projectName, + createdAt: context.createdAt, + modifiedAt: entry.revision, + shapes: entry.shapes, + history: entry.history, + historyIndex: entry.historyIndex, + assets: entry.assets, + workspace: context.workspace, + snapGrid: context.snapGrid, + placementElevation: context.placementElevation, + compressionLevel: 1, + }); const database = await openProjectShapesDb(); return new Promise((resolve, reject) => { const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite"); @@ -149,7 +299,12 @@ async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntr if (existing && existing.revision > entry.revision) { return; } - store.put({ id: projectId, ...entry, updatedAt: Date.now() } satisfies ProjectShapeRecord); + store.put({ + id: projectId, + revision: entry.revision, + skfPackage, + updatedAt: Date.now(), + } satisfies ProjectShapeRecord); }; transaction.oncomplete = () => { database.close(); @@ -166,6 +321,23 @@ async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntr }); } +function saveProjectShapesWhenIdle(projectId: string, entry: ProjectShapeCacheEntry, context: ProjectShapeSaveContext) { + return new Promise((resolve, reject) => { + const save = () => { + void saveProjectShapes(projectId, entry, context).then(resolve, reject); + }; + if (typeof window === "undefined") { + save(); + return; + } + if ("requestIdleCallback" in window) { + window.requestIdleCallback(save, { timeout: 1200 }); + return; + } + globalThis.setTimeout(save, 32); + }); +} + async function deleteProjectShapes(projectId: string) { const database = await openProjectShapesDb(); return new Promise((resolve, reject) => { @@ -241,9 +413,9 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb thumbnailUrl: project.thumbnailUrl ?? storedProject.thumbnailUrl, thumbnailVersion: project.thumbnailVersion ?? storedProject.thumbnailVersion, updatedAt: Math.max(project.updatedAt, storedProject.updatedAt), - workspace: project.workspace ?? storedProject.workspace, - snapGrid: project.snapGrid ?? storedProject.snapGrid, - placementElevation: project.placementElevation ?? storedProject.placementElevation, + workspace: storedProject.workspace ?? project.workspace, + snapGrid: storedProject.snapGrid ?? project.snapGrid, + placementElevation: storedProject.placementElevation ?? project.placementElevation, sharedProject: project.sharedProject ?? storedProject.sharedProject, }; } @@ -296,6 +468,7 @@ export default function Home() { const [mounted, setMounted] = useState(false); const [view, setView] = useState("dashboard"); const [editorStarted, setEditorStarted] = useState(false); + const [editorLoading, setEditorLoading] = useState(false); const [activeProjectId, setActiveProjectId] = useState(null); const [projects, setProjects] = useState([]); const [dashboardSection, setDashboardSection] = useState("home"); @@ -303,6 +476,8 @@ export default function Home() { const [viewMode, setViewMode] = useState("grid"); const [sortMode, setSortMode] = useState("recent"); const [settingsOpen, setSettingsOpen] = useState(false); + const [themePreference, setThemePreference] = useState("system"); + const [resolvedTheme, setResolvedTheme] = useState("light"); const [downloadMode, setDownloadMode] = useState("browser"); const [downloadFolder, setDownloadFolder] = useState(""); const [dashboardNotice, setDashboardNotice] = useState(""); @@ -314,6 +489,12 @@ export default function Home() { const dashboardImportInputRef = useRef(null); const nextProjectRevisionRef = useRef(0); const projectShapeSaveQueuesRef = useRef>>({}); + const editorLoadingStartedAtRef = useRef(0); + + const startEditorTransition = useCallback(() => { + editorLoadingStartedAtRef.current = Date.now(); + setEditorLoading(true); + }, []); const refreshSharedProjects = useCallback(async () => { if (STATIC_EXPORT_BUILD) return; @@ -333,19 +514,19 @@ export default function Home() { }, []); useEffect(() => { - document.documentElement.removeAttribute("data-theme"); - document.documentElement.style.colorScheme = "light"; - try { - window.localStorage.removeItem("sketchForge.theme"); - } catch { - // Light mode still applies when browser storage is unavailable. - } + const storedTheme = readStoredAppTheme(window.localStorage); + setThemePreference(storedTheme); + const systemPrefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; + setResolvedTheme(resolveAppTheme(storedTheme, systemPrefersDark)); + applyAppTheme(storedTheme, systemPrefersDark); const { projects: storedProjects, legacyShapes } = readStoredProjects(); setProjects(storedProjects); if (Object.keys(legacyShapes).length > 0) { setProjectShapesById(legacyShapes); Object.entries(legacyShapes).forEach(([projectId, entry]) => { - void saveProjectShapes(projectId, entry).catch(() => { + const project = storedProjects.find((candidate) => candidate.id === projectId); + if (!project) return; + void saveProjectShapes(projectId, entry, projectShapeSaveContext(project)).catch(() => { setDashboardNotice("Could not migrate project shapes to larger storage"); }); }); @@ -359,11 +540,26 @@ export default function Home() { if (requestedProjectId && storedProjects.some((project) => project.id === requestedProjectId)) { setActiveProjectId(requestedProjectId); } + startEditorTransition(); setEditorStarted(true); setView("editor"); } setMounted(true); - }, []); + }, [startEditorTransition]); + + useEffect(() => { + if (!mounted) return; + const media = window.matchMedia("(prefers-color-scheme: dark)"); + const applyCurrentTheme = () => { + setResolvedTheme(resolveAppTheme(themePreference, media.matches)); + applyAppTheme(themePreference, media.matches); + }; + storeAppTheme(window.localStorage, themePreference); + applyCurrentTheme(); + if (themePreference !== "system") return; + media.addEventListener("change", applyCurrentTheme); + return () => media.removeEventListener("change", applyCurrentTheme); + }, [mounted, themePreference]); useEffect(() => { if (!mounted) return; @@ -419,7 +615,7 @@ export default function Home() { const activeProject = projects.find((project) => project.id === activeProjectId); if (!activeProject) return; const cached = projectShapesById[activeProjectId]; - if (cached && cached.revision === activeProject.revision) return; + if (cached && cached.revision >= (activeProject.revision ?? 0)) return; let canceled = false; void loadProjectShapes(activeProjectId) @@ -431,6 +627,11 @@ export default function Home() { ...current, [activeProjectId]: entry, })); + if (record && !record.skfPackage) { + void saveProjectShapesWhenIdle(activeProjectId, entry, projectShapeSaveContext(activeProject)).catch(() => { + // The legacy record remains readable and migration can retry on the next load. + }); + } }) .catch((error) => { if (!canceled) { @@ -446,6 +647,22 @@ export default function Home() { }; }, [activeProjectId, mounted, projectShapesById, projects]); + useEffect(() => { + if (!editorLoading || view !== "editor") return; + if (activeProjectId) { + const activeProject = projects.find((project) => project.id === activeProjectId); + const activeEntry = projectShapesById[activeProjectId]; + if (!activeProject || !activeEntry) return; + } + + const elapsed = Date.now() - editorLoadingStartedAtRef.current; + const remaining = Math.max(0, EDITOR_SKELETON_MIN_DURATION_MS - elapsed); + const timer = window.setTimeout(() => { + window.requestAnimationFrame(() => setEditorLoading(false)); + }, remaining); + return () => window.clearTimeout(timer); + }, [activeProjectId, editorLoading, projectShapesById, projects, view]); + useEffect(() => { if (!mounted) return; window.localStorage.setItem(DOWNLOAD_MODE_STORAGE_KEY, downloadMode); @@ -479,6 +696,7 @@ export default function Home() { } else if (projectId) { setProjects((current) => current.map((project) => (project.id === projectId ? { ...project, updatedAt: Date.now() } : project))); } + startEditorTransition(); setActiveProjectId(projectId); setEditorStarted(true); setView("editor"); @@ -534,10 +752,15 @@ export default function Home() { history: EditorHistoryEntry[]; historyIndex: number; assets: ProjectAsset[]; + projectName: string; + projectCreatedAt: number; + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + placementElevation: number; }) => { const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1); nextProjectRevisionRef.current = revision; - const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets); + const entry = projectShapeCacheEntryFromEditor(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets); setProjectShapesById((current) => { const existing = current[snapshot.projectId]; if (existing && existing.revision > revision) { @@ -550,7 +773,14 @@ export default function Home() { }); const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve(); - const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, entry)); + const saveContext: ProjectShapeSaveContext = { + projectName: snapshot.projectName, + createdAt: snapshot.projectCreatedAt, + workspace: normalizeWorkspaceSettings(snapshot.workspace), + snapGrid: normalizeSnapGrid(snapshot.snapGrid), + placementElevation: Number.isFinite(snapshot.placementElevation) ? snapshot.placementElevation : 0, + }; + const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapesWhenIdle(snapshot.projectId, entry, saveContext)); projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave; void queuedSave @@ -576,7 +806,8 @@ export default function Home() { }, []); const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => { - const version = Date.now(); + const version = Math.max(Date.now(), nextProjectRevisionRef.current + 1); + nextProjectRevisionRef.current = version; const workspace = normalizeWorkspaceSettings(snapshot.workspace); const snapGrid = normalizeSnapGrid(snapshot.snap); const placementElevation = typeof snapshot.placementElevation === "number" && Number.isFinite(snapshot.placementElevation) @@ -599,9 +830,19 @@ export default function Home() { snapGrid, placementElevation, updatedAt: version, + revision: version, }; }); - return changed ? next : current; + if (!changed) return current; + try { + const storageProjects = mergeProjectsForStorage(next); + const serialized = JSON.stringify(storageProjects); + window.localStorage.setItem(PROJECTS_STORAGE_KEY, serialized); + projectsJsonRef.current = serialized; + return next; + } catch { + return next; + } }); }, []); @@ -611,7 +852,11 @@ export default function Home() { ...current, [project.id]: projectShapeCacheEntry(project.revision ?? project.updatedAt, []), })); - void saveProjectShapes(project.id, projectShapeCacheEntry(project.revision ?? project.updatedAt, [])).catch(() => { + void saveProjectShapes( + project.id, + projectShapeCacheEntry(project.revision ?? project.updatedAt, []), + projectShapeSaveContext(project), + ).catch(() => { setDashboardNotice("Could not prepare project shape storage"); }); setProjects((current) => [project, ...current]); @@ -634,7 +879,7 @@ export default function Home() { sharedProject: sharedProject ? { fileName: sharedProject.fileName, revision: sharedProject.revision } : undefined, }; const entry = projectShapeCacheEntry(now, restored.shapes, restored.history, restored.historyIndex, restored.assets); - await saveProjectShapes(project.id, entry); + await saveProjectShapes(project.id, entry, projectShapeSaveContext(project)); setProjectShapesById((current) => ({ ...current, [project.id]: entry })); setProjects((current) => [project, ...current]); setDashboardNotice(sharedProject ? `Opened shared project ${sharedProject.name}; edits autosave locally until you save back to shared` : `Opened ${file.name} as a new editable local project`); @@ -755,7 +1000,7 @@ export default function Home() { const project = newProject(projectName, projects.length, importedShapes.length); const revision = project.revision ?? project.updatedAt; const entry = projectShapeCacheEntry(revision, importedShapes, undefined, undefined, dedupeProjectAssets(importedAssets)); - await saveProjectShapes(project.id, entry); + await saveProjectShapes(project.id, entry, projectShapeSaveContext(project)); setProjectShapesById((current) => ({ ...current, [project.id]: entry, @@ -787,6 +1032,7 @@ export default function Home() { setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project))); } setDashboardSection("home"); + setEditorLoading(false); setView("dashboard"); if (typeof window !== "undefined") { window.history.replaceState(null, "", "/"); @@ -919,13 +1165,86 @@ export default function Home() { projectModifiedAt={activeProject?.updatedAt} projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0} sharedProjectsEnabled={sharedProjectsEnabled} + themePreference={themePreference} + resolvedTheme={resolvedTheme} + onThemePreferenceChange={setThemePreference} /> ) : null} + {view === "editor" && (editorLoading || !canRenderEditor) ? : null} ); } +function EditorLoadingSkeleton() { + const leftToolbarSections = [ + { className: "home", controls: 1 }, + { className: "clipboard", controls: 4 }, + { className: "history", controls: 2 }, + { className: "shapes", controls: 1 }, + ]; + const rightToolbarSections = [ + { className: "visibility", controls: 2 }, + { className: "combine", controls: 3 }, + { className: "modify", controls: 5 }, + { className: "arrange", controls: 2 }, + { className: "manage", controls: 3 }, + ]; + + const renderToolbarSection = ({ className, controls }: { className: string; controls: number }) => ( +
+ +
+ {Array.from({ length: controls }, (_, index) => ( + + ))} +
+
+ ); + + return ( +
+
+
+ + +
+
+
+ {leftToolbarSections.map(renderToolbarSection)} +
+ +
+ {rightToolbarSections.map(renderToolbarSection)} +
+
+
+ +
+
+
+ + + +
+ +
+ {Array.from({ length: 5 }, (_, index) => ( + + ))} +
+ + +
+
+
+ ); +} + function Dashboard({ dashboardSection, dashboardNotice, @@ -1030,10 +1349,10 @@ function Dashboard({ return (
- +
onQueryChange(event.currentTarget.value)} placeholder="Search projects" aria-label="Search projects" /> diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 5ee8c57..b447033 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -15,6 +15,7 @@ import droidSerifBoldFontJson from "three/examples/fonts/droid/droid_serif_bold. import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.json"; import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json"; import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json"; +import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme"; import { manifoldModuleSource } from "@/generated/manifoldModuleSource"; import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64"; import { sphereTessellation } from "@/lib/sphereTessellation"; @@ -72,10 +73,12 @@ import { CAD_MODIFIER_REQUEST_TIMEOUT_MS, cadModifierTimeoutMessage, cadModifierWorkerFailureMessage, + defaultCadModifierTangentChain, + selectableCadModifierEdge, type CadModifierRequestPhase, } from "@/lib/cadModifierRuntime"; import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; -import { appendEditorHistorySnapshot, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory"; +import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory"; import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap"; import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; @@ -87,7 +90,7 @@ import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAs import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport"; import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport"; -import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; +import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import { SKETCHFORGE_MCP_POLL_MS, SKETCHFORGE_MCP_ROUTE, @@ -188,6 +191,7 @@ declare global { __sketchforgeBooleanTest?: BooleanAutomationResult; __sketchforgeBooleanTestImage?: string; sketchforgeCaptureCanvas?: () => string; + sketchforgeCaptureCanvasAsync?: () => Promise; sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise | string; } } @@ -1380,10 +1384,6 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI return [...selected]; } -function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) { - return edge.display && edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle; -} - function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) { const removed = new Set(session.selectedEdgeIds); const elevation = shape.elevation ?? 0; @@ -5207,6 +5207,9 @@ export function SketchForgeEditor({ projectModifiedAt = Date.now(), projectRevision = 0, sharedProjectsEnabled = false, + themePreference = "system", + resolvedTheme = "light", + onThemePreferenceChange, }: { initialAssets?: ProjectAsset[]; initialShapes?: WorkplaneShape[]; @@ -5224,6 +5227,11 @@ export function SketchForgeEditor({ history: EditorHistoryEntry[]; historyIndex: number; assets: ProjectAsset[]; + projectName: string; + projectCreatedAt: number; + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + placementElevation: number; }) => void; onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void; onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => void; @@ -5233,6 +5241,9 @@ export function SketchForgeEditor({ projectModifiedAt?: number; projectRevision?: number; sharedProjectsEnabled?: boolean; + themePreference?: AppThemePreference; + resolvedTheme?: ResolvedAppTheme; + onThemePreferenceChange?: (preference: AppThemePreference) => void; } = {}) { const initialSceneRef = useRef(null); if (initialSceneRef.current === null) { @@ -5240,7 +5251,12 @@ export function SketchForgeEditor({ } const initialHistoryStateRef = useRef(null); if (initialHistoryStateRef.current === null) { - initialHistoryStateRef.current = hydrateEditorHistoryState(initialSceneRef.current, initialHistory, initialHistoryIndex); + initialHistoryStateRef.current = hydrateEditorHistoryState( + initialSceneRef.current, + initialHistory, + initialHistoryIndex, + normalizeWorkspaceSettings(initialWorkspace).historyLimit, + ); } const [shapes, setShapes] = useState(() => initialSceneRef.current as WorkplaneShape[]); const [projectAssets, setProjectAssets] = useState(() => dedupeProjectAssets(initialAssets)); @@ -5280,10 +5296,13 @@ export function SketchForgeEditor({ const projectAssetsRef = useRef(projectAssets); const selectedIdsRef = useRef(selectedIds); const workspaceSettingsRef = useRef(workspaceSettings); + const snapGridRef = useRef(snapGrid); + const placementElevationRef = useRef(placementElevation); const noticeRef = useRef(notice); - const projectInfoRef = useRef({ projectId: projectId ?? null, projectName }); + const projectInfoRef = useRef({ projectId: projectId ?? null, projectName, projectCreatedAt }); const historyIndexRef = useRef(historyIndex); const historyRef = useRef(history); + const historyLimitRef = useRef(workspaceSettings.historyLimit); const interactionHistoryStartRef = useRef(""); const interactionHistoryChangedRef = useRef(false); const interactionHistoryTimerRef = useRef(null); @@ -5571,13 +5590,21 @@ export function SketchForgeEditor({ workspaceSettingsRef.current = workspaceSettings; }, [workspaceSettings]); + useEffect(() => { + snapGridRef.current = snapGrid; + }, [snapGrid]); + + useEffect(() => { + placementElevationRef.current = placementElevation; + }, [placementElevation]); + useEffect(() => { noticeRef.current = notice; }, [notice]); useEffect(() => { - projectInfoRef.current = { projectId: projectId ?? null, projectName }; - }, [projectId, projectName]); + projectInfoRef.current = { projectId: projectId ?? null, projectName, projectCreatedAt }; + }, [projectCreatedAt, projectId, projectName]); useEffect(() => { historyIndexRef.current = historyIndex; @@ -5620,11 +5647,19 @@ export function SketchForgeEditor({ }, [sketchActive, sketchOperation, sketchProfile, sketchRevolveSettings]); useEffect(() => { - setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace)); + const nextWorkspace = normalizeWorkspaceSettings(initialWorkspace); + workspaceSettingsRef.current = nextWorkspace; + setWorkspaceSettings((current) => ( + workplaneSettingsFingerprint(current, snapGridRef.current) === workplaneSettingsFingerprint(nextWorkspace, snapGridRef.current) + ? current + : nextWorkspace + )); }, [initialWorkspace]); useEffect(() => { - setSnapGrid(normalizeSnapGrid(initialSnap)); + const nextSnap = normalizeSnapGrid(initialSnap); + snapGridRef.current = nextSnap; + setSnapGrid((current) => (current === nextSnap ? current : nextSnap)); }, [initialSnap]); const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]); @@ -5702,21 +5737,43 @@ export function SketchForgeEditor({ const runId = projectSnapshotRunRef.current + 1; projectSnapshotRunRef.current = runId; - const capture = () => { + const capture = async () => { if (projectSnapshotRunRef.current !== runId) { - return; + return true; + } + const image = window.sketchforgeCaptureCanvasAsync + ? await window.sketchforgeCaptureCanvasAsync() + : window.sketchforgeCaptureCanvas?.() ?? ""; + if (projectSnapshotRunRef.current !== runId) { + return true; } - const image = window.sketchforgeCaptureCanvas?.(); if (image && image.length > 100) { onProjectSnapshot({ image, projectId, shapes: shapes.length }); + return true; } + return false; }; - const firstTimer = window.setTimeout(capture, 850); - const secondTimer = window.setTimeout(capture, 1500); + let idleId: number | null = null; + let retryTimer: number | null = null; + const runCapture = () => { + void capture().then((captured) => { + if (!captured) { + retryTimer = window.setTimeout(() => void capture(), 650); + } + }); + }; + const captureTimer = window.setTimeout(() => { + if ("requestIdleCallback" in window) { + idleId = window.requestIdleCallback(runCapture, { timeout: 1200 }); + } else { + runCapture(); + } + }, 850); return () => { - window.clearTimeout(firstTimer); - window.clearTimeout(secondTimer); + window.clearTimeout(captureTimer); + if (retryTimer !== null) window.clearTimeout(retryTimer); + if (idleId !== null && "cancelIdleCallback" in window) window.cancelIdleCallback(idleId); }; }, [onProjectSnapshot, projectId, projectInteractionActive, shapes]); @@ -5737,7 +5794,7 @@ export function SketchForgeEditor({ }, [alignAnchorId, selectedIds, selectedShapes.length]); const syncProjectShapes = useCallback( - (nextShapes: WorkplaneShape[]) => { + (nextShapes: WorkplaneShape[], force = false) => { if (!projectId || !onProjectShapesChange) { return; } @@ -5751,7 +5808,7 @@ export function SketchForgeEditor({ } const canonicalNext = nextShapes.map(canonicalizeShape); const serialized = projectShapesFingerprint(canonicalNext); - if (lastProjectShapesSyncRef.current === serialized) { + if (!force && lastProjectShapesSyncRef.current === serialized) { return; } if (projectSyncTimerRef.current !== null) { @@ -5766,6 +5823,11 @@ export function SketchForgeEditor({ history: historyRef.current, historyIndex: historyIndexRef.current, assets: projectAssetsRef.current, + projectName: projectInfoRef.current.projectName, + projectCreatedAt: projectInfoRef.current.projectCreatedAt, + workspace: workspaceSettingsRef.current, + snapGrid: snapGridRef.current, + placementElevation: placementElevationRef.current, }); projectSyncTimerRef.current = null; }, 120); @@ -5773,9 +5835,30 @@ export function SketchForgeEditor({ [onProjectShapesChange, projectId], ); - const appendHistorySnapshot = useCallback((nextShapes: WorkplaneShape[], nextSelection: string[]) => { - const entry = editorHistoryEntry(nextShapes, nextSelection); - const result = appendEditorHistorySnapshot(historyRef.current, historyIndexRef.current, entry); + useEffect(() => { + const limitChanged = historyLimitRef.current !== workspaceSettings.historyLimit; + historyLimitRef.current = workspaceSettings.historyLimit; + const bounded = boundedEditorHistoryState( + historyRef.current, + historyIndexRef.current, + workspaceSettings.historyLimit, + ); + if (bounded.entries !== historyRef.current || bounded.index !== historyIndexRef.current) { + historyRef.current = bounded.entries; + historyIndexRef.current = bounded.index; + setHistory(bounded.entries); + setHistoryIndex(bounded.index); + } + if (limitChanged) syncProjectShapes(shapesRef.current, true); + }, [syncProjectShapes, workspaceSettings.historyLimit]); + + const appendHistoryEntry = useCallback((entry: EditorHistoryEntry) => { + const result = appendEditorHistorySnapshot( + historyRef.current, + historyIndexRef.current, + entry, + workspaceSettingsRef.current.historyLimit, + ); if (result.entries !== historyRef.current) { historyRef.current = result.entries; setHistory(result.entries); @@ -5785,6 +5868,12 @@ export function SketchForgeEditor({ return result.changed; }, []); + const appendHistorySnapshot = useCallback( + (nextShapes: WorkplaneShape[], nextSelection: string[]) => + appendHistoryEntry(editorHistoryEntry(nextShapes, nextSelection)), + [appendHistoryEntry], + ); + const finalizeInteractionHistory = useCallback(() => { const startFingerprint = interactionHistoryStartRef.current; const hadChanges = interactionHistoryChangedRef.current; @@ -5794,22 +5883,20 @@ export function SketchForgeEditor({ return; } - const canonicalNext = shapesRef.current.map(canonicalizeShape); - const nextFingerprint = projectShapesFingerprint(canonicalNext); - if (!startFingerprint || startFingerprint === nextFingerprint) { + const entry = editorHistoryEntry(shapesRef.current, selectedIdsRef.current); + if (!startFingerprint || startFingerprint === entry.fingerprint) { return; } - appendHistorySnapshot(canonicalNext, selectedIdsRef.current); - }, [appendHistorySnapshot]); + appendHistoryEntry(entry); + }, [appendHistoryEntry]); useEffect(() => { if (projectInteractionActive || !pendingProjectShapesRef.current) { return; } - const pendingShapes = pendingProjectShapesRef.current; pendingProjectShapesRef.current = null; - const timer = window.setTimeout(() => syncProjectShapes(pendingShapes), 180); + const timer = window.setTimeout(() => syncProjectShapes(shapesRef.current), 180); return () => window.clearTimeout(timer); }, [projectInteractionActive, syncProjectShapes]); @@ -5845,12 +5932,19 @@ export function SketchForgeEditor({ const updateProjectWorkspaceSettings = useCallback( (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => { - setWorkspaceSettings(settings.workspace); + const nextWorkspace = normalizeWorkspaceSettings(settings.workspace); + workspaceSettingsRef.current = nextWorkspace; + snapGridRef.current = settings.snap; + setWorkspaceSettings((current) => ( + workplaneSettingsFingerprint(current, settings.snap) === workplaneSettingsFingerprint(nextWorkspace, settings.snap) + ? current + : nextWorkspace + )); setSnapGrid(settings.snap); if (!projectId || !onProjectWorkspaceChange) { return; } - onProjectWorkspaceChange({ projectId, ...settings, placementElevation }); + onProjectWorkspaceChange({ projectId, workspace: nextWorkspace, snap: settings.snap, placementElevation }); }, [onProjectWorkspaceChange, placementElevation, projectId], ); @@ -6377,7 +6471,12 @@ export function SketchForgeEditor({ if (!projectChanged && incomingSerialized === projectShapesFingerprint(shapes)) { return; } - const hydratedHistory = hydrateEditorHistoryState(incoming, initialHistory, initialHistoryIndex); + const hydratedHistory = hydrateEditorHistoryState( + incoming, + initialHistory, + initialHistoryIndex, + normalizeWorkspaceSettings(initialWorkspace).historyLimit, + ); projectHydratingRef.current = true; shapesRef.current = incoming; selectedIdsRef.current = []; @@ -6387,8 +6486,8 @@ export function SketchForgeEditor({ setSelectedIds([]); setHistory(hydratedHistory.entries); setHistoryIndex(hydratedHistory.index); - setNotice(incoming.length ? "Project synced" : "Ready"); - }, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectInteractionActive, projectRevision]); + setNotice("Ready"); + }, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectRevision]); useEffect(() => { if (!projectId || !onProjectShapesChange) { @@ -6850,7 +6949,7 @@ export function SketchForgeEditor({ sharpAngle: 25, chamferAngle: 45, quality: "standard", - tangentChain: true, + tangentChain: defaultCadModifierTangentChain(appliedEdgeTreatmentCount), preserveEdgeSize: selectedShape.edgeResizeMode === "preserve", busy: true, prepared: false, @@ -8533,8 +8632,8 @@ export function SketchForgeEditor({ selected={sketchSelection} measurement={sketchMeasurement} pendingMeasurementStart={sketchMeasureStart} - initialSnap={initialSnap} - initialWorkspace={initialWorkspace} + initialSnap={snapGrid} + initialWorkspace={workspaceSettings} onPlanePoint={addSketchPlanePoint} onPointPress={pressSketchPoint} onSelectSegment={(id) => { @@ -8574,8 +8673,8 @@ export function SketchForgeEditor({ mirrorReferenceShapes={shapes} placementElevation={placementElevation} workplaneMode={workplaneMode} - initialSnap={initialSnap} - initialWorkspace={initialWorkspace} + initialSnap={snapGrid} + initialWorkspace={workspaceSettings} workspaceSettingsKey={projectId ?? "local-workplane"} onAddShape={addShape} onAlignAnchorChange={chooseAlignAnchor} @@ -8599,6 +8698,9 @@ export function SketchForgeEditor({ modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []} selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []} onModifierEdgeToggle={toggleModifierEdge} + themePreference={themePreference} + resolvedTheme={resolvedTheme} + onThemePreferenceChange={onThemePreferenceChange} /> )}
diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 98d76fb..e09997a 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -1,9 +1,10 @@ "use client"; import { ChevronLeft, ChevronRight, Home, Minus, MousePointer2, Plus, Ruler, X } from "lucide-react"; -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction, type WheelEvent as ReactWheelEvent } from "react"; import * as THREE from "three"; import { Brush, Evaluator, HOLLOW_INTERSECTION } from "three-bvh-csg"; +import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree } from "three-mesh-bvh"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js"; import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js"; @@ -17,10 +18,11 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays"; import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector"; import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; +import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme"; import { createGearGeometry } from "@/lib/gearGeometry"; import { parseMeasurementInput } from "@/lib/measurementUnits"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings"; -import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid"; +import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid"; import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; import { sphereTessellation } from "@/lib/sphereTessellation"; import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol"; @@ -56,6 +58,13 @@ const MIN_ELEVATION = -180; const MAX_ELEVATION = 220; const CAMERA_MIN_TARGET_Y = -70; const CAMERA_MAX_TARGET_Y = 120; +const ROTATION_PROTRACTOR_OUTER_RADIUS = 94; +const RENDER_LAYER_WORKPLANE = 0; +const RENDER_LAYER_SHAPES = 1; +const RENDER_LAYER_HELPERS = 2; +const RENDER_LAYER_MODIFIERS = 3; +const RENDER_LAYER_PREVIEWS = 4; +const BVH_PICKING_TRIANGLE_THRESHOLD = 512; const SHAPE_KINDS = new Set([ "box", "cylinder", @@ -92,6 +101,14 @@ const importedGeometryCache = new WeakMap< { geometry: THREE.BufferGeometry; edges: Map } >(); const preservedImportedGeometryCache = new WeakMap(); +const MAX_SHARED_SHAPE_GEOMETRIES = 192; +const MAX_SHARED_SHAPE_MATERIALS = 128; +const sharedShapeGeometryCache = new Map(); +const sharedEdgesGeometryCache = new WeakMap>(); +const sharedShapeMaterialCache = new Map(); +const sharedLineMaterialCache = new Map(); +const shapeResourceIds = new WeakMap(); +let nextShapeResourceId = 1; const imageTextureLoader = new THREE.TextureLoader(); const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000; const NORMAL_IMPORTED_SELECTION_EDGE_ANGLE = 60; @@ -163,6 +180,9 @@ type WorkplaneViewportProps = { modifierEdges?: CadModifierEdge[]; selectedModifierEdgeIds?: number[]; onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void; + themePreference?: AppThemePreference; + resolvedTheme?: ResolvedAppTheme; + onThemePreferenceChange?: (preference: AppThemePreference) => void; }; type WorkspaceSettings = WorkplaneWorkspaceSettings; @@ -189,6 +209,15 @@ function readSavedWorkspaceDefault(key: string | null) { } } +type ShapeRenderRecord = { + object: THREE.Group; + shape: WorkplaneShape; + transformSignature: string; + materialSignature: string; + geometrySignature: string; + selected: boolean; +}; + type ThreeState = { renderer: THREE.WebGLRenderer; scene: THREE.Scene; @@ -198,6 +227,8 @@ type ThreeState = { shapeLayer: THREE.Group; helperLayer: THREE.Group; modifierLayer: THREE.Group; + shapeRecords: Map; + officialShapeLayerActive: boolean; raycaster: THREE.Raycaster; pointer: THREE.Vector2; dragPlane: THREE.Plane; @@ -228,6 +259,7 @@ declare global { get: () => ViewportPerfStats; }; sketchforgeCaptureCanvas?: () => string; + sketchforgeCaptureCanvasAsync?: () => Promise; sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise | string; } } @@ -344,6 +376,7 @@ type TransformDragState = { rotationAxisVector?: THREE.Vector3; rotationPivot?: THREE.Vector3; rotationPlaneCenter?: THREE.Vector3; + rotationPlaneView?: RotationPlaneView; rotationStartVector?: THREE.Vector3; rotationScreenCenter?: { x: number; y: number }; rotationScreenSign?: number; @@ -460,6 +493,40 @@ function screenAngle(clientX: number, clientY: number, center: { x: number; y: n return Math.atan2(clientY - center.y, clientX - center.x); } +function rotationPlanePointerLocal( + plane: RotationPlaneView | undefined, + screenX: number, + screenY: number, +) { + if (!plane) { + return null; + } + const planeX = screenX - plane.x; + const planeY = screenY - plane.y; + const determinant = plane.a * plane.d - plane.b * plane.c; + if (Math.abs(determinant) < 0.000001) { + return null; + } + return { + x: (plane.d * planeX - plane.c * planeY) / determinant, + y: (-plane.b * planeX + plane.a * planeY) / determinant, + }; +} + +function rotationPlanePointerAngle( + plane: RotationPlaneView | undefined, + screenX: number, + screenY: number, + fallbackCenter: { x: number; y: number }, +) { + const local = rotationPlanePointerLocal(plane, screenX, screenY); + return THREE.MathUtils.radToDeg( + local + ? Math.atan2(local.y, local.x) + : Math.atan2(screenY - fallbackCenter.y, screenX - fallbackCenter.x), + ); +} + function unwrapRadians(value: number) { if (value > Math.PI) { return value - Math.PI * 2; @@ -535,6 +602,21 @@ function shouldPreserveDrawingBufferForLocalAutomation() { return typeof window !== "undefined"; } +function canvasPngDataUrl(canvas: HTMLCanvasElement) { + return new Promise((resolve) => { + canvas.toBlob((blob) => { + if (!blob) { + resolve(""); + return; + } + const reader = new FileReader(); + reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : ""); + reader.onerror = () => resolve(""); + reader.readAsDataURL(blob); + }, "image/png"); + }); +} + function rotationScreenSign(axisVector: THREE.Vector3, camera: THREE.Camera) { const cameraForward = camera.getWorldDirection(new THREE.Vector3()); return axisVector.dot(cameraForward) >= 0 ? 1 : -1; @@ -589,6 +671,111 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string { }); } +function shapeResourceId(value: object | null | undefined) { + if (!value) return 0; + const existing = shapeResourceIds.get(value); + if (existing) return existing; + const next = nextShapeResourceId; + nextShapeResourceId += 1; + shapeResourceIds.set(value, next); + return next; +} + +function shapeTransformSignature(shape: WorkplaneShape) { + return [ + shape.x, + shape.z, + shape.elevation ?? 0, + shape.rotation, + shape.rotationX ?? 0, + shape.rotationZ ?? 0, + Boolean(shape.mirrorX), + Boolean(shape.mirrorY), + Boolean(shape.mirrorZ), + ].join("|"); +} + +function shapeMaterialSignature(shape: WorkplaneShape): string { + return JSON.stringify({ + color: shape.color, + hole: Boolean(shape.hole), + imagePlate: shapeResourceId(shape.imagePlate), + imageData: shape.imagePlate?.dataUrl ?? "", + sourceFormat: shape.importedMesh?.sourceFormat ?? "", + mirrored: mirroredAxisCount(shape) % 2, + cadEdges: shapeResourceId(shape.cadDisplayEdges), + cadEdgesVersion: shape.cadDisplayEdgesVersion ?? 0, + cadEdgeDimensions: shape.cadDisplayEdges?.length ? [shapeWidth(shape), shapeDepth(shape), shape.height] : null, + groupedMaterials: shape.groupedShapes?.map((child) => [child.id, child.hidden, shapeMaterialSignature(shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child)]), + }); +} + +function shapeGeometrySignature(shape: WorkplaneShape): string { + if (shape.groupedShapes?.length && !shape.importedMesh) { + return JSON.stringify({ + kind: "group", + width: shapeWidth(shape), + depth: shapeDepth(shape), + height: shape.height, + children: shape.groupedShapes.map((child) => [ + child.id, + child.hidden, + shapeWidth(child), + shapeDepth(child), + child.height, + shapeTransformSignature(child), + shapeGeometrySignature(child), + ]), + }); + } + + if (shape.importedMesh) { + return JSON.stringify({ + kind: "mesh", + mesh: shapeResourceId(shape.importedMesh), + preserve: preservesEdgeTreatmentSize(shape) + ? [shapeWidth(shape), shapeDepth(shape), shape.height, shape.edgeTreatments] + : false, + }); + } + + if (shape.kind === "box" && !(shape.radius && shape.radius > 0)) { + return JSON.stringify({ kind: "box" }); + } + if (shape.kind === "cylinder") { + return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments }); + } + if (shape.kind === "sphere") { + return JSON.stringify({ kind: "sphere", steps: shape.steps }); + } + if (shape.kind === "polygon") { + return JSON.stringify({ kind: "polygon" }); + } + + return JSON.stringify({ + kind: shape.kind, + width: shapeWidth(shape), + depth: shapeDepth(shape), + height: shape.height, + radius: shape.radius, + steps: shape.steps, + sides: shape.sides, + bevel: shape.bevel, + segments: shape.segments, + topRadius: shape.topRadius, + baseRadius: shape.baseRadius, + teeth: shape.teeth, + toothSize: shape.toothSize, + toothWidth: shape.toothWidth, + centerHoleSize: shape.centerHoleSize, + gearType: shape.gearType, + helixAngle: shape.helixAngle, + helixQuality: shape.helixQuality, + text: shape.text, + font: shape.font, + }); +} + function rulerAttachmentWorld(state: ThreeState, attachment: RulerAttachment) { const object = findShapeObject(state, attachment.shapeId); if (!object) return null; @@ -879,6 +1066,7 @@ function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; state.raycaster.setFromCamera(state.pointer, state.camera); + state.raycaster.layers.set(RENDER_LAYER_SHAPES); const surfaceHit = state.raycaster.intersectObjects(targets, true).find((entry) => entry.object instanceof THREE.Mesh); if (!surfaceHit) return null; const shapeId = surfaceHit.object.userData.shapeId as string; @@ -1573,6 +1761,9 @@ export function WorkplaneViewport({ modifierEdges = [], selectedModifierEdgeIds = [], onModifierEdgeToggle, + themePreference = "system", + resolvedTheme = "light", + onThemePreferenceChange, }: WorkplaneViewportProps) { const [snapOpen, setSnapOpen] = useState(false); const [snap, setSnap] = useState(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID)); @@ -1585,6 +1776,7 @@ export function WorkplaneViewport({ const [hoverMeasureKey, setHoverMeasureKey] = useState(null); const [pinnedMeasureKey, setPinnedMeasureKey] = useState(null); const [rotationReadout, setRotationReadout] = useState(null); + const suppressNextRotationEditRef = useRef(false); const [activeRotationWheel, setActiveRotationWheel] = useState(false); const [activeTransformKind, setActiveTransformKind] = useState(null); const [rotationWheelAxis, setRotationWheelAxis] = useState("y"); @@ -1655,6 +1847,8 @@ export function WorkplaneViewport({ const placementElevationRef = useRef(placementElevation); const workplaneModeRef = useRef(workplaneMode); + const resolvedThemeRef = useRef(resolvedTheme); + resolvedThemeRef.current = resolvedTheme; const rememberResizeAnchor = useCallback((shapeId: string, kind: TransformHandleKind, handleKey: string) => { if (kind === "scale") { @@ -1693,7 +1887,7 @@ export function WorkplaneViewport({ snapRef.current = nextSnap; workspaceRef.current = nextWorkspace; if (threeRef.current) { - rebuildWorkplane(threeRef.current, nextWorkspace); + rebuildWorkplane(threeRef.current, nextWorkspace, resolvedThemeRef.current); constrainCamera(threeRef.current, nextWorkspace); threeRef.current.needsRender = true; } @@ -1744,7 +1938,13 @@ export function WorkplaneViewport({ useEffect(() => { shapesRef.current = shapes; - rebuildShapes(threeRef.current, shapes, renderSelectionIds(), shouldBuildCutPreviews(transformRef.current, dragRef.current)); + rebuildShapes( + threeRef.current, + shapes, + renderSelectionIds(), + shouldBuildCutPreviews(transformRef.current, dragRef.current), + modifierActiveRef.current, + ); refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { syncTransformOverlay( @@ -1792,7 +1992,13 @@ export function WorkplaneViewport({ setActiveTransformKind(null); } selectedIdsRef.current = selectedIds; - rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), shouldBuildCutPreviews(transformRef.current, dragRef.current)); + rebuildShapes( + threeRef.current, + shapesRef.current, + renderSelectionIds(selectedIds), + shouldBuildCutPreviews(transformRef.current, dragRef.current), + modifierActiveRef.current, + ); refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { syncTransformOverlay( @@ -1813,13 +2019,25 @@ export function WorkplaneViewport({ useEffect(() => { modifierActiveRef.current = modifierActive; if (!modifierActive) setHoverModifierEdgeId(null); - rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current); + rebuildShapes( + threeRef.current, + shapesRef.current, + renderSelectionIds(), + !transformRef.current && !dragRef.current, + modifierActive, + ); if (threeRef.current) threeRef.current.needsRender = true; }, [modifierActive, renderSelectionIds]); useEffect(() => { modifierPreviewActiveRef.current = modifierPreviewActive; - rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current); + rebuildShapes( + threeRef.current, + shapesRef.current, + renderSelectionIds(), + !transformRef.current && !dragRef.current, + modifierActiveRef.current, + ); if (threeRef.current) threeRef.current.needsRender = true; }, [modifierPreviewActive, renderSelectionIds]); @@ -1881,7 +2099,7 @@ export function WorkplaneViewport({ useEffect(() => { workspaceRef.current = workspace; - rebuildWorkplane(threeRef.current, workspace); + rebuildWorkplane(threeRef.current, workspace, resolvedTheme); if (threeRef.current) { syncTransformOverlay( threeRef.current, @@ -1895,7 +2113,7 @@ export function WorkplaneViewport({ syncRulerOverlay(threeRef.current, rulerModelRef.current, rulerOverlayRef, setRulerOverlay, workspace.accuracy); threeRef.current.needsRender = true; } - }, [workspace]); + }, [resolvedTheme, workspace]); useEffect(() => { setSelectionHelpersVisible(threeRef.current, activeTransformKind !== "rotate"); @@ -1909,12 +2127,17 @@ export function WorkplaneViewport({ const state = createThreeScene(host); threeRef.current = state; - rebuildWorkplane(state, workspaceRef.current); + rebuildWorkplane(state, workspaceRef.current, resolvedThemeRef.current); window.sketchforgeCaptureCanvas = () => { state.camera.updateMatrixWorld(); state.renderer.render(state.scene, state.camera); return state.renderer.domElement.toDataURL("image/png"); }; + window.sketchforgeCaptureCanvasAsync = () => { + state.camera.updateMatrixWorld(); + state.renderer.render(state.scene, state.camera); + return canvasPngDataUrl(state.renderer.domElement); + }; window.sketchforgeCaptureView = (face = "current") => { if (face === "home") { resetCamera(state); @@ -1991,6 +2214,7 @@ export function WorkplaneViewport({ state.controls.dispose(); disposeChildren(state.workplaneLayer); disposeChildren(state.shapeLayer); + state.shapeRecords.clear(); disposeChildren(state.helperLayer); disposeChildren(state.modifierLayer); state.renderer.dispose(); @@ -1998,6 +2222,9 @@ export function WorkplaneViewport({ if (window.sketchforgeCaptureCanvas) { delete window.sketchforgeCaptureCanvas; } + if (window.sketchforgeCaptureCanvasAsync) { + delete window.sketchforgeCaptureCanvasAsync; + } if (window.sketchforgeCaptureView) { delete window.sketchforgeCaptureView; } @@ -2365,7 +2592,7 @@ export function WorkplaneViewport({ const beginTransform = useCallback( (kind: TransformHandleKind, handleKey: string, event: ReactPointerEvent) => { - if (kind === "rotate" && event.button !== 0) { + if (event.button !== 0) { return; } const ids = selectedIdsRef.current; @@ -2456,6 +2683,7 @@ export function WorkplaneViewport({ rotationAxisVector: kind === "rotate" ? axisVector : undefined, rotationPivot: kind === "rotate" ? pivot : undefined, rotationPlaneCenter: kind === "rotate" ? rotationPlaneCenter : undefined, + rotationPlaneView: kind === "rotate" ? rotationPlane : undefined, rotationStartVector: kind === "rotate" ? rotationStartVector : undefined, rotationScreenCenter: rotationCenter, rotationScreenSign: kind === "rotate" && state ? rotationScreenSign(axisVector, state.camera) : 1, @@ -2469,6 +2697,7 @@ export function WorkplaneViewport({ y: event.clientY - renderRect.top - 18, text: `${Math.round(rotationValueForAxis(shape, rotationAxis))}°`, angle: 0, + pointerAngle: rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY }), }); } else if (kind === "lift" && state) { const renderRect = state.renderer.domElement.getBoundingClientRect(); @@ -2493,7 +2722,7 @@ export function WorkplaneViewport({ ); const beginCameraDragFromOverlay = useCallback((event: ReactPointerEvent) => { - if (event.button !== 2) { + if (event.button !== 1 && event.button !== 2) { return; } @@ -2530,6 +2759,38 @@ export function WorkplaneViewport({ ); }, []); + const forwardCameraWheelFromOverlay = useCallback((event: ReactWheelEvent) => { + const state = threeRef.current; + const canvas = state?.renderer.domElement; + const WheelEventConstructor = canvas?.ownerDocument.defaultView?.WheelEvent; + if (!canvas || !WheelEventConstructor) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + const source = event.nativeEvent; + canvas.dispatchEvent( + new WheelEventConstructor("wheel", { + bubbles: true, + cancelable: true, + composed: true, + deltaX: source.deltaX, + deltaY: source.deltaY, + deltaZ: source.deltaZ, + deltaMode: source.deltaMode, + clientX: source.clientX, + clientY: source.clientY, + screenX: source.screenX, + screenY: source.screenY, + ctrlKey: source.ctrlKey, + shiftKey: source.shiftKey, + altKey: source.altKey, + metaKey: source.metaKey, + }), + ); + }, []); + const updateTransform = useCallback( (clientX: number, clientY: number, shiftKey = false, altKey = false) => { const transform = transformRef.current; @@ -2642,11 +2903,17 @@ export function WorkplaneViewport({ currentPoint && transform.rotationStartVector && transform.rotationStartVector.lengthSq() > 0.000001 ? THREE.MathUtils.radToDeg(signedAngleAroundAxis(transform.rotationStartVector, currentPoint.sub(planeCenter), axisVector)) : THREE.MathUtils.radToDeg(unwrapRadians(screenAngle(localClientX, localClientY, rotationCenter) - transform.startScreenAngle)) * (transform.rotationScreenSign ?? 1); - const distance = transform.wheelCenter ? Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) : Number.POSITIVE_INFINITY; + const localRotationPointer = rotationPlanePointerLocal(transform.rotationPlaneView, localClientX, localClientY); + const insideSnapWheel = localRotationPointer + ? Math.hypot(localRotationPointer.x, localRotationPointer.y) <= ROTATION_PROTRACTOR_OUTER_RADIUS + : Boolean( + transform.wheelCenter + && Math.hypot(localClientX - transform.wheelCenter.x, localClientY - transform.wheelCenter.y) <= transform.wheelCenter.radius + ); let delta: number; if (shiftKey) { delta = Math.round(rawDelta / 45) * 45; - } else if (transform.wheelCenter && distance <= transform.wheelCenter.radius) { + } else if (insideSnapWheel) { delta = Math.round(rawDelta / 22.5) * 22.5; } else { delta = Math.round(rawDelta); @@ -2660,6 +2927,7 @@ export function WorkplaneViewport({ y: transform.wheelCenter ? transform.wheelCenter.y - 92 : localClientY - 18, text: `${Number(delta.toFixed(1))}°`, angle: delta, + pointerAngle: rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter), }); } transform.items.forEach((item) => { @@ -2700,6 +2968,12 @@ export function WorkplaneViewport({ if (transform.kind === "lift" && transform.hasMoved) { suppressLiftEditAfterDrag(); } + if (transform.kind === "rotate" && transform.hasMoved) { + suppressNextRotationEditRef.current = true; + window.setTimeout(() => { + suppressNextRotationEditRef.current = false; + }, 250); + } transformRef.current = null; setActiveRotationWheel(false); setActiveTransformKind(null); @@ -2798,6 +3072,10 @@ export function WorkplaneViewport({ }, []); const beginRotationEdit = useCallback((handleKey: string, x: number, y: number) => { + if (suppressNextRotationEditRef.current) { + suppressNextRotationEditRef.current = false; + return; + } const axis = rotationAxisForHandle(handleKey); const shape = selectedIdsRef.current.length === 1 ? shapesRef.current.find((entry) => entry.id === selectedIdsRef.current[0]) : null; const currentValue = shape ? rotationValueForAxis(shape, axis) : 0; @@ -2842,6 +3120,7 @@ export function WorkplaneViewport({ state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; state.raycaster.setFromCamera(state.pointer, state.camera); + state.raycaster.layers.set(RENDER_LAYER_SHAPES); const intersections = state.raycaster.intersectObjects(state.shapeLayer.children, true); const hit = intersections.find((entry) => typeof entry.object.userData.shapeId === "string"); @@ -2891,6 +3170,7 @@ export function WorkplaneViewport({ state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; state.raycaster.setFromCamera(state.pointer, state.camera); + state.raycaster.layers.set(RENDER_LAYER_HELPERS); const intersections = state.raycaster.intersectObjects(state.helperLayer.children, true); const hit = intersections.find((entry) => typeof entry.object.userData.transformHandle === "string"); @@ -3042,6 +3322,7 @@ export function WorkplaneViewport({ rotationAxisVector: handle.kind === "rotate" ? axisVector : undefined, rotationPivot: handle.kind === "rotate" ? pivot : undefined, rotationPlaneCenter: handle.kind === "rotate" ? rotationPlaneCenter : undefined, + rotationPlaneView: handle.kind === "rotate" ? rotationPlane : undefined, rotationStartVector: handle.kind === "rotate" ? rotationStartVector : undefined, rotationScreenCenter: rotationCenter, rotationScreenSign: handle.kind === "rotate" ? rotationScreenSign(axisVector, state.camera) : 1, @@ -3054,6 +3335,7 @@ export function WorkplaneViewport({ y: event.clientY - rect.top - 18, text: `${Math.round(rotationValueForAxis(shape, rotationAxis))}°`, angle: 0, + pointerAngle: rotationPlanePointerAngle(rotationPlane, localClientX, localClientY, rotationCenter ?? { x: localClientX, y: localClientY }), }); } else if (handle.kind === "lift") { setRotationReadout({ @@ -3123,7 +3405,7 @@ export function WorkplaneViewport({ event.currentTarget.setPointerCapture(event.pointerId); const dragIds = alreadySelected && selectedIdsSnapshot.length > 1 ? selectedIdsSnapshot : [id]; const items = dragIds - .map((dragId) => { + .map((dragId) => { const dragShape = shapesRef.current.find((entry) => entry.id === dragId); if (!dragShape || dragShape.locked) { return null; @@ -3690,6 +3972,7 @@ export function WorkplaneViewport({ rotationWheelAxis={rotationWheelAxis} pinnedRotationWheelView={pinnedRotationWheelView} onBeginCameraDrag={beginCameraDragFromOverlay} + onCameraWheel={forwardCameraWheelFromOverlay} onBeginTransform={beginTransform} onMoveTransform={updateTransform} onFinishTransform={finishTransform} @@ -3750,8 +4033,10 @@ export function WorkplaneViewport({ setSettingsOpen(false)} /> @@ -3773,6 +4058,10 @@ function createThreeScene(host: HTMLDivElement): ThreeState { scene.background = new THREE.Color("#f8fbfc"); const camera = new THREE.PerspectiveCamera(38, host.clientWidth / Math.max(1, host.clientHeight), 0.1, 6000); + camera.layers.enable(RENDER_LAYER_SHAPES); + camera.layers.enable(RENDER_LAYER_HELPERS); + camera.layers.enable(RENDER_LAYER_MODIFIERS); + camera.layers.enable(RENDER_LAYER_PREVIEWS); const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.08; @@ -3813,16 +4102,21 @@ function createThreeScene(host: HTMLDivElement): ThreeState { const workplaneLayer = new THREE.Group(); workplaneLayer.name = "Workplane"; + workplaneLayer.layers.set(RENDER_LAYER_WORKPLANE); const shapeLayer = new THREE.Group(); shapeLayer.name = "Shapes"; + shapeLayer.layers.set(RENDER_LAYER_SHAPES); const helperLayer = new THREE.Group(); helperLayer.name = "SelectionHelpers"; + helperLayer.layers.set(RENDER_LAYER_HELPERS); const modifierLayer = new THREE.Group(); modifierLayer.name = "EdgeModifier"; + modifierLayer.layers.set(RENDER_LAYER_MODIFIERS); scene.add(workplaneLayer, shapeLayer, helperLayer, modifierLayer); const raycaster = new THREE.Raycaster(); raycaster.params.Line = { threshold: 1.15 }; + (raycaster as THREE.Raycaster & { firstHitOnly?: boolean }).firstHitOnly = true; const pointer = new THREE.Vector2(); const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0); @@ -3844,6 +4138,8 @@ function createThreeScene(host: HTMLDivElement): ThreeState { shapeLayer, helperLayer, modifierLayer, + shapeRecords: new Map(), + officialShapeLayerActive: false, raycaster, pointer, dragPlane, @@ -3948,22 +4244,44 @@ function syncViewCube(state: ThreeState, cube: HTMLDivElement | null) { cube.style.transform = `rotateX(${-pitch}deg) rotateY(${-yaw}deg)`; } -function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings) { +function setObjectRenderLayer(object: THREE.Object3D, layer: number) { + object.traverse((child) => child.layers.set(layer)); +} + +function freezeStaticObjectMatrices(object: THREE.Object3D) { + object.traverse((child) => { + child.updateMatrix(); + child.matrixAutoUpdate = false; + }); + object.updateMatrixWorld(true); +} + +function refreshFrozenObjectMatrix(object: THREE.Object3D) { + object.updateMatrix(); + object.updateMatrixWorld(true); +} + +function rebuildWorkplane( + state: ThreeState | null, + workspace: WorkspaceSettings, + theme: ResolvedAppTheme = "light", +) { if (!state) { return; } + const palette = workplaneThemePalette(theme, workspace.background, workspace.gridColor); disposeChildren(state.workplaneLayer); - state.scene.background = new THREE.Color(workspace.background); + state.scene.background = new THREE.Color(palette.sceneBackground); state.renderer.shadowMap.enabled = workspace.showShadows; state.controls.zoomSpeed = 0.28 + workspace.zoomSpeed * 0.09; const base = new THREE.Mesh( new THREE.PlaneGeometry(workspace.width, workspace.depth), new THREE.MeshStandardMaterial({ - color: "#ddf8ff", + color: palette.surface.color, transparent: true, - opacity: 0.68, + opacity: palette.surface.opacity, roughness: 0.92, side: THREE.FrontSide, polygonOffset: true, @@ -3977,13 +4295,21 @@ function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings state.workplaneLayer.add(base); if (workspace.showGrid) { - state.workplaneLayer.add(createGridLines(workspace.width, workspace.depth, workspace.gridBlockSize)); + state.workplaneLayer.add(createGridLines(workspace.width, workspace.depth, workspace.gridBlockSize, theme, workspace.gridColor)); } + setObjectRenderLayer(state.workplaneLayer, RENDER_LAYER_WORKPLANE); + freezeStaticObjectMatrices(state.workplaneLayer); } -function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, blockSize = DEFAULT_WORKSPACE.gridBlockSize) { +function createGridLines( + width = WORKPLANE_WIDTH, + depth = WORKPLANE_DEPTH, + blockSize = DEFAULT_WORKSPACE.gridBlockSize, + theme: ResolvedAppTheme = "light", + gridColor = DEFAULT_WORKSPACE.gridColor, +) { const group = new THREE.Group(); - const palette = workplaneGridPalette(); + const palette = workplaneThemePalette(theme, DEFAULT_WORKSPACE.background, gridColor).grid; const minor = new THREE.LineBasicMaterial({ ...palette.minor, transparent: true, depthWrite: false }); const major = new THREE.LineBasicMaterial({ ...palette.major, transparent: true, depthWrite: false }); const axis = new THREE.LineBasicMaterial({ ...palette.axis, transparent: true, depthWrite: false }); @@ -4198,6 +4524,8 @@ function addCutPreviewOverlays(state: ThreeState, holeFrame: CutPreviewShapeFram preview.renderOrder = 18; preview.userData.cutPreview = true; preview.raycast = () => undefined; + setObjectRenderLayer(preview, RENDER_LAYER_PREVIEWS); + freezeStaticObjectMatrices(preview); state.shapeLayer.add(preview); }); } @@ -4239,27 +4567,213 @@ function syncCutPreviewOverlays(state: ThreeState, shapes: WorkplaneShape[]) { }); } -function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selectedIds: string[], showCutPreviews = true) { +function updateShapeObjectTransform(object: THREE.Group, shape: WorkplaneShape) { + object.name = shape.name; + object.userData.shapeId = shape.id; + object.userData.rulerDimensions = [shapeWidth(shape), shape.height, shapeDepth(shape)] satisfies [number, number, number]; + object.userData.rulerTopologyKey = rulerShapeTopologyKey(shape); + object.position.set(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); + object.rotation.set( + THREE.MathUtils.degToRad(shape.rotationX ?? 0), + THREE.MathUtils.degToRad(shape.rotation), + THREE.MathUtils.degToRad(shape.rotationZ ?? 0), + ); + object.scale.set(mirrorSign(shape.mirrorX), mirrorSign(shape.mirrorY), mirrorSign(shape.mirrorZ)); + refreshFrozenObjectMatrix(object); +} + +function syncShapeObjectDimensions(object: THREE.Group, shape: WorkplaneShape) { + object.userData.rulerDimensions = [shapeWidth(shape), shape.height, shapeDepth(shape)] satisfies [number, number, number]; + object.userData.rulerTopologyKey = rulerShapeTopologyKey(shape); + const surface = object.children.find((child): child is THREE.Mesh => child instanceof THREE.Mesh && Boolean(child.userData.shapeSurface)); + if (!surface) return; + const width = shapeWidth(shape); + const depth = shapeDepth(shape); + let scale: THREE.Vector3 | null = null; + if (shape.importedMesh && !preservesEdgeTreatmentSize(shape)) { + scale = new THREE.Vector3( + width / Math.max(0.001, shape.importedMesh.baseWidth), + shape.height / Math.max(0.001, shape.importedMesh.baseHeight), + depth / Math.max(0.001, shape.importedMesh.baseDepth), + ); + } else if (shape.kind === "box" && !(shape.radius && shape.radius > 0)) { + scale = new THREE.Vector3(width, shape.height, depth); + } else if (shape.kind === "cylinder" || shape.kind === "polygon") { + scale = new THREE.Vector3(width / 2, shape.height, depth / 2); + } else if (shape.kind === "sphere") { + scale = new THREE.Vector3(width / 2, shape.height / 2, depth / 2); + } + if (!scale) return; + + object.position.y = (shape.elevation ?? 0) + shape.height / 2; + object.updateMatrix(); + surface.scale.copy(scale); + surface.position.y = -shape.height / 2; + surface.updateMatrix(); + object.children.forEach((child) => { + if (!child.userData.shapeEdge) return; + child.position.copy(surface.position); + child.rotation.copy(surface.rotation); + child.scale.copy(surface.scale); + child.updateMatrix(); + }); + object.updateMatrixWorld(true); +} + +function removeShapeDecorations(object: THREE.Group) { + object.children + .filter((child) => Boolean(child.userData.shapeDecoration)) + .forEach((child) => { + object.remove(child); + disposeObject(child); + }); +} + +function syncShapeObjectAppearance(object: THREE.Group, shape: WorkplaneShape, selected: boolean, updateSurfaceMaterial: boolean, onTextureReady?: () => void) { + object.userData.showEdges = selected; + const groupedContent = object.children.find((child): child is THREE.Group => child instanceof THREE.Group && Boolean(child.userData.groupedShapeContent)); + if (groupedContent && shape.groupedShapes?.length && !shape.importedMesh) { + shape.groupedShapes + .filter((child) => !child.hidden) + .forEach((child) => { + const childObject = groupedContent.children.find((entry): entry is THREE.Group => entry instanceof THREE.Group && entry.userData.groupChildId === child.id); + if (!childObject) return; + const childShape = shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child; + syncShapeObjectAppearance(childObject, childShape, selected, updateSurfaceMaterial, onTextureReady); + }); + object.traverse((child) => { + child.userData.shapeId = shape.id; + }); + setObjectRenderLayer(object, RENDER_LAYER_SHAPES); + freezeStaticObjectMatrices(object); + return; + } + + const surface = object.children.find((child): child is THREE.Mesh => child instanceof THREE.Mesh && Boolean(child.userData.shapeSurface)); + if (!surface) return; + if (updateSurfaceMaterial) { + const material = sharedShapeMaterial(shape); + const nextMaterial = shape.kind === "box" && shape.imagePlate && !shape.hole + ? createImagePlateMaterials(shape, material, onTextureReady) + : material; + const currentMaterials = Array.isArray(surface.material) ? surface.material : null; + const sameMaterial = Array.isArray(nextMaterial) + ? Boolean(currentMaterials && nextMaterial.every((entry, index) => currentMaterials[index] === entry)) + : surface.material === nextMaterial; + if (!sameMaterial) { + replaceObjectMaterials(surface, nextMaterial); + } + } + removeShapeDecorations(object); + addShapeEdgeDecorations(object, surface, surface.geometry, shape); + object.traverse((child) => { + child.userData.shapeId = shape.id; + }); + setObjectRenderLayer(object, RENDER_LAYER_SHAPES); + freezeStaticObjectMatrices(object); +} + +function rebuildShapes( + state: ThreeState | null, + shapes: WorkplaneShape[], + selectedIds: string[], + showCutPreviews = true, + useOfficialModifierRendering = false, +) { if (!state) { return; } - disposeChildren(state.shapeLayer); - + clearCutPreviewOverlays(state); const selected = new Set(selectedIds); const visibleShapes = shapes.filter((shape) => !shape.hidden); - visibleShapes.forEach((shape) => { - const object = createShapeObject(shape, selected.has(shape.id), () => { - state.needsRender = true; - }); - state.shapeLayer.add(object); + if (useOfficialModifierRendering) { + disposeChildren(state.shapeLayer); + state.shapeRecords.clear(); + state.officialShapeLayerActive = true; + visibleShapes.forEach((shape) => { + const object = createShapeObject(shape, selected.has(shape.id), () => { + state.needsRender = true; + }, false); + state.shapeLayer.add(object); + }); + if (showCutPreviews) { + syncCutPreviewOverlays(state, visibleShapes); + } + rebuildSelectionHelpers(state, shapes, selectedIds); + state.needsRender = true; + return; + } + + if (state.officialShapeLayerActive) { + disposeChildren(state.shapeLayer); + state.shapeRecords.clear(); + state.officialShapeLayerActive = false; + } + + const visibleIds = new Set(visibleShapes.map((shape) => shape.id)); + state.shapeRecords.forEach((record, id) => { + if (visibleIds.has(id)) return; + state.shapeLayer.remove(record.object); + disposeObject(record.object); + state.shapeRecords.delete(id); }); + + visibleShapes.forEach((shape) => { + const selectedShape = selected.has(shape.id); + const transformSignature = shapeTransformSignature(shape); + const materialSignature = shapeMaterialSignature(shape); + const geometrySignature = shapeGeometrySignature(shape); + let record = state.shapeRecords.get(shape.id); + if (record && record.geometrySignature !== geometrySignature) { + state.shapeLayer.remove(record.object); + disposeObject(record.object); + state.shapeRecords.delete(shape.id); + record = undefined; + } + + if (!record) { + const object = createShapeObject(shape, selectedShape, () => { + state.needsRender = true; + }); + state.shapeLayer.add(object); + record = { + object, + shape, + transformSignature, + materialSignature, + geometrySignature, + selected: selectedShape, + }; + state.shapeRecords.set(shape.id, record); + return; + } + + if (record.transformSignature !== transformSignature) { + updateShapeObjectTransform(record.object, shape); + } + record.object.name = shape.name; + syncShapeObjectDimensions(record.object, shape); + const materialChanged = record.materialSignature !== materialSignature; + if (materialChanged || record.selected !== selectedShape) { + syncShapeObjectAppearance(record.object, shape, selectedShape, materialChanged, () => { + state.needsRender = true; + }); + } + record.shape = shape; + record.transformSignature = transformSignature; + record.materialSignature = materialSignature; + record.geometrySignature = geometrySignature; + record.selected = selectedShape; + }); + if (showCutPreviews) { syncCutPreviewOverlays(state, visibleShapes); } rebuildSelectionHelpers(state, shapes, selectedIds); + state.needsRender = true; } function modifierEdgeMaterialStyle(active: boolean, hovered: boolean, previewActive: boolean) { @@ -4293,6 +4807,8 @@ function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[] const line = new THREE.Line(geometry, material); line.userData.modifierEdgeId = edge.id; line.renderOrder = hovered ? 1003 : active ? 1002 : 1001; + setObjectRenderLayer(line, RENDER_LAYER_MODIFIERS); + freezeStaticObjectMatrices(line); state.modifierLayer.add(line); }); state.needsRender = true; @@ -4311,6 +4827,8 @@ function rebuildSelectionHelpers(state: ThreeState | null, shapes: WorkplaneShap } const shadow = createSelectedGroundFootprint(shape); if (shadow) { + setObjectRenderLayer(shadow, RENDER_LAYER_HELPERS); + freezeStaticObjectMatrices(shadow); state.helperLayer.add(shadow); } }); @@ -4908,7 +5426,7 @@ function syncMirrorOverlay( } function findShapeObject(state: ThreeState, id: string) { - return state.shapeLayer.children.find((child) => child.userData.shapeId === id) ?? null; + return state.shapeRecords.get(id)?.object ?? null; } function findSelectionHelper(state: ThreeState, id: string) { @@ -4936,13 +5454,13 @@ function applyDragItemPreview(state: ThreeState, item: DragItem) { } item.visual.position.x = item.nextX; item.visual.position.z = item.nextZ; - item.visual.updateMatrixWorld(true); + refreshFrozenObjectMatrix(item.visual); } if (item.helper && item.helperBox) { item.helper.box.copy(item.helperBox); item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ)); - item.helper.updateMatrixWorld(true); + refreshFrozenObjectMatrix(item.helper); } } @@ -4961,7 +5479,7 @@ function updateSelectedGroundFootprintPreviews(state: ThreeState, drag: DragStat } footprint.position.x = item.nextX - item.startX; footprint.position.z = item.nextZ - item.startZ; - footprint.updateMatrixWorld(true); + refreshFrozenObjectMatrix(footprint); }); } @@ -5137,11 +5655,171 @@ function createRotateArc(center: THREE.Vector3, radius: number, start: number, e return new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), material); } -function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureReady?: () => void) { +function sharedShapeGeometry(key: string, create: () => THREE.BufferGeometry) { + const cached = sharedShapeGeometryCache.get(key); + if (cached) { + sharedShapeGeometryCache.delete(key); + sharedShapeGeometryCache.set(key, cached); + return cached.geometry; + } + const geometry = putGeometryOnBase(create()); + geometry.userData.cached = true; + geometry.userData.sharedShapeGeometryKey = key; + sharedShapeGeometryCache.set(key, { geometry, users: 0 }); + return geometry; +} + +function disposeSharedShapeGeometry(geometry: THREE.BufferGeometry) { + const edges = sharedEdgesGeometryCache.get(geometry); + edges?.forEach((entry) => entry.dispose()); + if ((geometry as THREE.BufferGeometry & { boundsTree?: unknown }).boundsTree) { + disposeBoundsTree.call(geometry); + } + geometry.dispose(); +} + +function trimSharedShapeGeometryCache() { + while (sharedShapeGeometryCache.size > MAX_SHARED_SHAPE_GEOMETRIES) { + const removable = [...sharedShapeGeometryCache.entries()].find(([, entry]) => entry.users === 0); + if (!removable) return; + const [key, entry] = removable; + sharedShapeGeometryCache.delete(key); + disposeSharedShapeGeometry(entry.geometry); + } +} + +function retainSharedShapeGeometry(mesh: THREE.Mesh, geometry: THREE.BufferGeometry) { + const key = geometry.userData.sharedShapeGeometryKey as string | undefined; + if (!key) return; + const entry = sharedShapeGeometryCache.get(key); + if (!entry || entry.geometry !== geometry) return; + entry.users += 1; + mesh.userData.sharedShapeGeometryKey = key; + trimSharedShapeGeometryCache(); +} + +function releaseSharedShapeGeometry(mesh: THREE.Mesh | THREE.LineSegments) { + const key = mesh.userData.sharedShapeGeometryKey as string | undefined; + if (!key) return; + mesh.userData.sharedShapeGeometryKey = undefined; + const entry = sharedShapeGeometryCache.get(key); + if (entry && entry.geometry === mesh.geometry) { + entry.users = Math.max(0, entry.users - 1); + } + trimSharedShapeGeometryCache(); +} + +function sharedShapeMaterial(shape: WorkplaneShape) { + const key = JSON.stringify({ + color: shape.hole ? "#b7c0c9" : shape.color, + transparent: Boolean(shape.hole), + opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, + roughness: shape.hole ? 0.88 : 0.57, + side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? "double" : "front", + }); + const cached = sharedShapeMaterialCache.get(key); + if (cached) { + sharedShapeMaterialCache.delete(key); + sharedShapeMaterialCache.set(key, cached); + return cached.material; + } + const material = new THREE.MeshStandardMaterial({ + color: shape.hole ? "#b7c0c9" : shape.color, + transparent: Boolean(shape.hole), + opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, + roughness: shape.hole ? 0.88 : 0.57, + metalness: 0.02, + side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, + }); + material.userData.cached = true; + material.userData.sharedShapeMaterialKey = key; + sharedShapeMaterialCache.set(key, { material, users: 0 }); + return material; +} + +function trimSharedShapeMaterialCache() { + while (sharedShapeMaterialCache.size > MAX_SHARED_SHAPE_MATERIALS) { + const removable = [...sharedShapeMaterialCache.entries()].find(([, entry]) => entry.users === 0); + if (!removable) return; + const [key, entry] = removable; + sharedShapeMaterialCache.delete(key); + entry.material.dispose(); + } +} + +function retainSharedShapeMaterials(mesh: THREE.Mesh, materials: THREE.Material | THREE.Material[]) { + const retained: string[] = []; + (Array.isArray(materials) ? materials : [materials]).forEach((material) => { + const key = material.userData.sharedShapeMaterialKey as string | undefined; + if (!key || retained.includes(key)) return; + const entry = sharedShapeMaterialCache.get(key); + if (!entry || entry.material !== material) return; + entry.users += 1; + retained.push(key); + }); + mesh.userData.sharedShapeMaterialKeys = retained; + trimSharedShapeMaterialCache(); +} + +function releaseSharedShapeMaterials(mesh: THREE.Mesh | THREE.LineSegments) { + const keys = mesh.userData.sharedShapeMaterialKeys as string[] | undefined; + if (!keys?.length) return; + mesh.userData.sharedShapeMaterialKeys = []; + keys.forEach((key) => { + const entry = sharedShapeMaterialCache.get(key); + if (entry) entry.users = Math.max(0, entry.users - 1); + }); +} + +function sharedLineMaterial(color: string, opacity: number, depthWrite = true) { + const key = `${color}|${opacity}|${depthWrite}`; + const cached = sharedLineMaterialCache.get(key); + if (cached) return cached; + const material = new THREE.LineBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite }); + material.userData.cached = true; + sharedLineMaterialCache.set(key, material); + return material; +} + +function disposeMaterialResource(material: THREE.Material) { + if (material.userData.cached) return; + const map = "map" in material ? (material.map as THREE.Texture | null) : null; + if (map) map.dispose(); + material.dispose(); +} + +function replaceObjectMaterials(object: THREE.Mesh, materials: THREE.Material | THREE.Material[]) { + const previous = Array.isArray(object.material) ? object.material : [object.material]; + releaseSharedShapeMaterials(object); + object.material = materials; + retainSharedShapeMaterials(object, materials); + previous.forEach(disposeMaterialResource); + trimSharedShapeMaterialCache(); +} + +function enableAcceleratedMeshPicking(mesh: THREE.Mesh, geometry: THREE.BufferGeometry, force = false) { + const position = geometry.getAttribute("position"); + const triangles = geometry.getIndex()?.count + ? Math.floor((geometry.getIndex()?.count ?? 0) / 3) + : Math.floor((position?.count ?? 0) / 3); + mesh.raycast = acceleratedRaycast; + const bvhGeometry = geometry as THREE.BufferGeometry & { boundsTree?: unknown }; + if ((force || triangles >= BVH_PICKING_TRIANGLE_THRESHOLD) && !bvhGeometry.boundsTree) { + computeBoundsTree.call(geometry, { maxLeafSize: 12 }); + } +} + +function createShapeObject( + shape: WorkplaneShape, + showEdges = false, + onTextureReady?: () => void, + acceleratedPicking = true, +) { const group = new THREE.Group(); group.name = shape.name; group.userData.shapeId = shape.id; group.userData.showEdges = showEdges; + group.userData.acceleratedPicking = acceleratedPicking; group.userData.rulerDimensions = [shapeWidth(shape), shape.height, shapeDepth(shape)] satisfies [number, number, number]; group.userData.rulerTopologyKey = rulerShapeTopologyKey(shape); group.position.set(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); @@ -5154,11 +5832,13 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe if (shape.groupedShapes?.length && !shape.importedMesh) { const content = new THREE.Group(); + content.userData.groupedShapeContent = true; shape.groupedShapes .filter((child) => !child.hidden) .forEach((child) => { const childShape = shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child; - const childObject = createShapeObject(childShape, showEdges, onTextureReady); + const childObject = createShapeObject(childShape, showEdges, onTextureReady, acceleratedPicking); + childObject.userData.groupChildId = child.id; content.add(childObject); }); const contentBox = new THREE.Box3().setFromObject(content); @@ -5173,46 +5853,48 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe group.traverse((child) => { child.userData.shapeId = shape.id; }); + setObjectRenderLayer(group, RENDER_LAYER_SHAPES); + freezeStaticObjectMatrices(group); return group; } - const material = new THREE.MeshStandardMaterial({ - color: shape.hole ? "#b7c0c9" : shape.color, - transparent: Boolean(shape.hole), - opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, - roughness: shape.hole ? 0.88 : 0.57, - metalness: 0.02, - side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, - }); + const material = sharedShapeMaterial(shape); const width = shapeWidth(shape); const depth = shapeDepth(shape); const size = Math.min(width, depth); const height = shape.height; + const geometryCacheKey = shapeGeometrySignature(shape); switch (shape.kind) { case "box": addMesh( group, - shape.radius && shape.radius > 0 - ? new RoundedBoxGeometry(width, height, depth, Math.max(1, shape.steps ?? 10), shape.radius) - : new THREE.BoxGeometry(width, height, depth), + sharedShapeGeometry( + geometryCacheKey, + () => shape.radius && shape.radius > 0 + ? new RoundedBoxGeometry(width, height, depth, Math.max(1, shape.steps ?? 10), shape.radius) + : new THREE.BoxGeometry(1, 1, 1), + ), shape.imagePlate && !shape.hole ? createImagePlateMaterials(shape, material, onTextureReady) : material, shape, + undefined, + undefined, + shape.radius && shape.radius > 0 ? undefined : new THREE.Vector3(width, height, depth), ); break; case "cylinder": - addMesh(group, new THREE.CylinderGeometry(1, 1, height, shape.sides ?? 96, shape.segments ?? 1), material, shape, undefined, undefined, new THREE.Vector3(width / 2, 1, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, shape.sides ?? 96, shape.segments ?? 1)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2)); break; case "sphere": { const { widthSegments, heightSegments } = sphereTessellation(shape.steps); - addMesh(group, new THREE.SphereGeometry(1, widthSegments, heightSegments), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.SphereGeometry(1, widthSegments, heightSegments)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2)); break; } case "cone": addMesh( group, - new THREE.CylinderGeometry(shape.topRadius ?? 0, shape.baseRadius ?? width / 2, height, shape.sides ?? 96), + sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(shape.topRadius ?? 0, shape.baseRadius ?? width / 2, height, shape.sides ?? 96)), material, shape, undefined, @@ -5221,28 +5903,28 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe ); break; case "pyramid": - addMesh(group, createPyramidGeometry(width, height, depth, shape.sides ?? 4), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createPyramidGeometry(width, height, depth, shape.sides ?? 4)), material, shape); break; case "roof": - addMesh(group, createRoofGeometry(width, height, depth), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoofGeometry(width, height, depth)), material, shape); break; case "roundRoof": - addMesh(group, createRoundRoofGeometry(width, height, depth, shape.sides ?? 64), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoundRoofGeometry(width, height, depth, shape.sides ?? 64)), material, shape); break; case "halfSphere": - addMesh(group, createHalfSphereGeometry(width, height, depth, shape.steps ?? 32), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHalfSphereGeometry(width, height, depth, shape.steps ?? 32)), material, shape); break; case "torus": - addMesh(group, createTorusGeometry(width, height, depth), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createTorusGeometry(width, height, depth)), material, shape); break; case "ring": - addMesh(group, createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape); break; case "tube": - addMesh(group, createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape); break; case "gear": - addMesh(group, createGearGeometry({ + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createGearGeometry({ width, depth, height, @@ -5253,19 +5935,19 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe gearType: shape.gearType, helixAngle: shape.helixAngle, helixQuality: shape.helixQuality, - }), material, shape); + })), material, shape); break; case "wedge": - addMesh(group, createWedgeGeometry(width, height, depth), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createWedgeGeometry(width, height, depth)), material, shape); break; case "polygon": - addMesh(group, new THREE.CylinderGeometry(1, 1, height, 6), material, shape, undefined, undefined, new THREE.Vector3(width / 2, 1, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, 6)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2)); break; case "icosahedron": - addMesh(group, new THREE.IcosahedronGeometry(size / 2, 1), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.IcosahedronGeometry(size / 2, 1)), material, shape); break; case "text": - addTextShape(group, material, shape); + addTextShape(group, material, shape, geometryCacheKey); break; case "mesh": if (shape.importedMesh) { @@ -5284,21 +5966,23 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe ), ); } else { - addMesh(group, new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape); } break; case "scribble": - addMesh(group, new THREE.TorusKnotGeometry(size * 0.22, size * 0.055, 120, 12), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.TorusKnotGeometry(size * 0.22, size * 0.055, 120, 12)), material, shape); break; case "sketch": default: - addMesh(group, new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape); break; } group.traverse((child) => { child.userData.shapeId = shape.id; }); + setObjectRenderLayer(group, RENDER_LAYER_SHAPES); + freezeStaticObjectMatrices(group); return group; } @@ -5348,6 +6032,12 @@ function addMesh( ) { const prepared = geometry.userData.cached ? geometry : putGeometryOnBase(geometry); const mesh = new THREE.Mesh(prepared, material); + mesh.userData.shapeSurface = true; + retainSharedShapeGeometry(mesh, prepared); + retainSharedShapeMaterials(mesh, material); + if (group.userData.acceleratedPicking !== false && !shape.edgeTreatments?.length) { + enableAcceleratedMeshPicking(mesh, prepared, Boolean(shape.importedMesh)); + } mesh.castShadow = true; mesh.receiveShadow = false; if (position) { @@ -5361,7 +6051,10 @@ function addMesh( mesh.scale.copy(scale); } group.add(mesh); + addShapeEdgeDecorations(group, mesh, prepared, shape); +} +function addShapeEdgeDecorations(group: THREE.Group, mesh: THREE.Mesh, prepared: THREE.BufferGeometry, shape: WorkplaneShape) { const complexEdges = shape.kind === "mesh" || Boolean(shape.importedMesh) || @@ -5377,8 +6070,10 @@ function addMesh( addCadDisplayEdges(group, shape, edgeColor, edgeOpacity); } else { const selectedThreshold = shape.importedMesh ? NORMAL_IMPORTED_SELECTION_EDGE_ANGLE : 1; - const edges = new THREE.LineSegments(getEdgesGeometry(shape, prepared, selectedOutline ? selectedThreshold : complexEdges ? 14 : 25), new THREE.LineBasicMaterial({ color: edgeColor, transparent: true, opacity: edgeOpacity })); + const edges = new THREE.LineSegments(getEdgesGeometry(shape, prepared, selectedOutline ? selectedThreshold : complexEdges ? 14 : 25), sharedLineMaterial(edgeColor, edgeOpacity)); edges.userData.complexEdge = complexEdges; + edges.userData.shapeDecoration = true; + edges.userData.shapeEdge = true; edges.position.copy(mesh.position); edges.rotation.copy(mesh.rotation); edges.scale.copy(mesh.scale); @@ -5389,7 +6084,7 @@ function addMesh( function addCadDisplayEdges(group: THREE.Group, shape: WorkplaneShape, color: string, opacity: number) { if (!shape.cadDisplayEdges?.length) return; - const material = new THREE.LineBasicMaterial({ color, depthWrite: false, transparent: true, opacity }); + const material = sharedLineMaterial(color, opacity, false); shape.cadDisplayEdges.forEach((edge) => { if (edge.points.length < 6) return; const positions = resizedImportedCoordinates(shape, edge.points); @@ -5399,6 +6094,8 @@ function addCadDisplayEdges(group: THREE.Group, shape: WorkplaneShape, color: st line.position.y -= shape.height / 2; line.renderOrder = 1003; line.userData.complexEdge = true; + line.userData.shapeDecoration = true; + line.userData.cadDisplayEdge = true; group.add(line); }); } @@ -5440,19 +6137,23 @@ function getPreservedImportedMeshGeometry(shape: WorkplaneShape) { } function getEdgesGeometry(shape: WorkplaneShape, geometry: THREE.BufferGeometry, threshold: number) { - if (!shape.importedMesh || preservesEdgeTreatmentSize(shape)) { - return new THREE.EdgesGeometry(geometry, threshold); + const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape) + ? getImportedMeshCache(shape.importedMesh).edges + : null; + let cache = importedCache ?? sharedEdgesGeometryCache.get(geometry); + if (!cache) { + cache = new Map(); + sharedEdgesGeometryCache.set(geometry, cache); } - const cache = getImportedMeshCache(shape.importedMesh); - const cached = cache.edges.get(threshold); + const cached = cache.get(threshold); if (cached) { return cached; } - const edges = new THREE.EdgesGeometry(cache.geometry, threshold); + const edges = new THREE.EdgesGeometry(geometry, threshold); edges.userData.cached = true; - cache.edges.set(threshold, edges); + cache.set(threshold, edges); return edges; } @@ -5464,41 +6165,43 @@ function setComplexEdgeVisibility(object: THREE.Object3D, visible: boolean) { }); } -function addTextShape(group: THREE.Group, material: THREE.MeshStandardMaterial, shape: WorkplaneShape) { - const text = (shape.text ?? "TEXT").trim() || " "; - const bevel = clamp(shape.bevel ?? 0, 0, 8); - const fontName = shape.font ?? "Multilanguage"; - const geometry = new TextGeometry(text, { - font: textFonts[fontName] ?? textFonts.Multilanguage, - size: 20, - depth: shape.height, - curveSegments: fontName === "Stencil" ? 1 : 8, - bevelEnabled: bevel > 0, - bevelThickness: bevel * 0.22, - bevelSize: bevel * 0.16, - bevelSegments: Math.max(1, shape.segments ?? 0), +function addTextShape(group: THREE.Group, material: THREE.MeshStandardMaterial, shape: WorkplaneShape, geometryCacheKey: string) { + const geometry = sharedShapeGeometry(geometryCacheKey, () => { + const text = (shape.text ?? "TEXT").trim() || " "; + const bevel = clamp(shape.bevel ?? 0, 0, 8); + const fontName = shape.font ?? "Multilanguage"; + const next = new TextGeometry(text, { + font: textFonts[fontName] ?? textFonts.Multilanguage, + size: 20, + depth: shape.height, + curveSegments: fontName === "Stencil" ? 1 : 8, + bevelEnabled: bevel > 0, + bevelThickness: bevel * 0.22, + bevelSize: bevel * 0.16, + bevelSegments: Math.max(1, shape.segments ?? 0), + }); + + next.computeBoundingBox(); + const box = next.boundingBox; + if (box) { + const textWidth = Math.max(1, box.max.x - box.min.x); + const textDepth = Math.max(1, box.max.y - box.min.y); + const scale = Math.min(shapeWidth(shape) / textWidth, shapeDepth(shape) / textDepth); + next.scale(scale, scale, 1); + } + + next.rotateX(-Math.PI / 2); + next.computeBoundingBox(); + const rotatedBox = next.boundingBox; + if (rotatedBox) { + next.translate( + -(rotatedBox.min.x + rotatedBox.max.x) / 2, + -rotatedBox.min.y, + -(rotatedBox.min.z + rotatedBox.max.z) / 2, + ); + } + return next; }); - - geometry.computeBoundingBox(); - const box = geometry.boundingBox; - if (box) { - const textWidth = Math.max(1, box.max.x - box.min.x); - const textDepth = Math.max(1, box.max.y - box.min.y); - const scale = Math.min(shapeWidth(shape) / textWidth, shapeDepth(shape) / textDepth); - geometry.scale(scale, scale, 1); - } - - geometry.rotateX(-Math.PI / 2); - geometry.computeBoundingBox(); - const rotatedBox = geometry.boundingBox; - if (rotatedBox) { - geometry.translate( - -(rotatedBox.min.x + rotatedBox.max.x) / 2, - -rotatedBox.min.y, - -(rotatedBox.min.z + rotatedBox.max.z) / 2, - ); - } - addMesh(group, geometry, material, shape); } @@ -5716,19 +6419,19 @@ function disposeObject(object: THREE.Object3D) { object.traverse((child) => { const mesh = child as THREE.Mesh | THREE.LineSegments; if ("geometry" in mesh && mesh.geometry) { + releaseSharedShapeGeometry(mesh); if (!mesh.geometry.userData.cached) { + if ((mesh.geometry as THREE.BufferGeometry & { boundsTree?: unknown }).boundsTree) { + disposeBoundsTree.call(mesh.geometry); + } mesh.geometry.dispose(); } } if ("material" in mesh && mesh.material) { const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; - materials.forEach((material) => { - const map = "map" in material ? (material.map as THREE.Texture | null) : null; - if (map) { - map.dispose(); - } - material.dispose(); - }); + releaseSharedShapeMaterials(mesh); + materials.forEach(disposeMaterialResource); + trimSharedShapeMaterialCache(); } }); } diff --git a/apps/web/src/components/workplane/ShapeInspector.tsx b/apps/web/src/components/workplane/ShapeInspector.tsx index 4e67b14..e471800 100644 --- a/apps/web/src/components/workplane/ShapeInspector.tsx +++ b/apps/web/src/components/workplane/ShapeInspector.tsx @@ -363,8 +363,24 @@ export function ShapeInspector({ const [gearHelixOpen, setGearHelixOpen] = useState(true); const [colorOpen, setColorOpen] = useState(false); const [minimized, setMinimized] = useState(false); + const customColorInputRef = useRef(null); useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]); + useEffect(() => { + const input = customColorInputRef.current; + if (!colorOpen || !input) { + return; + } + + // React's color-input onChange follows the native input event and fires for + // every movement in the picker. Commit only the native change event, which + // fires after the user finishes choosing, so dragging stays responsive. + const commitCustomColor = () => { + onUpdate({ color: input.value, hole: false }); + }; + input.addEventListener("change", commitCustomColor); + return () => input.removeEventListener("change", commitCustomColor); + }, [colorOpen, onUpdate]); useLayoutEffect(() => { inspectorRef.current?.scrollTo({ top: 0, left: 0 }); }, [isSketchRevolve, shape.id]); @@ -446,15 +462,13 @@ export function ShapeInspector({ ))} diff --git a/apps/web/src/components/workplane/TransformOverlay.tsx b/apps/web/src/components/workplane/TransformOverlay.tsx index b73e4e2..272c82e 100644 --- a/apps/web/src/components/workplane/TransformOverlay.tsx +++ b/apps/web/src/components/workplane/TransformOverlay.tsx @@ -33,6 +33,7 @@ export function TransformOverlay({ rotationWheelAxis, pinnedRotationWheelView, onBeginCameraDrag, + onCameraWheel, onBeginTransform, onMoveTransform, onFinishTransform, @@ -67,7 +68,9 @@ export function TransformOverlay({ }; }); const activeAngle = rotationReadout?.angle ?? 0; - const activeRadians = THREE.MathUtils.degToRad(activeAngle - 90); + const activeRadians = rotationReadout?.pointerAngle === undefined + ? THREE.MathUtils.degToRad(activeAngle - 90) + : THREE.MathUtils.degToRad(rotationReadout.pointerAngle); const activeLine = { x: Math.cos(activeRadians) * 92, y: Math.sin(activeRadians) * 92, @@ -79,10 +82,13 @@ export function TransformOverlay({
{ - if (event.button === 2) { + if (event.button === 1 || event.button === 2) { + onHoverMeasure(null); + onPinMeasure(null); onBeginCameraDrag(event); } }} + onWheelCapture={onCameraWheel} onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); @@ -94,7 +100,11 @@ export function TransformOverlay({ aria-hidden="true" viewBox={`0 0 ${box.width} ${box.height}`} preserveAspectRatio="none" - onPointerDown={(event) => onBeginTransform("rotate", `rotate-wheel-${rotationWheelAxis}`, event)} + onPointerDown={(event) => { + if (event.button === 0) { + onBeginTransform("rotate", `rotate-wheel-${rotationWheelAxis}`, event); + } + }} onPointerMove={(event) => onMoveTransform(event.clientX, event.clientY, event.shiftKey, event.altKey)} onPointerUp={onFinishTransform} onPointerCancel={onFinishTransform} @@ -196,9 +206,18 @@ export function TransformOverlay({ className={`transform-handle ${handle.className}`} style={{ "--overlay-x": `${handle.x}px`, "--overlay-y": `${handle.y}px` } as CSSProperties} title={handle.title} - onPointerEnter={() => onHoverMeasure(handle.kind === "lift" ? null : handleMeasureKey(handle))} + onPointerEnter={(event) => { + if ((event.buttons & 4) !== 0) { + onHoverMeasure(null); + return; + } + onHoverMeasure(handle.kind === "lift" ? null : handleMeasureKey(handle)); + }} onPointerLeave={() => onHoverMeasure(null)} onPointerDown={(event) => { + if (event.button !== 0) { + return; + } onPinMeasure(handleMeasureKey(handle)); onBeginTransform(handle.kind, handle.key, event); }} @@ -219,7 +238,11 @@ export function TransformOverlay({ className={`rotate-handle ${handle.className}`} style={{ "--overlay-x": `${handle.x}px`, "--overlay-y": `${handle.y}px`, "--rotate-handle-angle": `${handle.angle}deg` } as CSSProperties} title="Rotate" - onPointerDown={(event) => onBeginTransform("rotate", handle.key, event)} + onPointerDown={(event) => { + if (event.button === 0) { + onBeginTransform("rotate", handle.key, event); + } + }} onPointerMove={(event) => onMoveTransform(event.clientX, event.clientY, event.shiftKey, event.altKey)} onPointerUp={onFinishTransform} onPointerCancel={onFinishTransform} diff --git a/apps/web/src/components/workplane/WorkspaceSettingsModal.tsx b/apps/web/src/components/workplane/WorkspaceSettingsModal.tsx index fcc6391..3ea1ad2 100644 --- a/apps/web/src/components/workplane/WorkspaceSettingsModal.tsx +++ b/apps/web/src/components/workplane/WorkspaceSettingsModal.tsx @@ -1,13 +1,16 @@ "use client"; -import { Grid3X3, Palette, Ruler, X } from "lucide-react"; -import { useEffect, useState } from "react"; +import { ChevronDown, Grid3X3, History, Palette, RotateCcw, Ruler, X } from "lucide-react"; +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { HexColorInput, HexColorPicker } from "react-colorful"; +import { APP_THEME_OPTIONS, type AppThemePreference } from "@/lib/appTheme"; import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits"; import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings"; import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; type WorkspaceSettings = WorkplaneWorkspaceSettings; -type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane"; +type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "history"; const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"]; const MIN_WORKSPACE_SIZE = 60; @@ -23,6 +26,8 @@ const WORKSPACE_SIZE_PRESETS = [ { label: "Custom", width: 200, depth: 200 }, ]; const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const; +const HISTORY_LIMIT_OPTIONS = [30, 50, 100, "unlimited", "custom"] as const; +const HISTORY_CUSTOM_DEFAULT = 250; function clamp(value: number, min: number, max: number) { return Math.min(max, Math.max(min, value)); @@ -35,18 +40,26 @@ function gridBlockSizeForPreset(preset: string, fallback: number) { return clamp(Number.parseFloat(preset) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE); } +function isHistoryLimitPreset(value: unknown): value is 30 | 50 | 100 { + return value === 30 || value === 50 || value === 100; +} + export function WorkspaceSettingsModal({ workspace, snap, + themePreference, onWorkspaceChange, onSnapChange, + onThemePreferenceChange, onMakeDefault, onClose, }: { workspace: WorkspaceSettings; snap: GridSize; + themePreference: AppThemePreference; onWorkspaceChange: (next: WorkspaceSettings) => void; onSnapChange: (next: GridSize) => void; + onThemePreferenceChange?: (preference: AppThemePreference) => void; onMakeDefault: () => void; onClose: () => void; }) { @@ -57,8 +70,20 @@ export function WorkspaceSettingsModal({ depth: workspace.depth.toFixed(workspace.accuracy), })); const [gridBlockSizeDraft, setGridBlockSizeDraft] = useState(() => workspace.gridBlockSize.toFixed(workspace.accuracy)); + const [customHistoryDraft, setCustomHistoryDraft] = useState(() => + typeof workspace.historyLimit === "number" && !isHistoryLimitPreset(workspace.historyLimit) + ? String(workspace.historyLimit) + : String(HISTORY_CUSTOM_DEFAULT), + ); + const historyLimitMode: (typeof HISTORY_LIMIT_OPTIONS)[number] = workspace.historyLimit === "unlimited" || isHistoryLimitPreset(workspace.historyLimit) + ? workspace.historyLimit + : "custom"; + const historyLimitIndex = HISTORY_LIMIT_OPTIONS.indexOf(historyLimitMode); const scaleOptions = scaleOptionsForUnits(workspace.units); const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale); + const gridColor = /^#[0-9a-f]{6}$/i.test(workspace.gridColor) + ? workspace.gridColor + : DEFAULT_WORKPLANE_WORKSPACE.gridColor; useEffect(() => { setDimensionDrafts({ width: workspace.width.toFixed(workspace.accuracy), @@ -68,6 +93,11 @@ export function WorkspaceSettingsModal({ useEffect(() => { setGridBlockSizeDraft(workspace.gridBlockSize.toFixed(workspace.accuracy)); }, [workspace.accuracy, workspace.gridBlockSize]); + useEffect(() => { + if (typeof workspace.historyLimit === "number" && !isHistoryLimitPreset(workspace.historyLimit)) { + setCustomHistoryDraft(String(workspace.historyLimit)); + } + }, [workspace.historyLimit]); const patchWorkspace = (patch: Partial) => { setDefaultSaved(false); const next = { ...workspace, ...patch }; @@ -96,6 +126,20 @@ export function WorkspaceSettingsModal({ setGridBlockSizeDraft(next.toFixed(workspace.accuracy)); patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next }); }; + const setHistoryLimitMode = (mode: (typeof HISTORY_LIMIT_OPTIONS)[number]) => { + if (mode === "custom") { + const parsed = Number.parseInt(customHistoryDraft, 10); + patchWorkspace({ historyLimit: Number.isFinite(parsed) ? clamp(parsed, 1, 5000) : HISTORY_CUSTOM_DEFAULT }); + return; + } + patchWorkspace({ historyLimit: mode }); + }; + const setCustomHistoryLimit = (value: string) => { + const parsed = Number.parseInt(value, 10); + const next = Number.isFinite(parsed) ? Math.round(clamp(parsed, 1, 5000)) : HISTORY_CUSTOM_DEFAULT; + setCustomHistoryDraft(String(next)); + patchWorkspace({ historyLimit: next }); + }; return (
@@ -121,6 +165,10 @@ export function WorkspaceSettingsModal({ Workplane +
@@ -131,8 +179,21 @@ export function WorkspaceSettingsModal({ Appearance Adjust the canvas and navigation behavior.
+ +

Theme applies across SketchForge and all projects.

patchWorkspace({ showShadows })} /> - patchWorkspace({ showGrid })} />
+ patchWorkspace({ gridColor: nextGridColor })} /> {workspace.gridBlockPreset === "Custom" ? (
@@ -279,6 +394,216 @@ export function WorkspaceSettingsModal({ ); } +const GRID_COLOR_PRESETS = [ + DEFAULT_WORKPLANE_WORKSPACE.gridColor, + "#0e69f1", + "#23a66f", + "#e0842f", + "#dc5252", + "#945bd4", + "#718695", +] as const; + +function GridColorControl({ color, onChange }: { color: string; onChange: (color: string) => void }) { + const [open, setOpen] = useState(false); + const [draftColor, setDraftColor] = useState(color); + const draftColorRef = useRef(color); + const pickerCommitAbortRef = useRef(null); + const rootRef = useRef(null); + const triggerRef = useRef(null); + const popoverRef = useRef(null); + + const previewColor = (nextColor: string) => { + draftColorRef.current = nextColor; + setDraftColor(nextColor); + }; + + const commitDraftColor = () => { + onChange(draftColorRef.current); + }; + + const armPickerCommit = (event: React.PointerEvent) => { + if (event.button !== 0) return; + pickerCommitAbortRef.current?.abort(); + const controller = new AbortController(); + pickerCommitAbortRef.current = controller; + const finish = () => { + commitDraftColor(); + controller.abort(); + if (pickerCommitAbortRef.current === controller) { + pickerCommitAbortRef.current = null; + } + }; + window.addEventListener("pointerup", finish, { once: true, signal: controller.signal }); + window.addEventListener("pointercancel", finish, { once: true, signal: controller.signal }); + }; + + useEffect(() => () => pickerCommitAbortRef.current?.abort(), []); + + useEffect(() => { + if (!open) { + previewColor(color); + } + }, [color, open]); + + useEffect(() => { + if (!open) return; + const closeOnOutsidePointer = (event: PointerEvent) => { + const target = event.target as Node; + if (!rootRef.current?.contains(target) && !popoverRef.current?.contains(target)) { + setOpen(false); + } + }; + document.addEventListener("pointerdown", closeOnOutsidePointer); + return () => document.removeEventListener("pointerdown", closeOnOutsidePointer); + }, [open]); + + useLayoutEffect(() => { + if (!open) return; + + const updatePopoverPosition = () => { + const trigger = triggerRef.current; + if (!trigger) return; + const triggerRect = trigger.getBoundingClientRect(); + const viewportPadding = 12; + const gap = 8; + const width = Math.min(286, Math.max(220, window.innerWidth - viewportPadding * 2)); + const measuredHeight = popoverRef.current?.offsetHeight ?? 320; + const roomBelow = window.innerHeight - triggerRect.bottom - viewportPadding; + const roomAbove = triggerRect.top - viewportPadding; + const openAbove = roomBelow < measuredHeight + gap && roomAbove > roomBelow; + const preferredTop = openAbove + ? triggerRect.top - measuredHeight - gap + : triggerRect.bottom + gap; + const top = Math.min( + Math.max(viewportPadding, preferredTop), + Math.max(viewportPadding, window.innerHeight - measuredHeight - viewportPadding), + ); + const left = Math.min( + Math.max(viewportPadding, triggerRect.right - width), + Math.max(viewportPadding, window.innerWidth - width - viewportPadding), + ); + const popover = popoverRef.current; + if (!popover) return; + popover.style.top = `${top}px`; + popover.style.left = `${left}px`; + popover.style.width = `${width}px`; + popover.style.visibility = "visible"; + }; + + updatePopoverPosition(); + window.addEventListener("resize", updatePopoverPosition); + window.addEventListener("scroll", updatePopoverPosition, true); + return () => { + window.removeEventListener("resize", updatePopoverPosition); + window.removeEventListener("scroll", updatePopoverPosition, true); + }; + }, [open]); + + const popover = open && typeof document !== "undefined" + ? createPortal( +
{ + if (event.key === "Escape") { + setOpen(false); + triggerRef.current?.focus(); + } + }} + > +
+ { + previewColor(nextColor); + onChange(nextColor); + }} + /> +
+
+ {GRID_COLOR_PRESETS.map((preset) => ( +
+
+ + +
+
, + document.body, + ) + : null; + + return ( +
+ Grid color +
{ + if (event.key === "Escape") setOpen(false); + }} + > + + {popover} +
+
+ ); +} + function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) { return (