From ee28672e23c936df3ce22dd3f19edab903438d35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enes=20Yak=C4=B1=C5=9Ft=C4=B1r?= Date: Thu, 12 Nov 2026 10:12:35 +0300 Subject: [PATCH] release: SnapCAD Studio 1.0.10 (desktop menuler, macOS kisayollari, YakNet SSO) --- .env.example | 3 + .gitignore | 5 + apps/desktop/build-web.mjs | 19 +- apps/desktop/dev.mjs | 23 +- apps/desktop/electron-builder.yml | 45 +- apps/desktop/main.cjs | 2168 ++++++++++++++++- apps/desktop/preload.cjs | 76 +- apps/web/next.config.ts | 21 + apps/web/public/.htaccess | 6 +- .../assets/sketchforge/sketchforge-logo.ico | Bin 0 -> 77106 bytes apps/web/public/sw.js | 2 +- apps/web/src/app/api/app-update/route.ts | 21 +- apps/web/src/app/globals.css | 116 +- apps/web/src/app/layout.tsx | 7 +- apps/web/src/app/page.tsx | 657 ++++- apps/web/src/components/SketchForgeEditor.tsx | 548 ++++- apps/web/src/components/WorkplaneViewport.tsx | 94 +- .../snapcad/AccessibilityCenter.tsx | 10 +- .../src/components/snapcad/CircuitsStudio.tsx | 6 +- .../components/snapcad/ClassroomsStudio.tsx | 29 +- .../src/components/snapcad/PlatformFooter.tsx | 4 + .../web/src/components/snapcad/PwaManager.tsx | 2 + .../snapcad/TechnicalDrawingStudio.tsx | 394 ++- .../components/snapcad/WebRuntimeChrome.tsx | 27 + .../src/components/snapcad/YakNetCloudBar.tsx | 266 +- apps/web/src/lib/appUpdates.ts | 15 +- apps/web/src/lib/cad2dEngine.ts | 259 +- apps/web/src/lib/cloudApi.ts | 53 + apps/web/src/lib/cloudComponents.ts | 13 +- apps/web/src/lib/desktopBridge.ts | 315 +++ apps/web/src/lib/glbImport.ts | 39 +- apps/web/src/lib/ifcImport.ts | 322 +++ apps/web/src/lib/importExtensions.ts | 2 +- apps/web/src/lib/meshSanitizer.ts | 369 +++ apps/web/src/lib/objImport.ts | 30 +- apps/web/src/lib/offsetKernel.ts | 685 +++++- apps/web/src/lib/planegcsSolver.ts | 454 ++++ apps/web/src/lib/projectAssets.ts | 3 +- apps/web/src/lib/projection/EdgeGenerator.ts | 217 ++ .../projection/PlanarIntersectionGenerator.ts | 72 + .../src/lib/projection/ProjectionGenerator.ts | 315 +++ apps/web/src/lib/projection/index.ts | 5 + .../lib/projection/utils/LineObjectsBVH.ts | 48 + .../lib/projection/utils/ProjectionEdge.ts | 16 + .../src/lib/projection/utils/bvhcastEdges.ts | 100 + .../src/lib/projection/utils/generateEdges.ts | 168 ++ .../utils/generateIntersectionEdges.ts | 73 + .../src/lib/projection/utils/getAllMeshes.ts | 17 + .../utils/getProjectedLineOverlap.ts | 111 + .../projection/utils/getProjectedOverlaps.ts | 78 + .../web/src/lib/projection/utils/nextFrame.ts | 19 + .../src/lib/projection/utils/overlapUtils.ts | 51 + .../lib/projection/utils/triangleLineUtils.ts | 57 + .../projection/utils/trimToBeneathTriPlane.ts | 67 + apps/web/src/lib/serviceWorker.ts | 2 +- apps/web/src/lib/skfProject.ts | 6 +- apps/web/src/lib/stlImport.ts | 13 +- apps/web/src/lib/technicalProjectionBridge.ts | 1272 ++++++++++ apps/web/src/types/desktop.d.ts | 281 ++- apps/web/src/types/sketchforge.ts | 2 +- callback.php | 67 +- cloud-api.php | 47 +- database/schema.php | 21 + login.php | 21 + package-lock.json | 114 +- package.json | 13 +- scripts/copy-ifc-wasm.mjs | 21 + scripts/copy-planegcs-wasm.mjs | 25 + scripts/publish-desktop-updates.mjs | 55 + scripts/run-cad-audit.mjs | 24 +- scripts/sync-laragon-static.mjs | 1 + snap-config.php | 302 +++ tests/unit/cad2dEngine.test.ts | 2 +- tests/unit/cloudApi.test.ts | 121 + tests/unit/desktopBridge.test.ts | 200 ++ tests/unit/ifcImport.test.ts | 59 + tests/unit/keyboardMovement.test.ts | 19 + tests/unit/meshSanitizer.test.ts | 89 + tests/unit/offsetKernel.test.ts | 23 + tests/unit/planegcsSolver.test.ts | 90 + tests/unit/technicalProjection.test.ts | 138 ++ 81 files changed, 10729 insertions(+), 821 deletions(-) create mode 100644 apps/web/public/assets/sketchforge/sketchforge-logo.ico create mode 100644 apps/web/src/components/snapcad/WebRuntimeChrome.tsx create mode 100644 apps/web/src/lib/cloudApi.ts create mode 100644 apps/web/src/lib/desktopBridge.ts create mode 100644 apps/web/src/lib/ifcImport.ts create mode 100644 apps/web/src/lib/meshSanitizer.ts create mode 100644 apps/web/src/lib/planegcsSolver.ts create mode 100644 apps/web/src/lib/projection/EdgeGenerator.ts create mode 100644 apps/web/src/lib/projection/PlanarIntersectionGenerator.ts create mode 100644 apps/web/src/lib/projection/ProjectionGenerator.ts create mode 100644 apps/web/src/lib/projection/index.ts create mode 100644 apps/web/src/lib/projection/utils/LineObjectsBVH.ts create mode 100644 apps/web/src/lib/projection/utils/ProjectionEdge.ts create mode 100644 apps/web/src/lib/projection/utils/bvhcastEdges.ts create mode 100644 apps/web/src/lib/projection/utils/generateEdges.ts create mode 100644 apps/web/src/lib/projection/utils/generateIntersectionEdges.ts create mode 100644 apps/web/src/lib/projection/utils/getAllMeshes.ts create mode 100644 apps/web/src/lib/projection/utils/getProjectedLineOverlap.ts create mode 100644 apps/web/src/lib/projection/utils/getProjectedOverlaps.ts create mode 100644 apps/web/src/lib/projection/utils/nextFrame.ts create mode 100644 apps/web/src/lib/projection/utils/overlapUtils.ts create mode 100644 apps/web/src/lib/projection/utils/triangleLineUtils.ts create mode 100644 apps/web/src/lib/projection/utils/trimToBeneathTriPlane.ts create mode 100644 apps/web/src/lib/technicalProjectionBridge.ts create mode 100644 scripts/copy-ifc-wasm.mjs create mode 100644 scripts/copy-planegcs-wasm.mjs create mode 100644 scripts/publish-desktop-updates.mjs create mode 100644 tests/unit/cloudApi.test.ts create mode 100644 tests/unit/desktopBridge.test.ts create mode 100644 tests/unit/ifcImport.test.ts create mode 100644 tests/unit/meshSanitizer.test.ts create mode 100644 tests/unit/planegcsSolver.test.ts create mode 100644 tests/unit/technicalProjection.test.ts diff --git a/.env.example b/.env.example index 0c7dbf8..1c16196 100644 --- a/.env.example +++ b/.env.example @@ -34,3 +34,6 @@ SNAPCAD_MAX_STORAGE_BYTES_PER_USER='104857600' # Client-supplied SSO payloads are never trusted. Use OAuth callback or a verified token. SNAPCAD_ENABLE_CLIENT_SSO_SYNC='false' + +# Masaüstü uygulaması (SnapCAD.exe) oturum token geçerlilik süresi (gün). Aktif kullanımda otomatik uzar. +SNAPCAD_DESKTOP_TOKEN_TTL_DAYS='180' diff --git a/.gitignore b/.gitignore index 32a336e..d5b84d7 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ node_modules/ out/ build/ dist/ +/updates/ # Environment files .env @@ -53,6 +54,8 @@ apps/web/public/occt/ apps/web/public/dwgdxf/ apps/web/public/libredwg/ apps/web/public/libredwg-web/ +apps/web/public/ifc/ +apps/web/public/planegcs/ # PHP dependencies (install with composer install) /vendor/ @@ -66,6 +69,7 @@ apps/web/public/libredwg-web/ /guvenlik/ /hakkimizda/ /icons/ +/ifc/ /iletisim/ /kullanim-kosullari/ /kurumsal-guvenlik/ @@ -73,6 +77,7 @@ apps/web/public/libredwg-web/ /libredwg/ /libredwg-web/ /occt/ +/planegcs/ /index.html /index.txt /404.html diff --git a/apps/desktop/build-web.mjs b/apps/desktop/build-web.mjs index 5bba9ff..1abf92a 100644 --- a/apps/desktop/build-web.mjs +++ b/apps/desktop/build-web.mjs @@ -6,7 +6,12 @@ import { fileURLToPath } from "node:url"; const desktopDir = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(desktopDir, "..", ".."); const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next"); -const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"); +const wasmCopyScripts = [ + path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-dwg-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-ifc-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-planegcs-wasm.mjs"), +]; function runNode(args, env = process.env) { const result = spawnSync(process.execPath, args, { @@ -25,7 +30,9 @@ function runNode(args, env = process.env) { } } -runNode([copyOcctScript]); +for (const scriptPath of wasmCopyScripts) { + runNode([scriptPath]); +} runNode([nextBin, "build", "apps/web"], { ...process.env, SKETCHFORGE_DOCKER_BUILD: "true", @@ -34,6 +41,7 @@ runNode([nextBin, "build", "apps/web"], { const requiredPaths = [ path.join(repoRoot, "apps", "web", ".next", "standalone", "apps", "web", "server.js"), + path.join(repoRoot, "apps", "web", ".next", "standalone", "node_modules"), path.join(repoRoot, "apps", "web", ".next", "static"), path.join(repoRoot, "apps", "web", "public"), ]; @@ -45,4 +53,9 @@ for (const requiredPath of requiredPaths) { } } -console.log("[desktop:web:build] Standalone SketchForge web bundle is ready."); +const standaloneModulesSrc = path.join(repoRoot, "apps", "web", ".next", "standalone", "node_modules"); +const stagedRuntimeModules = path.join(repoRoot, "apps", "web", ".next", "desktop-runtime_modules"); +fs.rmSync(stagedRuntimeModules, { recursive: true, force: true }); +fs.cpSync(standaloneModulesSrc, stagedRuntimeModules, { recursive: true, dereference: true }); + +console.log("[desktop:web:build] Standalone SnapCAD web bundle is ready."); diff --git a/apps/desktop/dev.mjs b/apps/desktop/dev.mjs index 51be8b5..2910599 100644 --- a/apps/desktop/dev.mjs +++ b/apps/desktop/dev.mjs @@ -7,7 +7,12 @@ import electronPath from "electron"; const desktopDir = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(desktopDir, "..", ".."); const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next"); -const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"); +const wasmCopyScripts = [ + path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-dwg-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-ifc-wasm.mjs"), + path.join(repoRoot, "scripts", "copy-planegcs-wasm.mjs"), +]; const electronMain = path.join(desktopDir, "main.cjs"); function findFreePort() { @@ -50,14 +55,16 @@ async function waitForUrl(url, child, timeoutMs = 45_000) { throw new Error(`Timed out waiting for SketchForge dev server.${detail}`); } -const copyResult = spawnSync(process.execPath, [copyOcctScript], { - cwd: repoRoot, - stdio: "inherit", - env: process.env, -}); +for (const scriptPath of wasmCopyScripts) { + const copyResult = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + stdio: "inherit", + env: process.env, + }); -if (copyResult.status !== 0) { - process.exit(copyResult.status ?? 1); + if (copyResult.status !== 0) { + process.exit(copyResult.status ?? 1); + } } const port = await findFreePort(); diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml index 458f9b9..651b36f 100644 --- a/apps/desktop/electron-builder.yml +++ b/apps/desktop/electron-builder.yml @@ -1,36 +1,61 @@ -appId: com.sketchforge.desktop -productName: SketchForge +appId: com.snapcad.desktop +productName: SnapCAD Studio +executableName: SnapCAD asar: true +npmRebuild: false directories: output: dist/desktop publish: - provider: github - owner: Formsmith746 - repo: SketchForge-3D - releaseType: release + provider: generic + url: https://snap.yakhub.com.tr/updates + +fileAssociations: + - ext: skf + name: SnapCAD Project + description: SnapCAD Studio 3D Parametric CAD Project + role: Editor files: - apps/desktop/main.cjs - apps/desktop/preload.cjs - package.json + - "!node_modules/**/*" + - "node_modules/electron-updater/**/*" + - "node_modules/builder-util-runtime/**/*" + - "node_modules/fs-extra/**/*" + - "node_modules/graceful-fs/**/*" + - "node_modules/jsonfile/**/*" + - "node_modules/universalify/**/*" + - "node_modules/js-yaml/**/*" + - "node_modules/argparse/**/*" + - "node_modules/debug/**/*" + - "node_modules/ms/**/*" + - "node_modules/lazy-val/**/*" + - "node_modules/lodash.escaperegexp/**/*" + - "node_modules/lodash.isequal/**/*" + - "node_modules/sax/**/*" + - "node_modules/semver/**/*" + - "node_modules/tiny-typed-emitter/**/*" extraResources: - from: apps/web/.next/standalone to: web + - from: apps/web/.next/desktop-runtime_modules + to: web/runtime_modules - from: apps/web/.next/static to: web/apps/web/.next/static - from: apps/web/public to: web/apps/web/public win: - icon: apps/web/public/assets/sketchforge/sketchforge-logo.png + icon: apps/web/public/assets/sketchforge/sketchforge-logo.ico target: - target: nsis arch: - x64 - artifactName: ${productName}-Setup-${version}-${arch}.${ext} + artifactName: SnapCAD-Setup-${version}-${arch}.${ext} nsis: oneClick: false @@ -44,7 +69,7 @@ mac: - dmg - zip category: public.app-category.graphics-design - artifactName: ${productName}-${version}-${arch}.${ext} + artifactName: SnapCAD-${version}-${arch}.${ext} linux: syncDesktopName: true @@ -52,4 +77,4 @@ linux: target: - AppImage category: Graphics - artifactName: ${productName}-${version}-${arch}.${ext} + artifactName: SnapCAD-${version}-${arch}.${ext} diff --git a/apps/desktop/main.cjs b/apps/desktop/main.cjs index 0398107..be597f0 100644 --- a/apps/desktop/main.cjs +++ b/apps/desktop/main.cjs @@ -1,20 +1,47 @@ -const { app, BrowserWindow, Menu, Tray, dialog, ipcMain, nativeImage, shell } = require("electron"); +const { app, BrowserWindow, Menu, Tray, dialog, ipcMain, nativeImage, safeStorage, screen, shell } = require("electron"); const { autoUpdater } = require("electron-updater"); const { spawn } = require("node:child_process"); +const crypto = require("node:crypto"); const fs = require("node:fs"); +const http = require("node:http"); +const os = require("node:os"); const path = require("node:path"); +const APP_DISPLAY_NAME = "SnapCAD Studio"; +const DESKTOP_APP_ID = "com.snapcad.desktop"; +const MAX_SKF_FILE_BYTES = 256 * 1024 * 1024; const devUrl = process.env.SKETCHFORGE_DESKTOP_DEV_URL?.trim() || ""; // Keep the desktop origin stable. localStorage and IndexedDB are scoped to the // full origin (including the port), so a random port made projects appear to // vanish after every restart. const DESKTOP_PORT = Number.parseInt(process.env.SKETCHFORGE_DESKTOP_PORT || "62158", 10); +function resolveSafeHttpUrl(rawUrl, fallbackUrl) { + const candidate = String(rawUrl || "").trim(); + if (!candidate) return fallbackUrl; + try { + const parsed = new URL(candidate); + if (parsed.protocol === "https:" || parsed.protocol === "http:") { + return parsed.toString().replace(/\/+$/, ""); + } + } catch { + // Ignore invalid URL overrides. + } + return fallbackUrl; +} + +const CLOUD_ORIGIN = resolveSafeHttpUrl(process.env.SNAPCAD_CLOUD_ORIGIN, "https://snap.yakhub.com.tr"); +const UPDATE_FEED_URL = resolveSafeHttpUrl(process.env.SNAPCAD_UPDATE_FEED_URL, `${CLOUD_ORIGIN}/updates`); + let mainWindow = null; let tray = null; let webServer = null; let webServerOutput = ""; let isQuitting = false; +let explicitQuit = false; +let isDocumentDirty = false; +let closePromptOpen = false; +let trayBalloonShown = false; let updaterConfigured = false; let desktopIpcConfigured = false; let updateCheckInFlight = false; @@ -23,6 +50,462 @@ let downloadedUpdateReady = false; let updateInstallRequested = false; let lastUpdateCheckResult = null; let lastUpdateCheckError = ""; +let pendingOpenFilePath = null; +let windowStateSaveTimer = null; +let desktopPrefs = { closeToTray: true }; +let desktopAuthSession = null; +const desktopCloudCookies = new Map(); +let pendingOAuthServer = null; +let pendingOAuthTimeout = null; +let desktopMenuBuilt = false; +const VALID_VISUAL_STYLES = new Set([ + "shaded", + "wireframe", + "hidden-line", + "monochrome", + "blueprint", + "cyberpunk", + "clay", +]); +let menuUiState = { + inEditor: false, + visualStyle: "shaded", + xRayMode: false, + isOrthographic: false, + showLeftToolset: true, + showDefaultTray: true, + showSecondaryRibbon: false, + skyGroundEnabled: false, + backEdgesEnabled: false, + keymapProfile: "classic-sketchup", +}; +let updateState = { + currentVersion: app.getVersion(), + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: new Date().toISOString(), + status: app.isPackaged ? "idle" : "unsupported", + progressPercent: 0, + bytesPerSecond: 0, + transferred: 0, + total: 0, + feedUrl: UPDATE_FEED_URL, + error: undefined, +}; + +// Only file paths returned by native OS dialogs or OS file-association argv +// can be overwritten silently by Ctrl+S without showing Save As. +const trustedDialogPaths = new Set(); + +function escapeHtml(raw) { + return String(raw ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function windowStatePath() { + return path.join(app.getPath("userData"), "snapcad-window-state.json"); +} + +function desktopPrefsPath() { + return path.join(app.getPath("userData"), "snapcad-desktop-prefs.json"); +} + +function cloudAuthPath() { + return path.join(app.getPath("userData"), "snapcad-cloud-auth.json"); +} + +function loadDesktopPrefs() { + try { + const raw = JSON.parse(fs.readFileSync(desktopPrefsPath(), "utf8")); + desktopPrefs = { + closeToTray: typeof raw?.closeToTray === "boolean" ? raw.closeToTray : true, + }; + } catch { + desktopPrefs = { closeToTray: true }; + } + return { ...desktopPrefs }; +} + +function saveDesktopPrefs(patch = {}) { + const prevCloseToTray = desktopPrefs.closeToTray; + const next = { + closeToTray: typeof patch.closeToTray === "boolean" ? patch.closeToTray : desktopPrefs.closeToTray, + }; + desktopPrefs = next; + try { + fs.mkdirSync(path.dirname(desktopPrefsPath()), { recursive: true }); + fs.writeFileSync(desktopPrefsPath(), JSON.stringify(next, null, 2), "utf8"); + } catch { + // Best-effort preference persistence. + } + updateTrayMenu(); + if (desktopMenuBuilt && next.closeToTray !== prevCloseToTray) { + buildNativeApplicationMenu(); + } + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send("snapcad:prefs-changed", { ...desktopPrefs }); + } + return { ...desktopPrefs }; +} + +function updateMenuUiState(patch = {}) { + if (!patch || typeof patch !== "object") return { ...menuUiState }; + const next = { + inEditor: typeof patch.inEditor === "boolean" ? patch.inEditor : menuUiState.inEditor, + visualStyle: + typeof patch.visualStyle === "string" && VALID_VISUAL_STYLES.has(patch.visualStyle) + ? patch.visualStyle + : menuUiState.visualStyle, + xRayMode: typeof patch.xRayMode === "boolean" ? patch.xRayMode : menuUiState.xRayMode, + isOrthographic: typeof patch.isOrthographic === "boolean" ? patch.isOrthographic : menuUiState.isOrthographic, + showLeftToolset: typeof patch.showLeftToolset === "boolean" ? patch.showLeftToolset : menuUiState.showLeftToolset, + showDefaultTray: typeof patch.showDefaultTray === "boolean" ? patch.showDefaultTray : menuUiState.showDefaultTray, + showSecondaryRibbon: + typeof patch.showSecondaryRibbon === "boolean" ? patch.showSecondaryRibbon : menuUiState.showSecondaryRibbon, + skyGroundEnabled: + typeof patch.skyGroundEnabled === "boolean" ? patch.skyGroundEnabled : menuUiState.skyGroundEnabled, + backEdgesEnabled: + typeof patch.backEdgesEnabled === "boolean" ? patch.backEdgesEnabled : menuUiState.backEdgesEnabled, + keymapProfile: + patch.keymapProfile === "snapcad-standard" || patch.keymapProfile === "classic-sketchup" + ? patch.keymapProfile + : menuUiState.keymapProfile, + }; + const changed = Object.keys(next).some((key) => next[key] !== menuUiState[key]); + menuUiState = next; + if (changed && desktopMenuBuilt) { + buildNativeApplicationMenu(); + } + return { ...menuUiState }; +} + +function clearDesktopAuthSession() { + const hadSession = Boolean(desktopAuthSession); + desktopAuthSession = null; + try { + if (fs.existsSync(cloudAuthPath())) { + fs.unlinkSync(cloudAuthPath()); + } + } catch { + // Ignore file delete errors during logout cleanup. + } + if (hadSession && desktopMenuBuilt) { + buildNativeApplicationMenu(); + } +} + +function saveDesktopAuthSession(session) { + if (!session || typeof session.token !== "string" || !/^[a-f0-9]{64}$/i.test(session.token)) { + return false; + } + const cleanUser = session.user && typeof session.user === "object" + ? { + id: Number(session.user.id || 0), + name: String(session.user.name || "YakNet Kullanıcısı").slice(0, 255), + email: String(session.user.email || "").slice(0, 255), + avatar: typeof session.user.avatar === "string" ? session.user.avatar.slice(0, 512) : null, + auth_source: "yaknet_desktop_token", + token_expires_at: typeof session.expiresAt === "string" ? session.expiresAt : undefined, + } + : null; + if (!cleanUser || cleanUser.id <= 0) return false; + + const cleanToken = session.token.toLowerCase(); + desktopAuthSession = { + token: cleanToken, + user: cleanUser, + expiresAt: typeof session.expiresAt === "string" ? session.expiresAt : null, + }; + + try { + if (!safeStorage.isEncryptionAvailable()) { + // Do not store plaintext long-lived credentials if OS encryption is unavailable. + if (desktopMenuBuilt) buildNativeApplicationMenu(); + return true; + } + const encrypted = safeStorage.encryptString(cleanToken).toString("base64"); + fs.mkdirSync(path.dirname(cloudAuthPath()), { recursive: true }); + fs.writeFileSync( + cloudAuthPath(), + JSON.stringify({ + encrypted: true, + token: encrypted, + user: cleanUser, + expiresAt: desktopAuthSession.expiresAt, + savedAt: new Date().toISOString(), + }), + "utf8", + ); + } catch { + // Keep session in memory even if disk encryption write fails. + } + if (desktopMenuBuilt) { + buildNativeApplicationMenu(); + } + return true; +} + +function loadDesktopAuthSession() { + try { + if (!fs.existsSync(cloudAuthPath())) { + desktopAuthSession = null; + return null; + } + const raw = JSON.parse(fs.readFileSync(cloudAuthPath(), "utf8")); + if (!raw || raw.encrypted !== true || typeof raw.token !== "string" || !safeStorage.isEncryptionAvailable()) { + desktopAuthSession = null; + return null; + } + if (typeof raw.expiresAt === "string") { + const expiresMs = Date.parse(raw.expiresAt); + if (Number.isFinite(expiresMs) && expiresMs <= Date.now()) { + clearDesktopAuthSession(); + return null; + } + } + const decrypted = safeStorage.decryptString(Buffer.from(raw.token, "base64")).trim().toLowerCase(); + if (!/^[a-f0-9]{64}$/.test(decrypted) || !raw.user || Number(raw.user.id || 0) <= 0) { + clearDesktopAuthSession(); + return null; + } + desktopAuthSession = { + token: decrypted, + user: raw.user, + expiresAt: typeof raw.expiresAt === "string" ? raw.expiresAt : null, + }; + return desktopAuthSession; + } catch { + clearDesktopAuthSession(); + return null; + } +} + +function emitAuthUpdated(payload) { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send("snapcad:auth-updated", payload); + } +} + +function normalizeCloudApiPath(rawPath) { + if (typeof rawPath !== "string") return null; + const trimmed = rawPath.trim(); + if (!trimmed || trimmed.length > 4096) return null; + if (trimmed === "/cloud-api.php" || trimmed.startsWith("/cloud-api.php?")) { + return trimmed; + } + return null; +} + +function formatFriendlyUpdateError(rawError) { + const message = rawError instanceof Error ? rawError.message : String(rawError || ""); + const clean = message.trim(); + if (!clean) return "Güncelleme denetlenemedi."; + const lower = clean.toLowerCase(); + if (lower.includes("404") || lower.includes("latest.yml") || lower.includes("cannot find")) { + return "Güncelleme sunucusunda henüz yeni bir masaüstü kurulum paketi yayınlanmadı."; + } + if ( + lower.includes("err_network") || + lower.includes("enotfound") || + lower.includes("econnrefused") || + lower.includes("etimedout") || + lower.includes("fetch failed") + ) { + return "Güncelleme sunucusuna bağlanılamadı. İnternet bağlantınızı kontrol edin."; + } + return clean; +} + +function clampWindowBoundsToDisplays(rawState) { + const fallback = { width: 1500, height: 960, isMaximized: false }; + if (!rawState || typeof rawState !== "object") return fallback; + + const width = Math.max(1100, Math.min(Number(rawState.width) || 1500, 7680)); + const height = Math.max(700, Math.min(Number(rawState.height) || 960, 4320)); + const isMaximized = Boolean(rawState.isMaximized); + + if (typeof rawState.x !== "number" || typeof rawState.y !== "number" || !Number.isFinite(rawState.x) || !Number.isFinite(rawState.y)) { + return { width, height, isMaximized }; + } + + const candidate = { x: Math.round(rawState.x), y: Math.round(rawState.y), width: Math.round(width), height: Math.round(height) }; + try { + const displays = screen.getAllDisplays(); + const visible = displays.some((display) => { + const area = display.workArea; + const overlapX = Math.max(0, Math.min(candidate.x + candidate.width, area.x + area.width) - Math.max(candidate.x, area.x)); + const overlapY = Math.max(0, Math.min(candidate.y + candidate.height, area.y + area.height) - Math.max(candidate.y, area.y)); + return overlapX >= 120 && overlapY >= 80; + }); + if (visible) { + return { ...candidate, isMaximized }; + } + } catch { + // Ignore screen enumeration errors and fall back to centered bounds. + } + + return { width: candidate.width, height: candidate.height, isMaximized }; +} + +function loadSavedWindowState() { + try { + const raw = fs.readFileSync(windowStatePath(), "utf8"); + return clampWindowBoundsToDisplays(JSON.parse(raw)); + } catch { + return clampWindowBoundsToDisplays(null); + } +} + +function saveWindowStateImmediate() { + if (!mainWindow || mainWindow.isDestroyed()) return; + try { + const isMaximized = mainWindow.isMaximized(); + const bounds = isMaximized ? mainWindow.getNormalBounds() : mainWindow.getBounds(); + fs.mkdirSync(path.dirname(windowStatePath()), { recursive: true }); + fs.writeFileSync( + windowStatePath(), + JSON.stringify({ + x: bounds.x, + y: bounds.y, + width: bounds.width, + height: bounds.height, + isMaximized, + }), + "utf8", + ); + } catch { + // Window state persistence is best-effort. + } +} + +function scheduleWindowStateSave() { + if (windowStateSaveTimer) clearTimeout(windowStateSaveTimer); + windowStateSaveTimer = setTimeout(() => { + windowStateSaveTimer = null; + saveWindowStateImmediate(); + }, 280); +} + +function extractSkfFilePathFromArgv(argv) { + if (!Array.isArray(argv)) return null; + for (let i = 1; i < argv.length; i += 1) { + const raw = String(argv[i] || "").trim(); + if (!raw || raw.startsWith("-")) continue; + const cleaned = raw.replace(/^["']|["']$/g, ""); + if (!cleaned.toLowerCase().endsWith(".skf")) continue; + try { + const resolved = path.resolve(cleaned); + const stat = fs.statSync(resolved); + if (stat.isFile() && stat.size <= MAX_SKF_FILE_BYTES) { + return resolved; + } + } catch { + // Ignore invalid or inaccessible argv paths. + } + } + return null; +} + +function readTrustedSkfFile(filePath) { + const resolved = path.resolve(filePath); + const stat = fs.statSync(resolved); + if (!stat.isFile()) { + throw new Error("Secilen oge gecerli bir .skf dosyasi degil."); + } + if (stat.size > MAX_SKF_FILE_BYTES) { + throw new Error("Proje dosyasi 256 MB masaustu sinirini asiyor."); + } + const buffer = fs.readFileSync(resolved); + trustedDialogPaths.add(resolved); + return { + filePath: resolved, + fileName: path.basename(resolved), + bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), + }; +} + +function writeFileAtomic(targetPath, bytes) { + const resolved = path.resolve(targetPath); + if (!(bytes instanceof Uint8Array)) { + throw new Error("Kaydedilecek ikili veri gecersiz."); + } + if (bytes.byteLength > MAX_SKF_FILE_BYTES) { + throw new Error("Dosya boyutu 256 MB sinirini asiyor."); + } + fs.mkdirSync(path.dirname(resolved), { recursive: true }); + const tempPath = `${resolved}.tmp-${process.pid}-${Date.now()}`; + let fd = null; + try { + fd = fs.openSync(tempPath, "w", 0o666); + fs.writeSync(fd, bytes, 0, bytes.byteLength, 0); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = null; + fs.renameSync(tempPath, resolved); + } catch (error) { + if (fd !== null) { + try { + fs.closeSync(fd); + } catch { + // Ignore close error on cleanup path. + } + } + try { + if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); + } catch { + // Ignore unlink error on cleanup path. + } + throw error; + } + trustedDialogPaths.add(resolved); + return resolved; +} + +function sanitizeWindowTitleInput(title) { + const cleaned = String(title || "") + .replace(/[\r\n\t\u0000-\u001f\u007f]+/g, " ") + .replace(/\s+/g, " ") + .trim() + .slice(0, 140); + return cleaned || APP_DISPLAY_NAME; +} + +function isAllowedExternalUrl(rawUrl) { + try { + const parsed = new URL(String(rawUrl || "")); + return parsed.protocol === "https:" || parsed.protocol === "http:"; + } catch { + return false; + } +} + +function sendMenuCommand(action) { + if (!mainWindow || mainWindow.isDestroyed()) return; + showMainWindow(); + mainWindow.webContents.send("snapcad:menu-command", action); +} + +function deliverOrQueueSkfOpen(filePath) { + if (!filePath) return; + try { + const resolved = path.resolve(filePath); + trustedDialogPaths.add(resolved); + if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isLoadingMainFrame()) { + const payload = readTrustedSkfFile(resolved); + showMainWindow(); + mainWindow.webContents.send("snapcad:open-file", payload); + return; + } + pendingOpenFilePath = resolved; + } catch { + // Ignore unreadable OS open-file payloads. + } +} function appendServerOutput(chunk) { webServerOutput += String(chunk); @@ -37,7 +520,7 @@ async function waitForServer(url, timeoutMs = 30_000) { while (Date.now() < deadline) { if (webServer && webServer.exitCode !== null) { - throw new Error(`SketchForge web process exited with code ${webServer.exitCode}.`); + throw new Error(`SnapCAD yerel sunucu sureci kod ${webServer.exitCode} ile kapandi.`); } try { @@ -51,17 +534,18 @@ async function waitForServer(url, timeoutMs = 30_000) { } const detail = lastError instanceof Error ? ` ${lastError.message}` : ""; - throw new Error(`SketchForge did not start its local web process in time.${detail}`); + throw new Error(`SnapCAD yerel web motoru zamaninda baslatilamadi.${detail}`); } async function startPackagedWebServer() { const webRoot = path.join(process.resourcesPath, "web"); const serverPath = path.join(webRoot, "apps", "web", "server.js"); if (!fs.existsSync(serverPath)) { - throw new Error(`Desktop web bundle is missing: ${serverPath}`); + throw new Error(`Masaustu uygulama paketi eksik: ${serverPath}`); } const port = DESKTOP_PORT; + const runtimeNodeModules = path.join(webRoot, "runtime_modules"); const packagedNodeModules = path.join(process.resourcesPath, "app.asar", "node_modules"); webServer = spawn(process.execPath, [serverPath], { @@ -71,7 +555,7 @@ async function startPackagedWebServer() { env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", - NODE_PATH: [packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter), + NODE_PATH: [runtimeNodeModules, packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter), HOSTNAME: "127.0.0.1", PORT: String(port), SKETCHFORGE_DESKTOP: "1", @@ -98,10 +582,29 @@ function stopPackagedWebServer() { } } -function appIconPath() { +function assetsDirPath() { return devUrl - ? path.join(__dirname, "..", "web", "public", "assets", "sketchforge", "sketchforge-logo.png") - : path.join(process.resourcesPath, "web", "apps", "web", "public", "assets", "sketchforge", "sketchforge-logo.png"); + ? path.join(__dirname, "..", "web", "public", "assets", "sketchforge") + : path.join(process.resourcesPath, "web", "apps", "web", "public", "assets", "sketchforge"); +} + +function appIconPath() { + const dir = assetsDirPath(); + if (process.platform === "win32") { + const ico = path.join(dir, "sketchforge-logo.ico"); + if (fs.existsSync(ico)) return ico; + } + return path.join(dir, "sketchforge-logo.png"); +} + +function createTrayImage() { + const iconPath = appIconPath(); + const loaded = nativeImage.createFromPath(iconPath); + if (iconPath.toLowerCase().endsWith(".ico") && !loaded.isEmpty()) { + return loaded; + } + const pngFallback = path.join(assetsDirPath(), "sketchforge-logo.png"); + return nativeImage.createFromPath(pngFallback).resize({ width: 20, height: 20, quality: "best" }); } function showMainWindow() { @@ -109,65 +612,172 @@ function showMainWindow() { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.show(); mainWindow.focus(); + updateTrayMenu(); +} + +function hideToTrayWindow({ showBalloonOnce = false } = {}) { + if (!mainWindow || mainWindow.isDestroyed()) return; + saveWindowStateImmediate(); + mainWindow.hide(); + updateTrayMenu(); + if (showBalloonOnce && !trayBalloonShown && tray && process.platform === "win32" && typeof tray.displayBalloon === "function") { + trayBalloonShown = true; + try { + tray.displayBalloon({ + icon: appIconPath(), + title: `${APP_DISPLAY_NAME} Arka Planda Çalışıyor`, + content: "Pencere sistem tepsisine (gizli simgeler) küçültüldü. Geri açmak için simgeye tıklayın; tamamen kapatmak için sağ tıklayıp Çıkış'ı seçin.", + noSound: true, + }); + } catch { + // Tray balloon is optional cosmetic feedback on Windows. + } + } +} + +function setUpdateState(patch = {}) { + updateState = { + ...updateState, + ...patch, + currentVersion: app.getVersion(), + feedUrl: UPDATE_FEED_URL, + }; + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send("snapcad:update-state", { ...updateState }); + } + return { ...updateState }; +} + +function desktopUpdatePayload(result = lastUpdateCheckResult, errorMessage = lastUpdateCheckError, overrides = {}) { + return { + currentVersion: app.getVersion(), + latestVersion: result?.updateInfo?.version || updateState.latestVersion || null, + updateAvailable: Boolean(result?.isUpdateAvailable ?? updateState.updateAvailable), + downloaded: downloadedUpdateReady, + checkedAt: updateState.checkedAt || new Date().toISOString(), + status: updateState.status, + progressPercent: updateState.progressPercent, + bytesPerSecond: updateState.bytesPerSecond, + transferred: updateState.transferred, + total: updateState.total, + feedUrl: UPDATE_FEED_URL, + error: errorMessage || undefined, + ...overrides, + }; } function installDownloadedUpdate() { if (!downloadedUpdateReady) return; + explicitQuit = true; isQuitting = true; stopPackagedWebServer(); + if (tray) { + try { + tray.destroy(); + } catch { + // Ignore tray teardown errors during update restart. + } + tray = null; + } setImmediate(() => autoUpdater.quitAndInstall(false, true)); } async function downloadAndInstallDesktopUpdate() { if (!app.isPackaged) { - return desktopUpdatePayload(null, "Updates can only be installed from the packaged SketchForge app."); + return desktopUpdatePayload( + null, + "Güncellemeler yalnızca kurulu SnapCAD Studio (.exe) uygulamasında indirilebilir.", + { status: "unsupported" }, + ); + } + + if (downloadedUpdateReady) { + installDownloadedUpdate(); + return desktopUpdatePayload(lastUpdateCheckResult, "", { status: "downloaded", progressPercent: 100 }); } lastUpdateCheckError = ""; try { let result = lastUpdateCheckResult; if (!result?.isUpdateAvailable) { + setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined }); result = await autoUpdater.checkForUpdates(); lastUpdateCheckResult = result; } if (!result?.isUpdateAvailable) { + setUpdateState({ + status: "not-available", + latestVersion: result?.updateInfo?.version || null, + updateAvailable: false, + downloaded: false, + checkedAt: new Date().toISOString(), + error: undefined, + }); return desktopUpdatePayload(result); } updateInstallRequested = true; + setUpdateState({ + status: "downloading", + latestVersion: result?.updateInfo?.version || null, + updateAvailable: true, + progressPercent: 0, + error: undefined, + }); await autoUpdater.downloadUpdate(); return desktopUpdatePayload(result); } catch (error) { updateInstallRequested = false; - const message = error instanceof Error ? error.message : String(error); + const message = formatFriendlyUpdateError(error); lastUpdateCheckError = message; + setUpdateState({ + status: "error", + checkedAt: new Date().toISOString(), + error: message, + }); return desktopUpdatePayload(lastUpdateCheckResult, message); } } -function desktopUpdatePayload(result = lastUpdateCheckResult, errorMessage = lastUpdateCheckError) { - return { - currentVersion: app.getVersion(), - latestVersion: result?.updateInfo?.version || null, - updateAvailable: Boolean(result?.isUpdateAvailable), - downloaded: downloadedUpdateReady, - checkedAt: new Date().toISOString(), - error: errorMessage || undefined, - }; +function visibleDialogParent() { + return mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible() ? mainWindow : undefined; } async function checkForDesktopUpdates(manual = false) { if (!app.isPackaged) { + setUpdateState({ + status: "unsupported", + checkedAt: new Date().toISOString(), + updateAvailable: false, + downloaded: false, + error: undefined, + }); if (manual) { - await dialog.showMessageBox({ + await dialog.showMessageBox(visibleDialogParent(), { type: "info", - title: "SketchForge updates", - message: "Automatic updates are tested from the installed SketchForge app.", + title: `${APP_DISPLAY_NAME} Güncellemeleri`, + message: "Otomatik güncelleme yalnızca kurulu masaüstü (.exe) uygulamasında aktiftir.", + detail: `Mevcut geliştirme sürümü: ${app.getVersion()}\nGüncelleme adresi: ${UPDATE_FEED_URL}`, }); } - return desktopUpdatePayload(null); + return desktopUpdatePayload(null, "", { status: "unsupported" }); } if (downloadedUpdateReady) { + if (manual) { + const choice = await dialog.showMessageBox(visibleDialogParent(), { + type: "info", + title: `${APP_DISPLAY_NAME} Güncellemesi Hazır`, + buttons: ["Şimdi Yeniden Başlat ve Kur", "Daha Sonra"], + defaultId: 0, + cancelId: 1, + noLink: true, + message: `${APP_DISPLAY_NAME} ${updateState.latestVersion || ""} kurulumu tamamlanmaya hazır.`, + detail: "Uygulama kapatılıp yeni sürüm kurulacak ve ardından yeniden başlatılacaktır.", + }); + if (choice.response === 0) { + installDownloadedUpdate(); + } + } return desktopUpdatePayload(); } if (updateCheckInFlight) { @@ -177,16 +787,31 @@ async function checkForDesktopUpdates(manual = false) { manualUpdateCheck = manualUpdateCheck || manual; updateCheckInFlight = true; lastUpdateCheckError = ""; + setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined }); try { const result = await autoUpdater.checkForUpdates(); lastUpdateCheckResult = result; + const available = Boolean(result?.isUpdateAvailable); + setUpdateState({ + status: available ? "available" : "not-available", + latestVersion: result?.updateInfo?.version || null, + updateAvailable: available, + downloaded: downloadedUpdateReady, + checkedAt: new Date().toISOString(), + error: undefined, + }); return desktopUpdatePayload(result); } catch (error) { - const message = error instanceof Error ? error.message : String(error); + const message = formatFriendlyUpdateError(error); lastUpdateCheckError = message; + setUpdateState({ + status: "error", + checkedAt: new Date().toISOString(), + error: message, + }); if (manualUpdateCheck) { - dialog.showErrorBox("Could not check for updates", message); manualUpdateCheck = false; + dialog.showErrorBox("Güncellemeler denetlenemedi", message); } return desktopUpdatePayload(null, message); } finally { @@ -194,6 +819,955 @@ async function checkForDesktopUpdates(manual = false) { } } +function requestForceQuit() { + explicitQuit = true; + if (!mainWindow || mainWindow.isDestroyed()) { + isQuitting = true; + app.quit(); + return; + } + if (isDocumentDirty) { + showMainWindow(); + } + mainWindow.close(); +} + +function renderOAuthCallbackHtml({ ok, title, message, userName }) { + const accent = ok ? "#10b981" : "#ef4444"; + const badge = ok ? "BAŞARILI" : "HATA"; + return ` + + + + ${escapeHtml(title)} — ${APP_DISPLAY_NAME} + + + +
+ ${badge} +

${escapeHtml(title)}

+

${escapeHtml(message)}

+ ${userName ? `

Hesap: ${escapeHtml(userName)}

` : ""} +
Bu tarayıcı sekmesini kapatabilir ve ${APP_DISPLAY_NAME} uygulamasına dönebilirsiniz.
+
+ +`; +} + +function closePendingOAuthServer() { + if (pendingOAuthTimeout) { + clearTimeout(pendingOAuthTimeout); + pendingOAuthTimeout = null; + } + if (pendingOAuthServer) { + try { + pendingOAuthServer.close(); + } catch { + // Ignore close errors. + } + pendingOAuthServer = null; + } +} + +async function startYakNetDesktopLogin() { + closePendingOAuthServer(); + + const expectedNonce = crypto.randomBytes(32).toString("hex"); + const expectedNonceBuf = Buffer.from(expectedNonce, "utf8"); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: true, + user: desktopAuthSession?.user ?? null, + }); + + return new Promise((resolve) => { + const server = http.createServer(async (req, res) => { + try { + const reqUrl = new URL(req.url || "/", "http://127.0.0.1"); + if (req.method !== "GET" || reqUrl.pathname !== "/oauth-callback") { + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); + res.end("Not Found"); + return; + } + + const returnedNonce = (reqUrl.searchParams.get("nonce") || "").trim().toLowerCase(); + const returnedNonceBuf = Buffer.from(returnedNonce, "utf8"); + const nonceValid = + returnedNonceBuf.length === expectedNonceBuf.length && + crypto.timingSafeEqual(returnedNonceBuf, expectedNonceBuf); + + if (!nonceValid) { + res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: false, + title: "Güvenlik Doğrulaması Başarısız", + message: "Oturum doğrulama anahtarı eşleşmedi. Lütfen uygulama içinden tekrar Giriş Yap butonuna basın.", + }), + ); + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: "OAuth güvenlik doğrulaması eşleşmedi.", + }); + showMainWindow(); + return; + } + + const errParam = (reqUrl.searchParams.get("error") || "").trim(); + if (errParam) { + res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: false, + title: "YakNet Girişi Tamamlanamadı", + message: errParam, + }), + ); + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: errParam, + }); + showMainWindow(); + return; + } + + const code = (reqUrl.searchParams.get("code") || "").trim().toLowerCase(); + if (!/^[a-f0-9]{48,128}$/.test(code)) { + res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: false, + title: "Geçersiz Giriş Kodu", + message: "Sunucudan geçerli oturum değişim kodu alınamadı.", + }), + ); + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: "Geçersiz oturum değişim kodu.", + }); + showMainWindow(); + return; + } + + const exchangeRes = await fetch(`${CLOUD_ORIGIN}/cloud-api.php?action=desktop_exchange`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, + }, + body: JSON.stringify({ + action: "desktop_exchange", + code, + nonce: expectedNonce, + }), + }); + const payload = await exchangeRes.json().catch(() => null); + if (!exchangeRes.ok || !payload?.ok || typeof payload.token !== "string" || !payload.user) { + const errMsg = payload?.error || "YakNet oturum anahtarı alınamadı."; + res.writeHead(502, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: false, + title: "Oturum Anahtarı Alınamadı", + message: errMsg, + }), + ); + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: errMsg, + }); + showMainWindow(); + return; + } + + saveDesktopAuthSession({ + token: payload.token, + user: payload.user, + expiresAt: payload.expires_at, + }); + + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: true, + title: "YakNet Girişi Tamamlandı", + message: `${APP_DISPLAY_NAME} oturumunuz güvenle bağlandı ve eşitleniyor.`, + userName: payload.user.name, + }), + ); + + closePendingOAuthServer(); + showMainWindow(); + emitAuthUpdated({ + authenticated: true, + pending: false, + user: desktopAuthSession?.user ?? payload.user, + cloudLoginCompleted: true, + }); + } catch (err) { + const message = err instanceof Error ? err.message : "Beklenmeyen giriş hatası"; + try { + res.writeHead(500, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end( + renderOAuthCallbackHtml({ + ok: false, + title: "Bağlantı Hatası", + message, + }), + ); + } catch { + // Ignore broken pipe while sending error response. + } + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: message, + }); + } + }); + + pendingOAuthServer = server; + server.on("error", (err) => { + closePendingOAuthServer(); + const message = err instanceof Error ? err.message : "Yerel giriş dinleyicisi başlatılamadı."; + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: message, + }); + resolve({ started: false, error: message }); + }); + + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + closePendingOAuthServer(); + resolve({ started: false, error: "Geri dönüş portu açılamadı." }); + return; + } + + pendingOAuthTimeout = setTimeout(() => { + closePendingOAuthServer(); + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + }); + }, 5 * 60 * 1000); + pendingOAuthTimeout.unref?.(); + + const deviceName = os.hostname() || "SnapCAD Masaüstü"; + const loginUrl = + `${CLOUD_ORIGIN}/login.php?desktop=1` + + `&desktop_port=${encodeURIComponent(String(address.port))}` + + `&desktop_nonce=${encodeURIComponent(expectedNonce)}` + + `&device=${encodeURIComponent(deviceName)}`; + + void shell.openExternal(loginUrl).then( + () => resolve({ started: true }), + (err) => { + closePendingOAuthServer(); + const message = err instanceof Error ? err.message : "Harici tarayıcı açılamadı."; + emitAuthUpdated({ + authenticated: Boolean(desktopAuthSession), + pending: false, + user: desktopAuthSession?.user ?? null, + error: message, + }); + resolve({ started: false, error: message }); + }, + ); + }); + }); +} + +function storeDesktopCloudCookies(response) { + if (!response?.headers) return; + const rawSetCookies = typeof response.headers.getSetCookie === "function" + ? response.headers.getSetCookie() + : response.headers.get("set-cookie") + ? [response.headers.get("set-cookie")] + : []; + for (const rawCookie of rawSetCookies) { + const firstPart = String(rawCookie || "").split(";")[0]?.trim(); + if (!firstPart) continue; + const eqIndex = firstPart.indexOf("="); + if (eqIndex <= 0) continue; + const name = firstPart.slice(0, eqIndex).trim(); + const val = firstPart.slice(eqIndex + 1).trim(); + if (!name) continue; + if (!val || val === "deleted") { + desktopCloudCookies.delete(name); + } else { + desktopCloudCookies.set(name, val); + } + } +} + +function buildDesktopCloudCookieHeader() { + if (desktopCloudCookies.size === 0) return ""; + return Array.from(desktopCloudCookies.entries()) + .map(([k, v]) => `${k}=${v}`) + .join("; "); +} + +async function logoutYakNetDesktop() { + const token = desktopAuthSession?.token; + const cookieHeader = buildDesktopCloudCookieHeader(); + if (token || cookieHeader) { + try { + const headers = { + Accept: "application/json", + "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, + }; + if (token) { + headers.Authorization = `Bearer ${token}`; + headers["X-SnapCAD-Desktop-Token"] = token; + } + if (cookieHeader) { + headers.Cookie = cookieHeader; + } + await fetch(`${CLOUD_ORIGIN}/cloud-api.php?action=logout`, { + method: "POST", + headers, + }); + } catch { + // Offline logout should still clear local desktop credentials cleanly. + } + } + desktopCloudCookies.clear(); + clearDesktopAuthSession(); + emitAuthUpdated({ + authenticated: false, + pending: false, + user: null, + loggedOut: true, + }); + return { ok: true }; +} + +async function proxyDesktopCloudRequest(rawOptions) { + const normalizedPath = normalizeCloudApiPath(rawOptions?.path); + if (!normalizedPath) { + return { + ok: false, + status: 400, + bodyText: JSON.stringify({ ok: false, error: "Geçersiz bulut API yolu." }), + contentType: "application/json; charset=utf-8", + error: "Geçersiz bulut API yolu.", + }; + } + + const rawMethod = String(rawOptions?.method || "GET").trim().toUpperCase(); + const method = rawMethod === "POST" ? "POST" : "GET"; + + const headers = { + Accept: "application/json", + "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, + }; + if (rawOptions?.headers && typeof rawOptions.headers === "object") { + for (const [k, v] of Object.entries(rawOptions.headers)) { + if (typeof v !== "string") continue; + if (k.toLowerCase() === "content-type") { + headers["Content-Type"] = v; + } + } + } + + const cookieHeader = buildDesktopCloudCookieHeader(); + if (cookieHeader) { + headers.Cookie = cookieHeader; + } + + const hadToken = Boolean(desktopAuthSession?.token); + if (desktopAuthSession?.token) { + headers.Authorization = `Bearer ${desktopAuthSession.token}`; + headers["X-SnapCAD-Desktop-Token"] = desktopAuthSession.token; + } + + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 20_000); + let response; + let bodyText; + try { + response = await fetch(`${CLOUD_ORIGIN}${normalizedPath}`, { + method, + headers, + body: method === "POST" && typeof rawOptions?.body === "string" ? rawOptions.body : undefined, + signal: controller.signal, + }); + storeDesktopCloudCookies(response); + bodyText = await response.text(); + } finally { + clearTimeout(timeout); + } + + if (normalizedPath.includes("action=logout")) { + desktopCloudCookies.clear(); + clearDesktopAuthSession(); + } else if (hadToken) { + let parsed = null; + try { + parsed = JSON.parse(bodyText); + } catch { + // Ignore non-JSON body when inspecting token invalidity. + } + if (parsed?.token_invalid === true || (response.status === 401 && parsed?.authenticated === false)) { + clearDesktopAuthSession(); + emitAuthUpdated({ + authenticated: false, + pending: false, + user: null, + loggedOut: true, + }); + } else if (parsed?.authenticated === true && parsed?.user && desktopAuthSession) { + desktopAuthSession.user = parsed.user; + } + } + + return { + ok: response.ok, + status: response.status, + bodyText, + contentType: response.headers.get("content-type") || "application/json; charset=utf-8", + }; + } catch (error) { + const message = error instanceof Error ? error.message : "YakNet Bulut servisine şu anda ulaşılamıyor."; + return { + ok: false, + status: 0, + bodyText: JSON.stringify({ ok: false, error: message }), + contentType: "application/json; charset=utf-8", + error: message, + }; + } +} + +function buildNativeApplicationMenu() { + if (!app.isReady()) return null; + const isMac = process.platform === "darwin"; + const isFullScreen = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFullScreen()); + const isClassicKeymap = menuUiState.keymapProfile !== "snapcad-standard"; + const signedInUser = desktopAuthSession?.user ?? null; + + const template = [ + ...(isMac + ? [ + { + label: APP_DISPLAY_NAME, + submenu: [ + { role: "about", label: `${APP_DISPLAY_NAME} Hakkında` }, + { type: "separator" }, + { role: "services" }, + { type: "separator" }, + { role: "hide" }, + { role: "hideOthers" }, + { role: "unhide" }, + { type: "separator" }, + { role: "quit", label: "Çıkış" }, + ], + }, + ] + : []), + { + label: "Dosya", + submenu: [ + { + label: "Yeni 3B Proje", + accelerator: "CmdOrCtrl+N", + click: () => sendMenuCommand("file:new"), + }, + { + label: "Proje Aç (.skf)…", + accelerator: "CmdOrCtrl+O", + click: () => sendMenuCommand("file:open"), + }, + { type: "separator" }, + { + label: "Kaydet", + accelerator: "CmdOrCtrl+S", + click: () => sendMenuCommand("file:save"), + }, + { + label: "Farklı Kaydet (.skf)…", + accelerator: "CmdOrCtrl+Shift+S", + click: () => sendMenuCommand("file:save-as"), + }, + { type: "separator" }, + { + label: "İçe Aktar (IFC, DWG, DXF, STEP, STL, OBJ, GLB, SVG, Görsel)…", + click: () => sendMenuCommand("file:import"), + }, + { + label: "Dışa Aktar", + submenu: [ + { label: "Dışa Aktar Penceresini Aç…", click: () => sendMenuCommand("file:export-panel") }, + { type: "separator" }, + { label: "STL 3B Yazıcı Modeli (.stl)…", click: () => sendMenuCommand("file:export-stl") }, + { label: "3MF Baskı Paketi (.3mf)…", click: () => sendMenuCommand("file:export-3mf") }, + { label: "STEP B-Rep Katı Model (.step)…", click: () => sendMenuCommand("file:export-step") }, + { label: "Wavefront 3B Mesh (.obj)…", click: () => sendMenuCommand("file:export-obj") }, + { label: "Binary glTF 3B Model (.glb)…", click: () => sendMenuCommand("file:export-glb") }, + { label: "AutoCAD 2B/3B DXF (.dxf)…", click: () => sendMenuCommand("file:export-dxf") }, + { label: "Vektör Üst Görünüm SVG (.svg)…", click: () => sendMenuCommand("file:export-svg") }, + { label: "SnapCAD Proje Arşivi (.skf)…", click: () => sendMenuCommand("file:export-skf") }, + ], + }, + { type: "separator" }, + { + label: "Model Bilgisi & Çalışma Alanı Birimleri…", + click: () => sendMenuCommand("window:workspace-settings"), + }, + { + label: "YakNet Bulut Hesabı", + submenu: signedInUser + ? [ + { + label: `Oturum Açık: ${signedInUser.name || signedInUser.email || "YakNet Kullanıcısı"}`, + enabled: false, + }, + { label: "Projeler ve Bulut Senkronizasyon Paneli", click: () => sendMenuCommand("file:dashboard") }, + { label: "Başka Hesapla Giriş Yap…", click: () => void startYakNetDesktopLogin() }, + { type: "separator" }, + { label: "YakNet Hesabından Çıkış Yap", click: () => void logoutYakNetDesktop() }, + ] + : [ + { label: "YakNet ile Giriş Yap (Tarayıcıda)…", click: () => void startYakNetDesktopLogin() }, + { label: "Projeler Paneline Dön", click: () => sendMenuCommand("file:dashboard") }, + ], + }, + { type: "separator" }, + { + label: "Projeler Paneline Dön", + click: () => sendMenuCommand("file:dashboard"), + }, + { + label: "Sistem Tepsisine Küçült", + click: () => hideToTrayWindow({ showBalloonOnce: true }), + }, + ...(!isMac + ? [ + { type: "separator" }, + { + label: "Tamamen Çıkış Yap", + accelerator: "Alt+F4", + click: () => requestForceQuit(), + }, + ] + : []), + ], + }, + { + label: "Düzenle", + submenu: [ + { label: "Geri Al", accelerator: "CmdOrCtrl+Z", registerAccelerator: false, click: () => sendMenuCommand("edit:undo") }, + { label: "Yinele", accelerator: "CmdOrCtrl+Y", registerAccelerator: false, click: () => sendMenuCommand("edit:redo") }, + { type: "separator" }, + { label: "Kes", accelerator: "CmdOrCtrl+X", registerAccelerator: false, click: () => sendMenuCommand("edit:cut") }, + { label: "Kopyala", accelerator: "CmdOrCtrl+C", registerAccelerator: false, click: () => sendMenuCommand("edit:copy") }, + { label: "Yapıştır", accelerator: "CmdOrCtrl+V", registerAccelerator: false, click: () => sendMenuCommand("edit:paste") }, + { label: "Çoğalt", accelerator: "CmdOrCtrl+D", registerAccelerator: false, click: () => sendMenuCommand("edit:duplicate") }, + { label: "Sil", accelerator: "Delete", registerAccelerator: false, click: () => sendMenuCommand("edit:delete") }, + { type: "separator" }, + { label: "Tümünü Seç", accelerator: "CmdOrCtrl+A", registerAccelerator: false, click: () => sendMenuCommand("edit:select-all") }, + { label: "Seçimi Bırak", accelerator: "Escape", registerAccelerator: false, click: () => sendMenuCommand("edit:clear-selection") }, + { type: "separator" }, + { + label: "Bileşen Oluştur (Make Component)", + accelerator: isClassicKeymap ? "G" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("edit:make-component"), + }, + { label: "Bileşeni Benzersiz Yap (Make Unique)", click: () => sendMenuCommand("edit:make-unique") }, + { label: "Grupla (Make Group)", accelerator: "CmdOrCtrl+G", registerAccelerator: false, click: () => sendMenuCommand("edit:group") }, + { label: "Grubu Çöz (Explode)", accelerator: "CmdOrCtrl+Shift+G", registerAccelerator: false, click: () => sendMenuCommand("edit:ungroup") }, + { label: "Kesişim (Boolean Intersection)", click: () => sendMenuCommand("edit:intersect") }, + { + label: "Biçim (Katı / Delik)", + submenu: [ + { label: "Katı Forma Dönüştür (Solid)", click: () => sendMenuCommand("edit:make-solid") }, + { label: "Deliğe Dönüştür (Hole)", click: () => sendMenuCommand("edit:make-hole") }, + ], + }, + { type: "separator" }, + { label: "Aynala (Mirror)", accelerator: "Shift+M", registerAccelerator: false, click: () => sendMenuCommand("edit:mirror") }, + { label: "Hizala (Align)", click: () => sendMenuCommand("edit:align") }, + { label: "Çalışma Düzlemine İndir", accelerator: "D", registerAccelerator: false, click: () => sendMenuCommand("edit:drop-to-workplane") }, + { label: "Izgaraya Oturt (Snap to Grid)", click: () => sendMenuCommand("edit:snap-to-grid") }, + { label: "Pah Kır (Chamfer)…", click: () => sendMenuCommand("edit:chamfer") }, + { label: "Yuvarla (Fillet)…", click: () => sendMenuCommand("edit:fillet") }, + { type: "separator" }, + { label: "Seçileni Gizle / Göster", accelerator: "CmdOrCtrl+H", registerAccelerator: false, click: () => sendMenuCommand("edit:hide") }, + { label: "Tüm Gizlileri Göster", accelerator: "CmdOrCtrl+Shift+H", registerAccelerator: false, click: () => sendMenuCommand("edit:show-hidden") }, + { label: "Kilitle / Kilidi Aç", accelerator: "CmdOrCtrl+L", registerAccelerator: false, click: () => sendMenuCommand("edit:lock") }, + ], + }, + { + label: "Görünüm", + submenu: [ + { + label: "Büyük Araç Seti (Sol Panel)", + type: "checkbox", + checked: Boolean(menuUiState.showLeftToolset), + click: () => sendMenuCommand("view:toggle-left-toolset"), + }, + { + label: "Varsayılan Tepsi (Sağ Panel)", + type: "checkbox", + checked: Boolean(menuUiState.showDefaultTray), + click: () => sendMenuCommand("view:toggle-tray"), + }, + { + label: "SnapCAD Üst Araç Şeridi", + type: "checkbox", + checked: Boolean(menuUiState.showSecondaryRibbon), + click: () => sendMenuCommand("view:toggle-secondary-ribbon"), + }, + { type: "separator" }, + { + label: "Gökyüzü & Ufuk Zemini", + type: "checkbox", + checked: Boolean(menuUiState.skyGroundEnabled), + click: () => sendMenuCommand("view:sky-ground"), + }, + { + label: "Arka Kenarlar (Back Edges)", + type: "checkbox", + checked: Boolean(menuUiState.backEdgesEnabled), + accelerator: isClassicKeymap ? "K" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("view:back-edges"), + }, + { + label: "X-Ray (Röntgen Modu)", + type: "checkbox", + checked: Boolean(menuUiState.xRayMode), + accelerator: "X", + registerAccelerator: false, + click: () => sendMenuCommand("view:xray"), + }, + { label: "Kesit Düzlemi (Section Plane)", click: () => sendMenuCommand("tool:section") }, + { type: "separator" }, + { + label: "Yüz Stili", + submenu: [ + { label: "Dokulu & Gölgeli", type: "radio", checked: menuUiState.visualStyle === "shaded", click: () => sendMenuCommand("view:style-shaded") }, + { label: "Monokrom", type: "radio", checked: menuUiState.visualStyle === "monochrome", click: () => sendMenuCommand("view:style-monochrome") }, + { label: "Gizli Çizgi (Hidden Line)", type: "radio", checked: menuUiState.visualStyle === "hidden-line", click: () => sendMenuCommand("view:style-hidden-line") }, + { label: "Tel Kafes (Wireframe)", type: "radio", checked: menuUiState.visualStyle === "wireframe", click: () => sendMenuCommand("view:style-wireframe") }, + { label: "Mimari Ozalit (Blueprint)", type: "radio", checked: menuUiState.visualStyle === "blueprint", click: () => sendMenuCommand("view:style-blueprint") }, + { label: "Sıcak Kil (Clay)", type: "radio", checked: menuUiState.visualStyle === "clay", click: () => sendMenuCommand("view:style-clay") }, + { label: "Cyberpunk", type: "radio", checked: menuUiState.visualStyle === "cyberpunk", click: () => sendMenuCommand("view:style-cyberpunk") }, + ], + }, + { type: "separator" }, + { label: "Etiketler / Katmanlar…", click: () => sendMenuCommand("view:layers") }, + { label: "Güneş & Gölgeler Etüdü…", click: () => sendMenuCommand("view:solar") }, + { label: "Kılavuz Çizgilerini Temizle", click: () => sendMenuCommand("view:clear-guides") }, + { type: "separator" }, + { role: "zoomIn", label: "Arayüzü Yakınlaştır" }, + { role: "zoomOut", label: "Arayüzü Uzaklaştır" }, + { role: "resetZoom", label: "Arayüz Yakınlaştırmasını Sıfırla" }, + { type: "separator" }, + { + label: "Tam Ekran", + type: "checkbox", + checked: isFullScreen, + accelerator: isMac ? "Ctrl+Cmd+F" : "F11", + click: () => { + if (!mainWindow || mainWindow.isDestroyed()) return; + mainWindow.setFullScreen(!mainWindow.isFullScreen()); + }, + }, + ], + }, + { + label: "Kamera", + submenu: [ + { label: "İzometrik Görünüm", accelerator: "Home", registerAccelerator: false, click: () => sendMenuCommand("camera:isometric") }, + { label: "Üst (Top)", accelerator: "5", registerAccelerator: false, click: () => sendMenuCommand("camera:top") }, + { label: "Alt (Bottom)", accelerator: "6", registerAccelerator: false, click: () => sendMenuCommand("camera:bottom") }, + { label: "Ön (Front)", accelerator: "1", registerAccelerator: false, click: () => sendMenuCommand("camera:front") }, + { label: "Arka (Back)", accelerator: "2", registerAccelerator: false, click: () => sendMenuCommand("camera:back") }, + { label: "Sol (Left)", accelerator: "3", registerAccelerator: false, click: () => sendMenuCommand("camera:left") }, + { label: "Sağ (Right)", accelerator: "4", registerAccelerator: false, click: () => sendMenuCommand("camera:right") }, + { type: "separator" }, + { + label: "Paralel İzdüşüm (Parallel Projection)", + type: "checkbox", + checked: Boolean(menuUiState.isOrthographic), + accelerator: isClassicKeymap ? "Shift+V" : "O", + registerAccelerator: false, + click: () => sendMenuCommand("view:toggle-projection"), + }, + { label: "İki Kaçışlı Perspektif (2-Point)", click: () => sendMenuCommand("camera:two-point") }, + { label: "Kamerayı Sıfırla", click: () => sendMenuCommand("view:reset-camera") }, + { type: "separator" }, + { + label: "Yörünge (Orbit)", + accelerator: isClassicKeymap ? "O" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("tool:orbit"), + }, + { + label: "Kaydır (Pan)", + accelerator: isClassicKeymap ? "H" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("tool:pan"), + }, + { label: "Yakınlaştır (Zoom)", accelerator: "Z", registerAccelerator: false, click: () => sendMenuCommand("tool:zoom") }, + { label: "Ekrana Sığdır (Zoom Extents)", accelerator: "Shift+Z", registerAccelerator: false, click: () => sendMenuCommand("view:zoom-extents") }, + { label: "Seçileni Çerçevele (Zoom Selection)", accelerator: "Alt+Z", registerAccelerator: false, click: () => sendMenuCommand("camera:zoom-selection") }, + { label: "Önceki Görünüm (Previous)", accelerator: "Alt+P", registerAccelerator: false, click: () => sendMenuCommand("camera:previous") }, + { type: "separator" }, + { label: "İçinde Yürü (Walk / WASD)", click: () => sendMenuCommand("tool:walk") }, + ], + }, + { + label: "Çizim", + submenu: [ + { label: "Çizgi (Line)", accelerator: "L", registerAccelerator: false, click: () => sendMenuCommand("tool:line") }, + { label: "Serbest / Eğri (Freehand)", click: () => sendMenuCommand("tool:freehand") }, + { label: "Yay (2-Point Arc)", accelerator: "A", registerAccelerator: false, click: () => sendMenuCommand("tool:arc") }, + { type: "separator" }, + { label: "Dikdörtgen (Rectangle)", accelerator: "R", registerAccelerator: false, click: () => sendMenuCommand("tool:rectangle") }, + { label: "Daire (Circle)", accelerator: "C", registerAccelerator: false, click: () => sendMenuCommand("tool:circle") }, + { label: "Çokgen (Polygon)", click: () => sendMenuCommand("tool:polygon") }, + { label: "3B Metin Ekle (3D Text)", click: () => sendMenuCommand("tool:3d-text") }, + { type: "separator" }, + { + label: "Temel 3B Şekil Ekle", + submenu: [ + { label: "Kutu", click: () => sendMenuCommand("draw:shape-box") }, + { label: "Silindir", click: () => sendMenuCommand("draw:shape-cylinder") }, + { label: "Küre", click: () => sendMenuCommand("draw:shape-sphere") }, + { label: "Koni", click: () => sendMenuCommand("draw:shape-cone") }, + { label: "Piramit", click: () => sendMenuCommand("draw:shape-pyramid") }, + { label: "Kama (Eğim)", click: () => sendMenuCommand("draw:shape-wedge") }, + { label: "Yuvarlak Çatı", click: () => sendMenuCommand("draw:shape-round-roof") }, + { label: "Yarım Küre", click: () => sendMenuCommand("draw:shape-half-sphere") }, + { label: "Halka (Simit)", click: () => sendMenuCommand("draw:shape-torus") }, + { label: "Boru", click: () => sendMenuCommand("draw:shape-tube") }, + { label: "Dişli Çark", click: () => sendMenuCommand("draw:shape-gear") }, + ], + }, + { type: "separator" }, + { label: "2B Eskiz: Ekstrüde (Extrude)", click: () => sendMenuCommand("draw:sketch-extrude") }, + { label: "2B Eskiz: Döndür (Revolve)", click: () => sendMenuCommand("draw:sketch-revolve") }, + { label: "Seçili Eskizi Düzenle", click: () => sendMenuCommand("draw:sketch-edit") }, + { type: "separator" }, + { label: "Örnek Mimari Ev Sahnesi Oluştur", click: () => sendMenuCommand("draw:house-scene") }, + ], + }, + { + label: "Araçlar", + submenu: [ + { label: "Seçim (Select)", accelerator: "Space", registerAccelerator: false, click: () => sendMenuCommand("tool:select") }, + { label: "Silgi (Eraser)", accelerator: "E", registerAccelerator: false, click: () => sendMenuCommand("tool:eraser") }, + { label: "Boya Kovası (Paint Bucket)", accelerator: "B", registerAccelerator: false, click: () => sendMenuCommand("tool:paint") }, + { type: "separator" }, + { label: "Taşı (Move)", accelerator: "M", registerAccelerator: false, click: () => sendMenuCommand("tool:move") }, + { label: "İt / Çek (Push/Pull)", accelerator: "P", registerAccelerator: false, click: () => sendMenuCommand("tool:push-pull") }, + { + label: "Döndür (Rotate)", + accelerator: isClassicKeymap ? "Q" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("tool:rotate"), + }, + { label: "Ölçekle (Scale)", accelerator: "S", registerAccelerator: false, click: () => sendMenuCommand("tool:scale") }, + { + label: "Ofset (Offset)", + accelerator: isClassicKeymap ? "F" : undefined, + registerAccelerator: false, + click: () => sendMenuCommand("tool:offset"), + }, + { label: "Beni Takip Et (Follow Me)…", click: () => sendMenuCommand("tool:follow-me") }, + { type: "separator" }, + { label: "Şerit Metre & Kılavuz", accelerator: "T", registerAccelerator: false, click: () => sendMenuCommand("tool:tape") }, + { label: "İletki / Açılı Kılavuz", click: () => sendMenuCommand("tool:protractor") }, + { label: "Eksenler / Çalışma Düzlemi", accelerator: "W", registerAccelerator: false, click: () => sendMenuCommand("tool:axes") }, + { label: "Kesit Düzlemi (Section Plane)", click: () => sendMenuCommand("tool:section") }, + { type: "separator" }, + { label: "Duvar Kapı / Pencere Boşluğu Aç…", click: () => sendMenuCommand("tool:wall-opening") }, + { label: "Arazi & Yükselti Üreticisi…", click: () => sendMenuCommand("tool:terrain") }, + { label: "Statik & Deprem Dayanım Testi…", click: () => sendMenuCommand("tool:structural-test") }, + { label: "Masamda Gör (AR Ön İzleme)…", click: () => sendMenuCommand("tool:ar-preview") }, + { type: "separator" }, + { label: "Fizik & Yerçekimi Simülasyonu (Başlat/Duraklat)", click: () => sendMenuCommand("tool:physics-toggle") }, + { label: "Fizik Simülasyonunu Sıfırla", click: () => sendMenuCommand("tool:physics-reset") }, + ], + }, + { + label: "Pencere", + submenu: [ + { + label: "Varsayılan Tepsi Bölümleri", + submenu: [ + { label: "Öğe Bilgisi (Entity Info)", click: () => sendMenuCommand("tray:entity-info") }, + { label: "Ana Hatlar (Outliner)", click: () => sendMenuCommand("tray:outliner") }, + { label: "Bileşenler (3B Havuz)", click: () => sendMenuCommand("tray:components") }, + { label: "Malzemeler (Materials)", click: () => sendMenuCommand("tray:materials") }, + { label: "Stiller (Styles)", click: () => sendMenuCommand("tray:styles") }, + { label: "Etiketler (Tags / Layers)", click: () => sendMenuCommand("tray:tags") }, + { label: "Gölgeler & Güneş (Shadows)", click: () => sendMenuCommand("tray:shadows") }, + { label: "Sahneler (Scenes)", click: () => sendMenuCommand("tray:scenes") }, + { label: "Eğitmen (Instructor)", click: () => sendMenuCommand("tray:instructor") }, + ], + }, + { + label: "Sağ Özellik Panelini Göster", + type: "checkbox", + checked: Boolean(menuUiState.showDefaultTray), + click: () => sendMenuCommand("view:toggle-tray"), + }, + { type: "separator" }, + { + label: "Kısayol Profili: Mimari Klasik", + type: "radio", + checked: isClassicKeymap, + click: () => sendMenuCommand("window:keymap-classic"), + }, + { + label: "Kısayol Profili: SnapCAD Erişilebilir", + type: "radio", + checked: !isClassicKeymap, + click: () => sendMenuCommand("window:keymap-standard"), + }, + { type: "separator" }, + { label: "Hızlı Komut Paleti…", accelerator: "CmdOrCtrl+K", registerAccelerator: false, click: () => sendMenuCommand("window:command-palette") }, + { label: "Erişilebilirlik & NVDA Kontrolleri…", accelerator: "Alt+A", registerAccelerator: false, click: () => sendMenuCommand("window:a11y") }, + { label: "Model Bilgisi & Birim Ayarları…", click: () => sendMenuCommand("window:workspace-settings") }, + { label: "Uygulama Ayarları…", click: () => sendMenuCommand("window:settings") }, + { type: "separator" }, + { + label: "Kapatınca Gizli Simgelerde Tut", + type: "checkbox", + checked: Boolean(desktopPrefs.closeToTray), + click: (menuItem) => { + saveDesktopPrefs({ closeToTray: Boolean(menuItem.checked) }); + }, + }, + { + label: "Sistem Tepsisine Küçült", + click: () => hideToTrayWindow({ showBalloonOnce: true }), + }, + ], + }, + { + label: "Stüdyolar", + submenu: [ + { label: "3B Katı Tasarım (Projeler)", click: () => sendMenuCommand("file:dashboard") }, + { label: "Teknik Çizim Stüdyosu", click: () => sendMenuCommand("window:drawing") }, + { label: "Elektronik Devreler", click: () => sendMenuCommand("window:circuits") }, + { label: "Kod Blokları", click: () => sendMenuCommand("window:codeblocks") }, + { type: "separator" }, + { label: "Sınıflar & Ortak Alanlar", click: () => sendMenuCommand("window:classrooms") }, + { label: "Paylaşılan Projeler", click: () => sendMenuCommand("window:shared") }, + { label: "Görevler ve Eğitimler", click: () => sendMenuCommand("window:challenges") }, + { label: "Görünüm & Erişilebilirlik Merkezi", click: () => sendMenuCommand("window:customization") }, + { type: "separator" }, + { label: "Uygulama Ayarları…", click: () => sendMenuCommand("window:settings") }, + ], + }, + { + label: "Yardım", + submenu: [ + { label: "3B Sahne Denetçisi (Erişilebilir Rapor)", accelerator: "F2", registerAccelerator: false, click: () => sendMenuCommand("help:audit") }, + { label: "Sesli / Metin CAD Komut Konsolu…", accelerator: "F4", registerAccelerator: false, click: () => sendMenuCommand("help:voice") }, + { label: "Sesli 3B Radar Taraması", accelerator: "F8", registerAccelerator: false, click: () => sendMenuCommand("help:radar") }, + { label: "Klavye Kısayolları", click: () => sendMenuCommand("help:shortcuts") }, + { type: "separator" }, + { label: "SnapCAD Akademi İnteraktif Eğitimi…", click: () => sendMenuCommand("help:tutorial") }, + { label: "Günün Mimari Görevleri…", click: () => sendMenuCommand("help:daily-challenges") }, + { type: "separator" }, + { label: "Güncellemeleri Denetle…", click: () => void checkForDesktopUpdates(true) }, + { + label: "Kurumsal Bilgiler", + submenu: [ + { label: "Hakkımızda", click: () => sendMenuCommand("window:about") }, + { label: "İletişim & Destek", click: () => sendMenuCommand("window:contact") }, + { label: "KVKK & Gizlilik Politikası", click: () => sendMenuCommand("window:kvkk") }, + { label: "Kullanım Koşulları", click: () => sendMenuCommand("window:terms") }, + { label: "Kurumsal Güvenlik", click: () => sendMenuCommand("window:security") }, + ], + }, + { + label: `${APP_DISPLAY_NAME} Hakkında`, + click: () => { + void dialog.showMessageBox(mainWindow ?? undefined, { + type: "info", + title: `${APP_DISPLAY_NAME} Hakkında`, + message: `${APP_DISPLAY_NAME} v${app.getVersion()}`, + detail: [ + "Yerel-öncelikli 3B Parametrik CAD, HLR Teknik Çizim, BIM (IFC) ve Elektronik Tasarım Stüdyosu.", + "Geometri Çekirdekleri: Three.js + three-bvh-csg + three-edge-projection + Manifold + OpenCascade + PlaneGCS + Clipper2 + web-ifc", + "Lisans: AGPL-3.0-only", + ].join("\n"), + }); + }, + }, + ], + }, + ]; + + const appMenu = Menu.buildFromTemplate(template); + Menu.setApplicationMenu(appMenu); + desktopMenuBuilt = true; + return appMenu; +} + function setupDesktopIpc() { if (desktopIpcConfigured) return; desktopIpcConfigured = true; @@ -201,6 +1775,140 @@ function setupDesktopIpc() { ipcMain.handle("sketchforge:get-version", () => app.getVersion()); ipcMain.handle("sketchforge:check-for-updates", () => checkForDesktopUpdates(false)); ipcMain.handle("sketchforge:install-update", () => downloadAndInstallDesktopUpdate()); + ipcMain.handle("snapcad:get-update-state", () => desktopUpdatePayload()); + + ipcMain.handle("snapcad:get-desktop-prefs", () => ({ ...desktopPrefs })); + ipcMain.handle("snapcad:set-desktop-prefs", (_event, patch) => saveDesktopPrefs(patch)); + ipcMain.handle("snapcad:hide-to-tray", () => { + hideToTrayWindow({ showBalloonOnce: true }); + return true; + }); + + ipcMain.handle("snapcad:yaknet-login", () => startYakNetDesktopLogin()); + ipcMain.handle("snapcad:yaknet-logout", () => logoutYakNetDesktop()); + ipcMain.handle("snapcad:cloud-request", (_event, options) => proxyDesktopCloudRequest(options)); + + ipcMain.handle("snapcad:open-skf-dialog", async () => { + const result = await dialog.showOpenDialog(mainWindow ?? undefined, { + title: "SnapCAD Projesi Aç (.skf)", + properties: ["openFile"], + filters: [ + { name: "SnapCAD Projesi (.skf)", extensions: ["skf"] }, + { name: "Tüm Dosyalar", extensions: ["*"] }, + ], + }); + if (result.canceled || result.filePaths.length === 0) return null; + return readTrustedSkfFile(result.filePaths[0]); + }); + + ipcMain.handle("snapcad:save-skf-dialog", async (_event, rawOptions) => { + const options = rawOptions && typeof rawOptions === "object" ? rawOptions : {}; + const bytes = options.bytes instanceof Uint8Array + ? options.bytes + : ArrayBuffer.isView(options.bytes) + ? new Uint8Array(options.bytes.buffer, options.bytes.byteOffset, options.bytes.byteLength) + : null; + if (!bytes) { + return { canceled: true, error: "Proje verisi gecersiz." }; + } + + const defaultNameRaw = typeof options.defaultFileName === "string" && options.defaultFileName.trim() + ? options.defaultFileName.trim() + : "snapcad-proje.skf"; + const defaultName = defaultNameRaw.toLowerCase().endsWith(".skf") ? defaultNameRaw : `${defaultNameRaw}.skf`; + + const requestedTarget = typeof options.targetPath === "string" && options.targetPath.trim() + ? path.resolve(options.targetPath.trim()) + : null; + + if (!options.forceDialog && requestedTarget && requestedTarget.toLowerCase().endsWith(".skf") && trustedDialogPaths.has(requestedTarget)) { + const savedPath = writeFileAtomic(requestedTarget, bytes); + return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; + } + + const saveResult = await dialog.showSaveDialog(mainWindow ?? undefined, { + title: "SnapCAD Projesini Kaydet", + defaultPath: requestedTarget || path.join(app.getPath("documents"), defaultName), + filters: [{ name: "SnapCAD Projesi (.skf)", extensions: ["skf"] }], + }); + if (saveResult.canceled || !saveResult.filePath) { + return { canceled: true }; + } + const target = saveResult.filePath.toLowerCase().endsWith(".skf") ? saveResult.filePath : `${saveResult.filePath}.skf`; + const savedPath = writeFileAtomic(target, bytes); + return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; + }); + + ipcMain.handle("snapcad:save-export-dialog", async (_event, rawOptions) => { + const options = rawOptions && typeof rawOptions === "object" ? rawOptions : {}; + const bytes = options.bytes instanceof Uint8Array + ? options.bytes + : ArrayBuffer.isView(options.bytes) + ? new Uint8Array(options.bytes.buffer, options.bytes.byteOffset, options.bytes.byteLength) + : null; + if (!bytes) { + return { canceled: true, error: "Disa aktarilacak veri gecersiz." }; + } + const defaultFileName = typeof options.defaultFileName === "string" && options.defaultFileName.trim() + ? path.basename(options.defaultFileName.trim()) + : "snapcad-export.stl"; + const filters = Array.isArray(options.filters) && options.filters.length > 0 + ? options.filters + : [{ name: "Tüm Dosyalar", extensions: ["*"] }]; + + const saveResult = await dialog.showSaveDialog(mainWindow ?? undefined, { + title: "Model / Teknik Çizim Dışa Aktar", + defaultPath: path.join(app.getPath("documents"), defaultFileName), + filters, + }); + if (saveResult.canceled || !saveResult.filePath) { + return { canceled: true }; + } + const savedPath = writeFileAtomic(saveResult.filePath, bytes); + return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; + }); + + ipcMain.handle("snapcad:consume-pending-open-file", () => { + if (!pendingOpenFilePath) return null; + const queued = pendingOpenFilePath; + pendingOpenFilePath = null; + try { + return readTrustedSkfFile(queued); + } catch { + return null; + } + }); + + ipcMain.handle("snapcad:set-dirty", (_event, dirty) => { + isDocumentDirty = Boolean(dirty); + }); + + ipcMain.handle("snapcad:set-window-title", (_event, title) => { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.setTitle(sanitizeWindowTitleInput(title)); + } + }); + + ipcMain.handle("snapcad:confirm-close-after-save", () => { + isDocumentDirty = false; + explicitQuit = true; + isQuitting = true; + saveWindowStateImmediate(); + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.destroy(); + } + app.quit(); + }); + + ipcMain.handle("snapcad:open-external", (_event, rawUrl) => { + if (!isAllowedExternalUrl(rawUrl)) return false; + void shell.openExternal(String(rawUrl)); + return true; + }); + + ipcMain.handle("snapcad:set-menu-state", (_event, patch) => { + updateMenuUiState(patch); + }); } function setupDesktopUpdater() { @@ -210,107 +1918,292 @@ function setupDesktopUpdater() { autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; autoUpdater.allowPrerelease = false; + try { + autoUpdater.setFeedURL({ + provider: "generic", + url: UPDATE_FEED_URL, + }); + } catch { + // Fallback cleanly to bundled resources/app-update.yml if setFeedURL rejects. + } - autoUpdater.on("update-available", (info) => { - if (!manualUpdateCheck) return; - manualUpdateCheck = false; - void dialog.showMessageBox({ - type: "info", - title: "SketchForge update", - message: `SketchForge ${info.version} is available.`, - detail: "Open Settings and press Update to install it.", + autoUpdater.on("checking-for-update", () => { + setUpdateState({ + status: "checking", + checkedAt: new Date().toISOString(), + error: undefined, }); }); - autoUpdater.on("update-not-available", () => { + autoUpdater.on("update-available", (info) => { + setUpdateState({ + status: "available", + latestVersion: info?.version || null, + updateAvailable: true, + downloaded: downloadedUpdateReady, + checkedAt: new Date().toISOString(), + error: undefined, + }); if (!manualUpdateCheck) return; manualUpdateCheck = false; - void dialog.showMessageBox({ + void dialog + .showMessageBox(visibleDialogParent(), { + type: "info", + title: `${APP_DISPLAY_NAME} Güncellemesi`, + buttons: ["İndir ve Kur", "Ayarları Aç", "Daha Sonra"], + defaultId: 0, + cancelId: 2, + noLink: true, + message: `${APP_DISPLAY_NAME} ${info.version} sürümü mevcut.`, + detail: "Hemen indirip kurmak veya Ayarlar panelinden ilerlemeyi izlemek ister misiniz?", + }) + .then(({ response }) => { + if (response === 0) { + showMainWindow(); + void downloadAndInstallDesktopUpdate(); + } else if (response === 1) { + sendMenuCommand("window:settings"); + } + }); + }); + + autoUpdater.on("update-not-available", () => { + setUpdateState({ + status: "not-available", + updateAvailable: false, + downloaded: false, + checkedAt: new Date().toISOString(), + error: undefined, + }); + if (tray) tray.setToolTip(APP_DISPLAY_NAME); + if (!manualUpdateCheck) return; + manualUpdateCheck = false; + void dialog.showMessageBox(visibleDialogParent(), { type: "info", - title: "SketchForge updates", - message: "SketchForge is up to date.", + title: `${APP_DISPLAY_NAME} Güncellemeleri`, + message: `${APP_DISPLAY_NAME} en güncel sürümde (v${app.getVersion()}).`, }); }); autoUpdater.on("download-progress", (progress) => { - if (tray) tray.setToolTip(`SketchForge - downloading update ${Math.round(progress.percent)}%`); + const percent = Math.max(0, Math.min(100, Math.round(Number(progress?.percent || 0)))); + if (tray) tray.setToolTip(`${APP_DISPLAY_NAME} — güncelleme indiriliyor (%${percent})`); + setUpdateState({ + status: "downloading", + progressPercent: percent, + bytesPerSecond: Number(progress?.bytesPerSecond || 0), + transferred: Number(progress?.transferred || 0), + total: Number(progress?.total || 0), + error: undefined, + }); }); autoUpdater.on("update-downloaded", (info) => { downloadedUpdateReady = true; - if (tray) tray.setToolTip(`SketchForge ${info.version} ready to install`); - if (updateInstallRequested) installDownloadedUpdate(); + updateTrayMenu(); + if (tray) tray.setToolTip(`${APP_DISPLAY_NAME} v${info?.version || ""} kuruluma hazır`); + setUpdateState({ + status: "downloaded", + latestVersion: info?.version || updateState.latestVersion, + updateAvailable: true, + downloaded: true, + progressPercent: 100, + error: undefined, + }); + if (updateInstallRequested) { + installDownloadedUpdate(); + return; + } + void dialog + .showMessageBox(visibleDialogParent(), { + type: "info", + title: `${APP_DISPLAY_NAME} Güncellemesi Hazır`, + buttons: ["Şimdi Yeniden Başlat ve Kur", "Daha Sonra"], + defaultId: 0, + cancelId: 1, + noLink: true, + message: `${APP_DISPLAY_NAME} ${info?.version || ""} indirildi.`, + detail: "Güncellemeyi tamamlamak için uygulamayı yeniden başlatabilirsiniz.", + }) + .then(({ response }) => { + if (response === 0) { + installDownloadedUpdate(); + } + }); }); autoUpdater.on("error", (error) => { - if (tray) tray.setToolTip("SketchForge"); + const friendly = formatFriendlyUpdateError(error); + lastUpdateCheckError = friendly; + if (tray) tray.setToolTip(APP_DISPLAY_NAME); + setUpdateState({ + status: "error", + checkedAt: new Date().toISOString(), + error: friendly, + }); if (!manualUpdateCheck) return; manualUpdateCheck = false; - dialog.showErrorBox("Could not update SketchForge", error instanceof Error ? error.message : String(error)); + dialog.showErrorBox(`${APP_DISPLAY_NAME} güncellenemedi`, friendly); }); setTimeout(() => void checkForDesktopUpdates(false), 4_000).unref(); setInterval(() => void checkForDesktopUpdates(false), 6 * 60 * 60 * 1000).unref(); } +function updateTrayMenu() { + if (!tray) return; + const visible = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()); + tray.setContextMenu( + Menu.buildFromTemplate([ + { + label: visible ? "Sistem Tepsisine Küçült" : `${APP_DISPLAY_NAME}'yu Göster`, + click: () => { + if (visible) { + hideToTrayWindow(); + } else { + showMainWindow(); + } + }, + }, + { type: "separator" }, + { + label: "Kapatınca Gizli Simgelerde Tut", + type: "checkbox", + checked: Boolean(desktopPrefs.closeToTray), + click: (menuItem) => { + saveDesktopPrefs({ closeToTray: Boolean(menuItem.checked) }); + }, + }, + downloadedUpdateReady + ? { + label: "Güncellemeyi Kur ve Yeniden Başlat", + click: installDownloadedUpdate, + } + : { + label: "Güncellemeleri Denetle…", + click: () => void checkForDesktopUpdates(true), + }, + { type: "separator" }, + { + label: "Tamamen Çıkış Yap", + click: () => { + if (downloadedUpdateReady) { + installDownloadedUpdate(); + return; + } + requestForceQuit(); + }, + }, + ]), + ); +} + function createTray() { if (tray) return; - const icon = nativeImage.createFromPath(appIconPath()).resize({ width: 20, height: 20 }); - tray = new Tray(icon); - tray.setToolTip("SketchForge"); - tray.setContextMenu(Menu.buildFromTemplate([ - { - label: "Open SketchForge", - click: showMainWindow, - }, - { - label: "Check for Updates", - click: () => void checkForDesktopUpdates(true), - }, - { type: "separator" }, - { - label: "Quit SketchForge", - click: () => { - if (downloadedUpdateReady) { - installDownloadedUpdate(); - return; - } - isQuitting = true; - app.quit(); - }, - }, - ])); + tray = new Tray(createTrayImage()); + tray.setToolTip(APP_DISPLAY_NAME); + updateTrayMenu(); tray.on("click", showMainWindow); + tray.on("double-click", showMainWindow); } function createMainWindow(url) { const appOrigin = new URL(url).origin; const iconPath = appIconPath(); + const initialState = loadSavedWindowState(); mainWindow = new BrowserWindow({ - width: 1500, - height: 960, + x: initialState.x, + y: initialState.y, + width: initialState.width, + height: initialState.height, minWidth: 1100, minHeight: 700, show: false, - title: "SketchForge", + backgroundColor: "#060810", + title: APP_DISPLAY_NAME, icon: iconPath, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true, + spellcheck: false, + devTools: !app.isPackaged || Boolean(devUrl), preload: path.join(__dirname, "preload.cjs"), }, }); - mainWindow.removeMenu(); + if (initialState.isMaximized) { + mainWindow.maximize(); + } + + mainWindow.on("resize", scheduleWindowStateSave); + mainWindow.on("move", scheduleWindowStateSave); + mainWindow.on("maximize", scheduleWindowStateSave); + mainWindow.on("unmaximize", scheduleWindowStateSave); + mainWindow.on("show", updateTrayMenu); + mainWindow.on("hide", updateTrayMenu); + mainWindow.on("enter-full-screen", () => { + if (desktopMenuBuilt) buildNativeApplicationMenu(); + }); + mainWindow.on("leave-full-screen", () => { + if (desktopMenuBuilt) buildNativeApplicationMenu(); + }); + + mainWindow.on("app-command", (event, cmd) => { + if (cmd === "browser-backward" || cmd === "browser-forward" || cmd === "browser-refresh") { + event.preventDefault(); + } + }); + + mainWindow.webContents.on("before-input-event", (event, input) => { + if (input.type !== "keyDown") return; + const key = String(input.key || "").toLowerCase(); + const ctrlOrMeta = Boolean(input.control || input.meta); + + // Block web browser navigation/refresh hotkeys inside desktop CAD runtime. + if ( + key === "f5" || + (ctrlOrMeta && key === "r") || + (ctrlOrMeta && key === "l") || + (input.alt && (key === "arrowleft" || key === "arrowright")) || + (app.isPackaged && !devUrl && (key === "f12" || (ctrlOrMeta && input.shift && key === "i") || (ctrlOrMeta && key === "u"))) + ) { + event.preventDefault(); + } + }); + + mainWindow.webContents.on("context-menu", (_event, params) => { + if (!params.isEditable) return; + const editableMenu = Menu.buildFromTemplate([ + { role: "undo", label: "Geri Al", enabled: params.editFlags.canUndo }, + { role: "redo", label: "Yinele", enabled: params.editFlags.canRedo }, + { type: "separator" }, + { role: "cut", label: "Kes", enabled: params.editFlags.canCut }, + { role: "copy", label: "Kopyala", enabled: params.editFlags.canCopy }, + { role: "paste", label: "Yapıştır", enabled: params.editFlags.canPaste }, + { type: "separator" }, + { role: "selectAll", label: "Tümünü Seç", enabled: params.editFlags.canSelectAll }, + ]); + editableMenu.popup({ window: mainWindow ?? undefined }); + }); mainWindow.webContents.setWindowOpenHandler(({ url: targetUrl }) => { try { const target = new URL(targetUrl); - if (target.origin === appOrigin) return { action: "allow" }; - if (target.protocol === "http:" || target.protocol === "https:") { + if (target.origin === appOrigin) { + if (target.pathname === "/login.php") { + void startYakNetDesktopLogin(); + return { action: "deny" }; + } + if (target.pathname === "/logout.php") { + void logoutYakNetDesktop(); + return { action: "deny" }; + } + return { action: "allow" }; + } + if (isAllowedExternalUrl(targetUrl)) { void shell.openExternal(targetUrl); } } catch { @@ -322,9 +2215,21 @@ function createMainWindow(url) { mainWindow.webContents.on("will-navigate", (event, targetUrl) => { try { const target = new URL(targetUrl); - if (target.origin === appOrigin) return; + if (target.origin === appOrigin) { + if (target.pathname === "/login.php") { + event.preventDefault(); + void startYakNetDesktopLogin(); + return; + } + if (target.pathname === "/logout.php") { + event.preventDefault(); + void logoutYakNetDesktop(); + return; + } + return; + } event.preventDefault(); - if (target.protocol === "http:" || target.protocol === "https:") { + if (isAllowedExternalUrl(targetUrl)) { void shell.openExternal(targetUrl); } } catch { @@ -332,28 +2237,97 @@ function createMainWindow(url) { } }); + mainWindow.webContents.on("render-process-gone", (_event, details) => { + if (isQuitting || details.reason === "clean-exit") return; + const choice = dialog.showMessageBoxSync(mainWindow ?? undefined, { + type: "error", + buttons: ["Çalışma Alanını Yeniden Başlat", "Uygulamayı Kapat"], + defaultId: 0, + cancelId: 1, + title: `${APP_DISPLAY_NAME} Kurtarma`, + message: "Grafik işleme motoru beklenmedik şekilde sonlandı.", + detail: `Neden: ${details.reason}. Yerel projenizi geri yüklemek için yeniden başlatabilirsiniz.`, + }); + if (choice === 0 && mainWindow && !mainWindow.isDestroyed()) { + mainWindow.reload(); + } else { + explicitQuit = true; + isQuitting = true; + app.quit(); + } + }); + mainWindow.once("ready-to-show", () => { mainWindow?.show(); + updateTrayMenu(); }); mainWindow.on("close", (event) => { + saveWindowStateImmediate(); if (isQuitting) return; + + if (!explicitQuit && desktopPrefs.closeToTray) { + event.preventDefault(); + hideToTrayWindow({ showBalloonOnce: true }); + return; + } + + if (!isDocumentDirty) { + isQuitting = true; + return; + } + event.preventDefault(); - mainWindow?.hide(); + if (closePromptOpen) return; + closePromptOpen = true; + showMainWindow(); + + void dialog + .showMessageBox(mainWindow, { + type: "warning", + buttons: ["Kaydet ve Çık (.skf)", "Kaydetmeden Çık", "İptal"], + defaultId: 0, + cancelId: 2, + noLink: true, + title: `Kaydedilmemiş Değişiklikler — ${APP_DISPLAY_NAME}`, + message: "Açık projede veya disk dosyasında kaydedilmemiş değişiklikler var.", + detail: "Çıkmadan önce .skf proje dosyasına kaydetmek ister misiniz?", + }) + .then(({ response }) => { + closePromptOpen = false; + if (response === 0) { + mainWindow?.webContents.send("snapcad:menu-command", "file:save-and-quit"); + } else if (response === 1) { + isDocumentDirty = false; + explicitQuit = true; + isQuitting = true; + mainWindow?.destroy(); + app.quit(); + } else { + explicitQuit = false; + } + }) + .catch(() => { + closePromptOpen = false; + explicitQuit = false; + }); }); mainWindow.on("closed", () => { mainWindow = null; + updateTrayMenu(); }); void mainWindow.loadURL(url); } async function startDesktop() { - Menu.setApplicationMenu(null); + loadDesktopPrefs(); + loadDesktopAuthSession(); + buildNativeApplicationMenu(); try { - const url = devUrl || await startPackagedWebServer(); + const url = devUrl || (await startPackagedWebServer()); setupDesktopIpc(); createTray(); createMainWindow(url); @@ -362,22 +2336,38 @@ async function startDesktop() { const message = error instanceof Error ? error.message : String(error); const detail = webServerOutput.trim(); dialog.showErrorBox( - "SketchForge could not start", + `${APP_DISPLAY_NAME} başlatılamadı`, detail ? `${message}\n\n${detail}` : message, ); app.quit(); } } +pendingOpenFilePath = extractSkfFilePathFromArgv(process.argv); + const hasSingleInstanceLock = app.requestSingleInstanceLock(); if (!hasSingleInstanceLock) { app.quit(); } else { - app.on("second-instance", showMainWindow); + app.on("second-instance", (_event, commandLine) => { + showMainWindow(); + const candidate = extractSkfFilePathFromArgv(commandLine); + if (candidate) { + deliverOrQueueSkfOpen(candidate); + } + }); + + app.on("open-file", (event, filePath) => { + event.preventDefault(); + if (filePath && filePath.toLowerCase().endsWith(".skf")) { + deliverOrQueueSkfOpen(filePath); + } + }); app.whenReady().then(() => { - if (process.platform === "win32") app.setAppUserModelId("com.sketchforge.desktop"); + app.setName(APP_DISPLAY_NAME); + if (process.platform === "win32") app.setAppUserModelId(DESKTOP_APP_ID); void startDesktop(); app.on("activate", () => { @@ -392,10 +2382,22 @@ if (!hasSingleInstanceLock) { app.on("before-quit", () => { isQuitting = true; + closePendingOAuthServer(); + saveWindowStateImmediate(); stopPackagedWebServer(); + if (tray) { + try { + tray.destroy(); + } catch { + // Ignore tray teardown errors during shutdown. + } + tray = null; + } }); app.on("window-all-closed", () => { - // Keep SketchForge available from the system tray. Use Quit SketchForge - // from the tray menu when the user wants to fully stop the application. + if (downloadedUpdateReady) return; + if (process.platform !== "darwin") { + app.quit(); + } }); diff --git a/apps/desktop/preload.cjs b/apps/desktop/preload.cjs index 7a77a05..b5de2c7 100644 --- a/apps/desktop/preload.cjs +++ b/apps/desktop/preload.cjs @@ -1,7 +1,81 @@ const { contextBridge, ipcRenderer } = require("electron"); -contextBridge.exposeInMainWorld("sketchforgeDesktop", { +function toUint8Array(data) { + if (data instanceof Uint8Array) return data; + if (data instanceof ArrayBuffer) return new Uint8Array(data); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + } + return new Uint8Array(0); +} + +function subscribeChannel(channel, transform) { + return (listener) => { + if (typeof listener !== "function") return () => {}; + const wrapped = (_event, payload) => { + listener(transform ? transform(payload) : payload); + }; + ipcRenderer.on(channel, wrapped); + return () => { + ipcRenderer.removeListener(channel, wrapped); + }; + }; +} + +function normalizeOpenedFile(payload) { + if (!payload || typeof payload.filePath !== "string" || typeof payload.fileName !== "string") { + return null; + } + return { + filePath: payload.filePath, + fileName: payload.fileName, + bytes: toUint8Array(payload.bytes), + }; +} + +const desktopBridge = Object.freeze({ + isDesktop: true, + platform: process.platform, getVersion: () => ipcRenderer.invoke("sketchforge:get-version"), checkForUpdates: () => ipcRenderer.invoke("sketchforge:check-for-updates"), installUpdate: () => ipcRenderer.invoke("sketchforge:install-update"), + getUpdateState: () => ipcRenderer.invoke("snapcad:get-update-state"), + onUpdateState: subscribeChannel("snapcad:update-state"), + getDesktopPrefs: () => ipcRenderer.invoke("snapcad:get-desktop-prefs"), + setDesktopPrefs: (patch) => + ipcRenderer.invoke("snapcad:set-desktop-prefs", patch && typeof patch === "object" ? patch : {}), + hideToTray: () => ipcRenderer.invoke("snapcad:hide-to-tray"), + onDesktopPrefsChanged: subscribeChannel("snapcad:prefs-changed"), + startYakNetLogin: () => ipcRenderer.invoke("snapcad:yaknet-login"), + logoutYakNet: () => ipcRenderer.invoke("snapcad:yaknet-logout"), + cloudRequest: (options) => + ipcRenderer.invoke("snapcad:cloud-request", options && typeof options === "object" ? options : {}), + onAuthUpdated: subscribeChannel("snapcad:auth-updated"), + openSkfDialog: async () => normalizeOpenedFile(await ipcRenderer.invoke("snapcad:open-skf-dialog")), + saveSkfDialog: (options) => + ipcRenderer.invoke("snapcad:save-skf-dialog", { + defaultFileName: options?.defaultFileName, + targetPath: options?.targetPath ?? null, + forceDialog: Boolean(options?.forceDialog), + bytes: toUint8Array(options?.bytes), + }), + saveExportFileDialog: (options) => + ipcRenderer.invoke("snapcad:save-export-dialog", { + defaultFileName: options?.defaultFileName, + filters: Array.isArray(options?.filters) ? options.filters : undefined, + bytes: toUint8Array(options?.bytes), + }), + consumePendingOpenFile: async () => + normalizeOpenedFile(await ipcRenderer.invoke("snapcad:consume-pending-open-file")), + onOpenFile: subscribeChannel("snapcad:open-file", normalizeOpenedFile), + onMenuCommand: subscribeChannel("snapcad:menu-command"), + setMenuState: (state) => + ipcRenderer.invoke("snapcad:set-menu-state", state && typeof state === "object" ? state : {}), + setDirty: (dirty) => ipcRenderer.invoke("snapcad:set-dirty", Boolean(dirty)), + setWindowTitle: (title) => ipcRenderer.invoke("snapcad:set-window-title", String(title ?? "")), + confirmCloseAfterSave: () => ipcRenderer.invoke("snapcad:confirm-close-after-save"), + openExternal: (url) => ipcRenderer.invoke("snapcad:open-external", String(url ?? "")), }); + +contextBridge.exposeInMainWorld("snapcadDesktop", desktopBridge); +contextBridge.exposeInMainWorld("sketchforgeDesktop", desktopBridge); diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index e64168d..e53dcf1 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,8 +1,28 @@ import type { NextConfig } from "next"; +import fs from "node:fs"; import path from "node:path"; +function readRootAppVersion(): string { + const candidates = [ + path.resolve(process.cwd(), "package.json"), + path.resolve(process.cwd(), "..", "..", "package.json"), + ]; + for (const candidate of candidates) { + try { + const parsed = JSON.parse(fs.readFileSync(candidate, "utf8")) as { version?: unknown }; + if (typeof parsed.version === "string" && parsed.version.trim()) { + return parsed.version.trim(); + } + } catch { + // Ignore missing or unreadable package.json candidate. + } + } + return "1.0.10"; +} + const isStaticExport = process.env.STATIC_EXPORT === "true"; const isDockerBuild = process.env.SKETCHFORGE_DOCKER_BUILD === "true"; +const appVersion = readRootAppVersion(); const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "") .split(",") .map((origin) => origin.trim()) @@ -18,6 +38,7 @@ const nextConfig: NextConfig = { allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins], env: { NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false", + NEXT_PUBLIC_APP_VERSION: appVersion, }, images: { unoptimized: true diff --git a/apps/web/public/.htaccess b/apps/web/public/.htaccess index 566b9ed..de0741a 100644 --- a/apps/web/public/.htaccess +++ b/apps/web/public/.htaccess @@ -6,6 +6,8 @@ ServerSignature Off AddType application/wasm .wasm AddType application/javascript .js .mjs AddType image/svg+xml .svg + AddType text/yaml .yml + AddType application/octet-stream .exe .blockmap @@ -26,8 +28,8 @@ ServerSignature Off -# Service worker ve manifest güncellemeleri tarayıcıda takılı kalmasın. - +# Service worker, manifest ve masaüstü güncelleme bildirimleri önbellekte takılı kalmasın. + Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" diff --git a/apps/web/public/assets/sketchforge/sketchforge-logo.ico b/apps/web/public/assets/sketchforge/sketchforge-logo.ico new file mode 100644 index 0000000000000000000000000000000000000000..cb78c2832069e4096a3e2ff0cde11f313f8610ee GIT binary patch literal 77106 zcmbTdWl$YKw*`6*?k)#+cL*BX-GaNjyK`^|?(P02&<3=b7Z@!}zlTx~fWv0%|4+Pd)*ZrHFzE08k%~_-g!V0|4Gh zTH6%>KV!1K;C}8SjR|2yx=AFX1ZlL~+GMd7t?=BJaftv5d?nK4nUaBBc<=O? zFLeL@$d!bDlt8EZxTuJG8ngfG~8|d;T8%erxfHD*?t1`N!c}|zTJ{|ZD*r|Bq7(N)RJ^QAtpHG? zjpSrrMj|PL|LUlt+)i!d!`K+>;?;iSRB%qIH<>tgkOoxCqD6JtL>hqT>+saBI{oG3 z1hTquD>&%Kt4RF-ru6sAnFOCkViw`EK9a}QUk_y{QJX)R_gvGnh2_%oVzMn9crQo~ zEyP&-s5$)^?AVkOrS*vVgWe}(WZx(Ba|Q!sBoxJKM2&*~U%2qe8UWV+a3MB|=#x_a zcP>DF`!5$_Q|+w?B|t+yMuwcz9SkKGZxUXO0bUdB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mR%{$&f&M|qYy8W&(q4(QOh)SSeuD+C zo?mM&E9(+uHvFD`;AQ*^9?@aA@~SSP2|f&G@X!}y(4oM?R@h&4x>+vps5(|U4Id5u zj5s+4qKtty`efs#UyLijWZWs5JU;R{(>8t#2fk{@DcaR0BmR{Z#SF<_$5&ie*b=^J zu!A_LF-AIQT&)&b7OTKFbhgq#W2`14$qwQb8EqyQ6S z1s@v&Op|9xKd2=8)rFl>9Ht@L#+%C*>h*|kKY_#AjTUbY1n zHe^_)1%EhQ$dGL~re!gbd}99P`MOUwt`GmM%q=b~-1B$Pg|V7|5r$6y0000 {children} - + ); diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 473e984..7f2cbd8 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -41,8 +41,11 @@ import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceF import { hydrateProjectShapeState, reconcileLoadedProjectShapeCacheEntry, type ImportedMeshResource } from "@/lib/projectShapePersistence"; import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; import { importExtensionSupported } from "@/lib/importExtensions"; +import { cloudApiFetch } from "@/lib/cloudApi"; import { speakTurkish } from "@/lib/accessibility"; +import { dispatchDesktopMenuCommand, formatFriendlyUpdateError, getDesktopBridge, isEditorOnlyMenuAction, sanitizeDesktopTitle, useIsDesktopRuntime } from "@/lib/desktopBridge"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; +import type { DesktopMenuAction, DesktopOpenedFile, DesktopPreferences, DesktopUpdateResult } from "@/types/desktop"; import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; type AppView = "dashboard" | "editor"; @@ -567,6 +570,11 @@ export default function Home() { const dashboardImportInputRef = useRef(null); const nextProjectRevisionRef = useRef(0); const projectShapeSaveQueuesRef = useRef>>({}); + const diskFileByProjectIdRef = useRef>({}); + const [diskFileVersion, setDiskFileVersion] = useState(0); + const [pendingSaveCount, setPendingSaveCount] = useState(0); + const activeProjectIdRef = useRef(null); + const viewRef = useRef("dashboard"); const editorLoadingStartedAtRef = useRef(0); const startEditorTransition = useCallback(() => { @@ -725,6 +733,28 @@ export default function Home() { projectShapesByIdRef.current = projectShapesById; }, [projectShapesById]); + useEffect(() => { + activeProjectIdRef.current = activeProjectId; + }, [activeProjectId]); + + useEffect(() => { + viewRef.current = view; + }, [view]); + + useEffect(() => { + if (!mounted) return; + const bridge = getDesktopBridge(); + if (!bridge) return; + const activeProj = view === "editor" && activeProjectId ? projects.find((project) => project.id === activeProjectId) ?? null : null; + const diskMeta = activeProj ? diskFileByProjectIdRef.current[activeProj.id] : undefined; + const liveRevision = activeProj ? (projectShapesById[activeProj.id]?.revision ?? activeProj.revision ?? activeProj.updatedAt) : 0; + const isDirty = pendingSaveCount > 0 || Boolean(diskMeta && liveRevision > diskMeta.savedRevision); + const titleLabel = activeProj ? diskMeta?.fileName ?? activeProj.name : document.title; + void bridge.setDirty?.(isDirty); + void bridge.setWindowTitle?.(sanitizeDesktopTitle(titleLabel, isDirty)); + void bridge.setMenuState?.({ inEditor: view === "editor" }); + }, [activeProjectId, dashboardSection, diskFileVersion, mounted, pendingSaveCount, projectShapesById, projects, view]); + useEffect(() => { if (!mounted) return; void refreshSharedProjects(); @@ -1062,6 +1092,7 @@ export default function Home() { }; const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapesWhenIdle(snapshot.projectId, entry, saveContext)); projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave; + setPendingSaveCount((count) => count + 1); void queuedSave .then(() => { @@ -1079,6 +1110,7 @@ export default function Home() { } }) .finally(() => { + setPendingSaveCount((count) => Math.max(0, count - 1)); if (projectShapeSaveQueuesRef.current[snapshot.projectId] === queuedSave) { delete projectShapeSaveQueuesRef.current[snapshot.projectId]; } @@ -1140,7 +1172,8 @@ export default function Home() { }, []); const createAndOpenProject = (name?: string, challengeTutorial: ChallengeTutorialId | null = null, initialShapes: WorkplaneShape[] = []) => { - const project = newProject(name ?? `Adsız Tasarım ${projects.length + 1}`, projects.length, initialShapes.length); + const existingCount = Math.max(projectsRef.current.length, projects.length); + const project = newProject(name ?? `Adsız Tasarım ${existingCount + 1}`, existingCount, initialShapes.length); const initialEntry = projectShapeCacheEntry(project.revision ?? project.updatedAt, initialShapes); setProjectShapesById((current) => ({ ...current, @@ -1164,13 +1197,17 @@ export default function Home() { setDashboardNotice(message); }, []); - const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => { + const openSkfProjectFromFile = useCallback(async ( + file: File, + sharedProject?: SharedProject, + desktopDiskMeta?: { filePath: string; fileName: string }, + ) => { setDashboardNotice(`${file.name} yeni proje olarak açılmadan önce doğrulanıyor`); try { const restored = await importSkfProject(await file.arrayBuffer()); const now = Date.now(); const project: DashboardProject = { - ...newProject(restored.projectName, projects.length, restored.shapes.length), + ...newProject(restored.projectName, projectsRef.current.length, restored.shapes.length), createdAt: restored.createdAt, updatedAt: now, revision: now, @@ -1184,6 +1221,14 @@ export default function Home() { const entry = projectShapeCacheEntry(now, restored.shapes, restored.history, restored.historyIndex, restored.assets); await saveProjectShapes(project.id, entry, projectShapeSaveContext(project)); setProjectShapesById((current) => ({ ...current, [project.id]: entry })); + if (desktopDiskMeta) { + diskFileByProjectIdRef.current[project.id] = { + filePath: desktopDiskMeta.filePath, + fileName: desktopDiskMeta.fileName, + savedRevision: now, + }; + setDiskFileVersion((version) => version + 1); + } setProjects((current) => [project, ...current]); announceDashboardNotice(sharedProject ? `${sharedProject.name} paylaşılan projesi açıldı; paylaşılan alana geri kaydedene kadar değişiklikler yerel olarak saklanır` : `${file.name} düzenlenebilir yeni bir yerel proje olarak açıldı`, 20000); openEditor(project.id, { allowMissingFromStorage: true, preserveNotice: true }); @@ -1193,7 +1238,281 @@ export default function Home() { setDashboardNotice(message); return { ok: false, message }; } - }, [projects.length]); + }, [announceDashboardNotice]); + + const openSkfFromDesktopPayload = useCallback( + async (opened: DesktopOpenedFile | null) => { + if (!opened) return; + const copy = new Uint8Array(opened.bytes.byteLength); + copy.set(opened.bytes); + const file = new File([copy.buffer], opened.fileName, { type: "application/vnd.sketchforge.project+zip" }); + await openSkfProjectFromFile(file, undefined, { filePath: opened.filePath, fileName: opened.fileName }); + }, + [openSkfProjectFromFile], + ); + + const saveActiveProjectToDisk = useCallback(async ({ forceDialog = false, quitAfterSave = false }: { forceDialog?: boolean; quitAfterSave?: boolean } = {}) => { + const bridge = getDesktopBridge(); + if (!bridge?.saveSkfDialog) return; + const currentProjectId = activeProjectIdRef.current; + const currentProject = currentProjectId ? projectsRef.current.find((project) => project.id === currentProjectId) ?? null : null; + if (!currentProject || viewRef.current !== "editor") { + if (quitAfterSave) { + await bridge.confirmCloseAfterSave?.(); + } else { + setDashboardNotice("Kaydetmek için önce bir 3B proje açın"); + } + return; + } + + try { + window.dispatchEvent(new CustomEvent("snapcad:flush-project-sync")); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + + let entry = projectShapesByIdRef.current[currentProject.id]; + if (!entry) { + const loaded = await loadProjectShapes(currentProject.id); + entry = projectShapeCacheEntry( + currentProject.revision ?? currentProject.updatedAt, + loaded?.shapes ?? [], + loaded?.history, + loaded?.historyIndex, + loaded?.assets ?? [], + ); + } + const bytes = await exportSkfProject({ + projectId: currentProject.id, + projectName: currentProject.name, + createdAt: currentProject.createdAt, + modifiedAt: Date.now(), + shapes: entry.shapes, + history: entry.history, + historyIndex: entry.historyIndex, + assets: entry.assets, + workspace: normalizeWorkspaceSettings(currentProject.workspace), + snapGrid: normalizeSnapGrid(currentProject.snapGrid), + placementElevation: currentProject.placementElevation ?? 0, + placementWorkplane: normalizePlacementWorkplane(currentProject.placementWorkplane, currentProject.placementElevation), + sketchPlacementWorkplane: normalizePlacementWorkplane(currentProject.sketchPlacementWorkplane), + }); + + const existingDiskMeta = diskFileByProjectIdRef.current[currentProject.id]; + const safeFileBase = currentProject.name.replace(/[\\/:*?"<>|]/g, "_").trim() || "snapcad-proje"; + const result = await bridge.saveSkfDialog({ + defaultFileName: existingDiskMeta?.fileName ?? `${safeFileBase}.skf`, + targetPath: existingDiskMeta?.filePath ?? null, + forceDialog, + bytes, + }); + + if (result.canceled) { + return; + } + if (result.error) { + setDashboardNotice(result.error); + return; + } + if (result.filePath) { + const latestRev = projectShapesByIdRef.current[currentProject.id]?.revision ?? currentProject.revision ?? currentProject.updatedAt; + diskFileByProjectIdRef.current[currentProject.id] = { + filePath: result.filePath, + fileName: result.fileName ?? `${safeFileBase}.skf`, + savedRevision: latestRev, + }; + setDiskFileVersion((version) => version + 1); + setDashboardNotice(`Proje kaydedildi: ${result.fileName ?? result.filePath}`); + if (quitAfterSave) { + await bridge.confirmCloseAfterSave?.(); + } + } + } catch (error) { + setDashboardNotice(error instanceof Error ? error.message : "Proje diske kaydedilemedi"); + } + }, []); + + useEffect(() => { + if (!mounted) return; + const bridge = getDesktopBridge(); + if (!bridge) return; + + void bridge.consumePendingOpenFile?.().then((pending) => { + if (pending) { + void openSkfFromDesktopPayload(pending); + } + }); + + const unsubOpenFile = bridge.onOpenFile?.((opened) => { + void openSkfFromDesktopPayload(opened); + }); + + const unsubMenu = bridge.onMenuCommand?.((action) => { + switch (action) { + case "file:new": + createAndOpenProject(); + break; + case "file:open": + void bridge.openSkfDialog?.().then((opened) => { + if (opened) { + void openSkfFromDesktopPayload(opened); + } + }); + break; + case "file:save": + void saveActiveProjectToDisk({ forceDialog: false }); + break; + case "file:save-as": + void saveActiveProjectToDisk({ forceDialog: true }); + break; + case "file:save-and-quit": + void saveActiveProjectToDisk({ forceDialog: false, quitAfterSave: true }); + break; + case "file:import": + if (viewRef.current === "dashboard") { + dashboardImportInputRef.current?.click(); + } else { + dispatchDesktopMenuCommand(action); + } + break; + case "file:dashboard": + setView("dashboard"); + navigateToDashboardSection("home"); + break; + case "window:drawing": + setView("dashboard"); + setActiveDrawingPresetId(null); + navigateToDashboardSection("drawing"); + break; + case "window:circuits": + setView("dashboard"); + setActiveCircuitTemplateId(null); + navigateToDashboardSection("circuits"); + break; + case "window:codeblocks": + setView("dashboard"); + setActiveCodeblockTemplateId(null); + navigateToDashboardSection("codeblocks"); + break; + case "window:classrooms": + setView("dashboard"); + navigateToDashboardSection("classrooms"); + break; + case "window:shared": + setView("dashboard"); + navigateToDashboardSection("shared"); + void refreshSharedProjects(); + break; + case "window:challenges": + setView("dashboard"); + navigateToDashboardSection("challenges"); + break; + case "window:customization": + setView("dashboard"); + navigateToDashboardSection("customization"); + break; + case "window:about": + setView("dashboard"); + navigateToDashboardSection("about"); + break; + case "window:contact": + setView("dashboard"); + navigateToDashboardSection("contact"); + break; + case "window:kvkk": + setView("dashboard"); + navigateToDashboardSection("kvkk"); + break; + case "window:terms": + setView("dashboard"); + navigateToDashboardSection("terms"); + break; + case "window:security": + setView("dashboard"); + navigateToDashboardSection("security"); + break; + case "window:command-palette": + window.dispatchEvent(new CustomEvent("snapcad:open-command-palette")); + break; + case "window:a11y": + window.dispatchEvent(new CustomEvent("snapcad:open-a11y-drawer")); + break; + case "window:settings": + setView("dashboard"); + setSettingsOpen(true); + break; + case "help:shortcuts": + if (viewRef.current === "editor") { + dispatchDesktopMenuCommand(action); + } else { + const shortcutNotice = + "3B Editör kısayolları bir 3B proje açıldığında kullanılabilir. Genel kısayollar: Ctrl+K Hızlı Komut Paleti, Alt+A Erişilebilirlik Menüsü."; + setDashboardNotice(shortcutNotice); + speakTurkish(shortcutNotice); + } + break; + case "edit:undo": + case "edit:redo": + case "edit:cut": + case "edit:copy": + case "edit:paste": + case "edit:select-all": { + if (viewRef.current !== "editor") { + const activeEl = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const isEditableTextTarget = Boolean( + activeEl && + (activeEl.isContentEditable || + activeEl.tagName === "TEXTAREA" || + (activeEl.tagName === "INPUT" && + !["checkbox", "radio", "button", "submit", "reset", "file", "range", "color"].includes( + (activeEl as HTMLInputElement).type.toLowerCase(), + ))), + ); + const hasSelection = action === "edit:copy" && Boolean(window.getSelection()?.toString()); + if (isEditableTextTarget || hasSelection) { + const execCommandMap: Partial> = { + "edit:undo": "undo", + "edit:redo": "redo", + "edit:cut": "cut", + "edit:copy": "copy", + "edit:paste": "paste", + "edit:select-all": "selectAll", + }; + const cmd = execCommandMap[action]; + if (cmd) { + try { + document.execCommand(cmd); + } catch { + // Ignore unsupported execCommand calls on non-editable targets. + } + break; + } + } + } + if (isEditorOnlyMenuAction(action) && viewRef.current !== "editor") { + const notice = "Bu işlem 3B Tasarım Stüdyosu içinde aktiftir; önce bir 3B proje açın veya oluşturun."; + setDashboardNotice(notice); + speakTurkish(notice); + break; + } + dispatchDesktopMenuCommand(action); + break; + } + default: + if (isEditorOnlyMenuAction(action) && viewRef.current !== "editor") { + const notice = "Bu işlem 3B Tasarım Stüdyosu içinde aktiftir; önce bir 3B proje açın veya oluşturun."; + setDashboardNotice(notice); + speakTurkish(notice); + break; + } + dispatchDesktopMenuCommand(action); + break; + } + }); + + return () => { + unsubOpenFile?.(); + unsubMenu?.(); + }; + }, [mounted, navigateToDashboardSection, openSkfFromDesktopPayload, refreshSharedProjects, saveActiveProjectToDisk]); const openSharedProject = useCallback(async (sharedProject: SharedProject) => { setDashboardNotice(`${sharedProject.name} paylaşılan projesi açılıyor`); @@ -1282,10 +1601,11 @@ export default function Home() { const isObj = sourceFormat === "obj"; const isSvg = sourceFormat === "svg"; const isStep = sourceFormat === "step"; + const isIfc = sourceFormat === "ifc"; const isDxf = sourceFormat === "dxf"; const isDwg = sourceFormat === "dwg"; const isGlb = sourceFormat === "glb"; - if (!sourceFormat || (!isSvg && !isStep && !isDxf && !isDwg && !isGlb && !importExtensionSupported(file.name))) { + if (!sourceFormat || (!isSvg && !isStep && !isIfc && !isDxf && !isDwg && !isGlb && !importExtensionSupported(file.name))) { failures.push({ fileName: file.name, reason: "Desteklenmeyen dosya türü" }); continue; } @@ -1296,17 +1616,19 @@ export default function Home() { const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; const parsedShape = isStep ? await import("@/lib/stepImport").then(({ importedShapeFromStep }) => importedShapeFromStep(file.name, buffer)) - : isObj - ? importedShapeFromObj(file.name, new TextDecoder().decode(bytes)) - : isSvg - ? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes)) - : isDxf - ? await import("@/lib/dxfImport").then(({ importedShapeFromDxf }) => importedShapeFromDxf(file.name, new TextDecoder().decode(bytes))) - : isDwg - ? await import("@/lib/dwgKernel").then(({ importedShapeFromDwg }) => importedShapeFromDwg(file.name, bytes)) - : isGlb - ? await import("@/lib/glbImport").then(({ importedShapeFromGlb }) => importedShapeFromGlb(file.name, buffer)) - : importedShapeFromStl(file.name, buffer); + : isIfc + ? await import("@/lib/ifcImport").then(({ importedShapeFromIfc }) => importedShapeFromIfc(file.name, bytes)) + : isObj + ? importedShapeFromObj(file.name, new TextDecoder().decode(bytes)) + : isSvg + ? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes)) + : isDxf + ? await import("@/lib/dxfImport").then(({ importedShapeFromDxf }) => importedShapeFromDxf(file.name, new TextDecoder().decode(bytes))) + : isDwg + ? await import("@/lib/dwgKernel").then(({ importedShapeFromDwg }) => importedShapeFromDwg(file.name, bytes)) + : isGlb + ? await import("@/lib/glbImport").then(({ importedShapeFromGlb }) => importedShapeFromGlb(file.name, buffer)) + : importedShapeFromStl(file.name, buffer); const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type); importedShapes.push(attachProjectAsset(parsedShape, asset.id)); importedAssets.push(asset); @@ -1402,7 +1724,7 @@ export default function Home() { setDashboardNotice("Could not delete project shapes from local storage"); }); // YakNet Bulut veritabanından da sil - void fetch("/cloud-api.php?action=delete", { + void cloudApiFetch("/cloud-api.php?action=delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "delete", project_uid: projectId }), @@ -1579,7 +1901,7 @@ export default function Home() { project_json: { shapes }, thumbnail_data_url: proj.thumbnailUrl || null, }; - const res = await fetch("/cloud-api.php?action=classroom_submit_project", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_submit_project", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), @@ -1614,7 +1936,7 @@ export default function Home() { className="hidden-file-input" type="file" multiple - accept=".skf,.SKF,.dwg,.DWG,.dxf,.DXF,.step,.STEP,.stp,.STP,.stl,.STL,.obj,.OBJ,.glb,.GLB,.gltf,.GLTF,.svg,.SVG" + accept=".skf,.SKF,.ifc,.IFC,.dwg,.DWG,.dxf,.DXF,.step,.STEP,.stp,.STP,.stl,.STL,.obj,.OBJ,.glb,.GLB,.gltf,.GLTF,.svg,.SVG" onChange={(event) => { const files = event.currentTarget.files ? Array.from(event.currentTarget.files) : []; if (files.length) { @@ -2018,6 +2340,8 @@ function Dashboard({ const [projectPendingRenameId, setProjectPendingRenameId] = useState(null); const [projectNameDraft, setProjectNameDraft] = useState(""); const [updateStatus, setUpdateStatus] = useState(null); + const [desktopUpdateState, setDesktopUpdateState] = useState(null); + const [desktopPrefs, setDesktopPrefs] = useState({ closeToTray: true }); const [desktopAppVersion, setDesktopAppVersion] = useState(null); const [desktopUpdaterConnected, setDesktopUpdaterConnected] = useState(false); const [updateChecking, setUpdateChecking] = useState(false); @@ -2029,6 +2353,7 @@ function Dashboard({ const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null; const sharedProjectPendingDelete = sharedProjects.find((project) => project.fileName === sharedProjectPendingDeleteFileName) ?? null; const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null; + const isDesktopRuntime = useIsDesktopRuntime(); const dashboardMainRef = useRef(null); const [sectionAnnouncement, setSectionAnnouncement] = useState(""); const isFirstSectionRender = useRef(true); @@ -2067,10 +2392,78 @@ function Dashboard({ }, [dashboardSection]); useEffect(() => { - const desktop = window.sketchforgeDesktop; + const desktop = getDesktopBridge(); if (!desktop) return; setDesktopUpdaterConnected(true); void desktop.getVersion().then(setDesktopAppVersion).catch(() => undefined); + void desktop.getDesktopPrefs?.().then((prefs) => { + if (prefs && typeof prefs.closeToTray === "boolean") { + setDesktopPrefs(prefs); + } + }).catch(() => undefined); + void desktop.getUpdateState?.().then((state) => { + if (!state) return; + setDesktopUpdateState(state); + setDesktopAppVersion(state.currentVersion); + setUpdateStatus({ + currentVersion: state.currentVersion, + latestVersion: state.latestVersion, + updateAvailable: state.updateAvailable, + checkedAt: state.checkedAt, + updateUrl: "", + installationReady: true, + requiresUpdateKey: false, + updateMode: "desktop", + status: state.status, + downloaded: state.downloaded, + progressPercent: state.progressPercent, + checkError: state.error ? formatFriendlyUpdateError(state.error) : undefined, + }); + }).catch(() => undefined); + + const unsubPrefs = desktop.onDesktopPrefsChanged?.((prefs) => { + if (prefs && typeof prefs.closeToTray === "boolean") { + setDesktopPrefs(prefs); + } + }); + + const unsubUpdate = desktop.onUpdateState?.((state) => { + setDesktopUpdateState(state); + setDesktopAppVersion(state.currentVersion); + setUpdateStatus({ + currentVersion: state.currentVersion, + latestVersion: state.latestVersion, + updateAvailable: state.updateAvailable, + checkedAt: state.checkedAt, + updateUrl: "", + installationReady: true, + requiresUpdateKey: false, + updateMode: "desktop", + status: state.status, + downloaded: state.downloaded, + progressPercent: state.progressPercent, + checkError: state.error ? formatFriendlyUpdateError(state.error) : undefined, + }); + setUpdateChecking(state.status === "checking"); + if (state.status === "downloading") { + setUpdateStarting(true); + const pct = typeof state.progressPercent === "number" ? state.progressPercent : 0; + setUpdateMessage(`SnapCAD Studio ${state.latestVersion ?? ""} indiriliyor… %${pct}`); + } else if (state.status === "downloaded") { + setUpdateStarting(false); + setUpdateMessage(`SnapCAD Studio ${state.latestVersion ?? ""} kuruluma hazır.`); + } else if (state.status === "error" && state.error) { + setUpdateStarting(false); + setUpdateMessage(formatFriendlyUpdateError(state.error)); + } else if (state.status === "not-available") { + setUpdateStarting(false); + } + }); + + return () => { + unsubPrefs?.(); + unsubUpdate?.(); + }; }, []); useEffect(() => { @@ -2115,16 +2508,17 @@ function Dashboard({ }; const checkForUpdates = useCallback(async (force: boolean, alwaysPrompt: boolean) => { - if (staticExportBuild) return; + const desktop = getDesktopBridge(); + if (staticExportBuild && !desktop) return; setUpdateChecking(true); - setUpdateMessage(""); + if (alwaysPrompt) setUpdateMessage(""); try { - const desktop = window.sketchforgeDesktop; if (desktop) { setDesktopUpdaterConnected(true); const result = await desktop.checkForUpdates(); + setDesktopUpdateState(result); setDesktopAppVersion(result.currentVersion); - if (result.error) throw new Error(result.error); + const friendlyError = result.error ? formatFriendlyUpdateError(result.error) : undefined; const payload: AppUpdateStatus = { currentVersion: result.currentVersion, latestVersion: result.latestVersion, @@ -2134,14 +2528,31 @@ function Dashboard({ installationReady: true, requiresUpdateKey: false, updateMode: "desktop", + status: result.status, + downloaded: result.downloaded, + progressPercent: result.progressPercent, + checkError: friendlyError, }; setUpdateStatus(payload); + if (friendlyError) { + if (alwaysPrompt) setUpdateMessage(friendlyError); + return; + } if (result.updateAvailable && result.latestVersion) { setUpdateMessage( result.downloaded ? `SnapCAD Studio ${result.latestVersion} kuruluma hazır.` : `SnapCAD Studio ${result.latestVersion} mevcut.`, ); + const dismissedVersion = window.localStorage.getItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY); + if (alwaysPrompt || dismissedVersion !== result.latestVersion) { + onCloseSettings(); + setUpdatePromptOpen(true); + } + } else if (result.status === "unsupported") { + if (alwaysPrompt) { + setUpdateMessage("Güncellemeler yalnızca kurulu masaüstü (.exe) uygulamasında denetlenir."); + } } else if (alwaysPrompt) { setUpdateMessage("SnapCAD Studio güncel."); } @@ -2184,16 +2595,23 @@ function Dashboard({ }; const requestUpdate = async () => { - if (!updateStatus?.updateAvailable) return; + const hasUpdate = Boolean(updateStatus?.updateAvailable || desktopUpdateState?.updateAvailable || desktopUpdateState?.downloaded); + if (!hasUpdate) return; - const desktop = window.sketchforgeDesktop; + const desktop = getDesktopBridge(); if (desktop) { setUpdateStarting(true); - setUpdateMessage(`SnapCAD Studio ${updateStatus.latestVersion ?? "update"} indiriliyor…`); + setUpdateMessage( + desktopUpdateState?.downloaded + ? "Kurulum başlatılıyor, uygulama yeniden başlatılacak…" + : `SnapCAD Studio ${updateStatus?.latestVersion ?? desktopUpdateState?.latestVersion ?? ""} indiriliyor…`, + ); try { const result = await desktop.installUpdate(); - if (result.error) throw new Error(result.error); - if (!result.updateAvailable) { + setDesktopUpdateState(result); + const friendlyError = result.error ? formatFriendlyUpdateError(result.error) : undefined; + if (friendlyError) throw new Error(friendlyError); + if (!result.updateAvailable && !result.downloaded) { setUpdateStatus({ currentVersion: result.currentVersion, latestVersion: result.latestVersion, @@ -2203,9 +2621,12 @@ function Dashboard({ installationReady: true, requiresUpdateKey: false, updateMode: "desktop", + status: result.status, + downloaded: false, + progressPercent: 0, }); setUpdateMessage("SnapCAD Studio zaten güncel."); - } else { + } else if (result.downloaded) { setUpdateMessage("Güncelleme indirildi, yeniden başlatılıyor…"); } } catch (error) { @@ -2216,6 +2637,8 @@ function Dashboard({ return; } + if (!updateStatus) return; + if (!updateStatus.installationReady) { window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer"); dismissUpdate(); @@ -2937,7 +3360,7 @@ function Dashboard({ ) : null} - {updatePromptOpen && updateStatus?.updateAvailable && updateStatus.latestVersion ? ( + {updatePromptOpen && (updateStatus?.updateAvailable || desktopUpdateState?.downloaded) && (updateStatus?.latestVersion || desktopUpdateState?.latestVersion) ? (
- SnapCAD Studio {updateStatus.latestVersion} mevcut + + SnapCAD Studio {updateStatus?.latestVersion ?? desktopUpdateState?.latestVersion} mevcut +
-

{updateStatus.currentVersion} sürümünden güncellemek ister misiniz?

+

+ {updateStatus?.currentVersion ?? desktopAppVersion ?? SKF_CREATED_WITH_VERSION} sürümünden güncellemek ister misiniz? +

- Tarayıcıdaki projeleriniz korunur. + {isDesktopRuntime + ? "Yerel projeleriniz ve YakNet oturumunuz korunur." + : "Tarayıcıdaki projeleriniz korunur."}
+ {desktopUpdateState?.status === "downloading" ? ( +
+
+
+ ) : null} {updateMessage ?
{updateMessage}
: null}
@@ -2987,7 +3424,13 @@ function Dashboard({ if (!updateStarting) void requestUpdate(); }} > - {updateStarting ? "Başlatılıyor…" : "Güncelle"} + {desktopUpdateState?.downloaded + ? "Yeniden Başlat ve Kur" + : desktopUpdateState?.status === "downloading" + ? `İndiriliyor… %${desktopUpdateState.progressPercent ?? 0}` + : updateStarting + ? "Başlatılıyor…" + : "İndir ve Kur"}
@@ -3015,24 +3458,134 @@ function Dashboard({ - + {!isDesktopRuntime ? ( + + ) : null} + {isDesktopRuntime ? ( +
+
+ Sistem Tepsisi & Arka Plan + Pencere X tuşundan kapatıldığında uygulama Windows gizli simgelerde açık kalır. +
+ + +
+ ) : null} + {isDesktopRuntime || !staticExportBuild ? ( +
+
+ Yazılım Güncellemeleri + + {desktopUpdaterConnected + ? `Kaynak: ${desktopUpdateState?.feedUrl ?? "https://snap.yakhub.com.tr/updates"}` + : "Sürüm güncellemelerini denetleyin ve uygulayın."} + +
+ {(() => { + const isDownloading = desktopUpdateState?.status === "downloading"; + const isDownloaded = Boolean(desktopUpdateState?.downloaded || updateStatus?.downloaded); + const hasUpdate = Boolean(updateStatus?.updateAvailable || desktopUpdateState?.updateAvailable || isDownloaded); + const errorText = updateStatus?.checkError || (desktopUpdateState?.error ? formatFriendlyUpdateError(desktopUpdateState.error) : ""); + const progressPercent = desktopUpdateState?.progressPercent ?? updateStatus?.progressPercent ?? 0; + + return ( + <> +
+ {isDownloading + ? `Güncelleme indiriliyor… %${progressPercent}` + : isDownloaded + ? `v${updateStatus?.latestVersion ?? desktopUpdateState?.latestVersion ?? ""} kuruluma hazır.` + : hasUpdate + ? `Yeni sürüm mevcut: v${updateStatus?.latestVersion ?? desktopUpdateState?.latestVersion ?? ""}` + : errorText + ? errorText + : desktopUpdateState?.status === "unsupported" + ? "Otomatik güncelleme kurulu .exe paketinde etkindir." + : updateMessage || (updateStatus ? `En güncel sürüm yüklü (v${updateStatus.currentVersion}).` : "Son durum bekleniyor.")} +
+ {isDownloading || isDownloaded ? ( +
+
+
+ ) : null} +
+ + {hasUpdate ? ( + + ) : null} +
+ + ); + })()} +
+ ) : null}
SnapCAD Studio Sürümü {desktopAppVersion ?? updateStatus?.currentVersion ?? SKF_CREATED_WITH_VERSION} diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 0fe634a..2a64421 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -1,6 +1,6 @@ "use client"; -import { Activity, Check, Circle as CircleIcon, CloudUpload, Download, Eye, FolderOpen, Hexagon as HexagonIcon, Square as SquareIcon, Triangle as TriangleIcon, X } from "lucide-react"; +import { Activity, Check, Circle as CircleIcon, CloudUpload, Compass, Download, Eye, FolderOpen, Hexagon as HexagonIcon, Square as SquareIcon, Triangle as TriangleIcon, X } from "lucide-react"; import type manifoldModule from "manifold-3d"; import type { ManifoldToplevel } from "manifold-3d"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -175,6 +175,13 @@ import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport"; import { exportMeshesToDxf } from "@/lib/dxfExport"; import { importedShapeFromDxf, getImportedDxfText } from "@/lib/dxfImport"; import { importedShapeFromGlb } from "@/lib/glbImport"; +import { cleanTriangleSoup } from "@/lib/meshSanitizer"; +import { + DESKTOP_MENU_COMMAND_EVENT, + exportFiltersForFilename, + getDesktopBridge, +} from "@/lib/desktopBridge"; +import type { DesktopMenuAction } from "@/types/desktop"; import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import { normalizePlacementWorkplane, @@ -245,7 +252,7 @@ type EdgeFeatureRevertOption = { removesNewerCount: number; }; type ManifoldSolid = ReturnType; -type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string }; +type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string } | { mode: "canceled" }; type GroupBuildResult = { group: WorkplaneShape | null; booleanSelection: WorkplaneShape[]; @@ -2823,6 +2830,19 @@ function triggerBrowserDownload(filename: string, content: string, type: string) } async function downloadTextFile(filename: string, content: string, type: string): Promise { + const desktopBridge = getDesktopBridge(); + if (desktopBridge?.saveExportFileDialog) { + const bytes = new TextEncoder().encode(content); + const saved = await desktopBridge.saveExportFileDialog({ + defaultFileName: filename, + bytes, + filters: exportFiltersForFilename(filename), + }); + if (saved.canceled) return { mode: "canceled" }; + if (saved.error) throw new Error(saved.error); + if (saved.filePath) return { mode: "folder", path: saved.filePath }; + } + const mode = window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY); const folder = window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY)?.trim() ?? ""; if (!STATIC_EXPORT_BUILD && mode === "folder" && folder) { @@ -2843,6 +2863,19 @@ async function downloadTextFile(filename: string, content: string, type: string) } async function downloadBlobFile(filename: string, blob: Blob): Promise { + const desktopBridge = getDesktopBridge(); + if (desktopBridge?.saveExportFileDialog) { + const bytes = new Uint8Array(await blob.arrayBuffer()); + const saved = await desktopBridge.saveExportFileDialog({ + defaultFileName: filename, + bytes, + filters: exportFiltersForFilename(filename), + }); + if (saved.canceled) return { mode: "canceled" }; + if (saved.error) throw new Error(saved.error); + if (saved.filePath) return { mode: "folder", path: saved.filePath }; + } + const mode = window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY); const folder = window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY)?.trim() ?? ""; if (!STATIC_EXPORT_BUILD && mode === "folder" && folder) { @@ -3138,14 +3171,15 @@ function mirroredShapesForSelection(shapes: WorkplaneShape[], selectedIds: strin } function geometryFromMeshData(mesh: MeshData) { - const positions: number[] = []; + const rawPositions: number[] = []; mesh.faces.forEach(([ai, bi, ci]) => { [mesh.vertices[ai], mesh.vertices[bi], mesh.vertices[ci]].forEach(([x, y, z]) => { - positions.push(x, y, z); + rawPositions.push(x, y, z); }); }); + const sanitized = cleanTriangleSoup(rawPositions); const geometry = new THREE.BufferGeometry(); - geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(sanitized.positions, 3)); geometry.computeVertexNormals(); return geometry; } @@ -4078,7 +4112,7 @@ function booleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null { result = evaluator.evaluate(result, brushFromShape(hole, true), SUBTRACTION); }); - const resultPositions = positionsFromGeometryDrawRange(result.geometry); + const resultPositions = cleanTriangleSoup(positionsFromGeometryDrawRange(result.geometry)).positions; const groupBounds = boundsForPositions(resultPositions); if (!groupBounds) { return null; @@ -4144,7 +4178,7 @@ function resultGeometryToMeshShape( geometry: THREE.BufferGeometry, idPrefix: string, ): WorkplaneShape | null { - const resultPositions = positionsFromGeometryDrawRange(geometry); + const resultPositions = cleanTriangleSoup(positionsFromGeometryDrawRange(geometry)).positions; const groupBounds = boundsForPositions(resultPositions); if (!groupBounds) { return null; @@ -5991,6 +6025,32 @@ export function SketchForgeEditor({ }; }, []); + useEffect(() => { + const bridge = getDesktopBridge(); + if (!bridge?.setMenuState) return; + void bridge.setMenuState({ + visualStyle: activeVisualStyle, + xRayMode, + isOrthographic, + showLeftToolset: sketchUpPrefs.showLeftToolset, + showDefaultTray: sketchUpPrefs.showDefaultTray, + showSecondaryRibbon: sketchUpPrefs.showSecondaryRibbon, + skyGroundEnabled: sketchUpPrefs.skyGroundEnabled, + backEdgesEnabled: sketchUpPrefs.backEdgesEnabled, + keymapProfile: sketchUpPrefs.keymapProfile, + }); + }, [ + activeVisualStyle, + isOrthographic, + sketchUpPrefs.backEdgesEnabled, + sketchUpPrefs.keymapProfile, + sketchUpPrefs.showDefaultTray, + sketchUpPrefs.showLeftToolset, + sketchUpPrefs.showSecondaryRibbon, + sketchUpPrefs.skyGroundEnabled, + xRayMode, + ]); + const syncPushPullMode = useCallback((activeOrUpdater: boolean | ((prev: boolean) => boolean)) => { setPushPullMode((prev) => { const next = typeof activeOrUpdater === "function" ? activeOrUpdater(prev) : activeOrUpdater; @@ -7361,10 +7421,42 @@ export function SketchForgeEditor({ return; } const next = offsetSketchProfile(sketchProfile, distance); + if (next.points.length === sketchProfile.points.length) { + setNotice(`Ofset (${distance} mm) mevcut geometriyi tamamen kapattığı için yeni kontur üretilemedi`); + return; + } commitSketchProfile(next, `Duvar / Ofset Çizgisi Oluşturuldu (${distance} mm)`); playSynthesizedSound("chime"); }, [commitSketchProfile, sketchProfile]); + const solveCurrentSketchConstraints = useCallback(async () => { + if (sketchProfile.points.length < 2 || sketchProfile.segments.length === 0) { + setNotice("PlaneGCS kısıt çözücü için en az bir çizim segmenti gereklidir"); + return; + } + try { + setNotice("FreeCAD PlaneGCS 2B kısıt çözücü çalıştırılıyor…"); + const { autoConstrainAndSolveSnapCadProfile } = await import("@/lib/planegcsSolver"); + const anchorPointId = sketchSelection?.kind === "point" ? sketchSelection.id : undefined; + const result = await autoConstrainAndSolveSnapCadProfile(sketchProfile, { anchorPointId }); + if (!result.solved) { + setNotice(`2B kısıt sistemi çözülemedi (durum: ${result.status}, serbestlik: ${result.dof})`); + return; + } + if (result.changedPointsCount > 0) { + commitSketchProfile( + result.profile, + `PlaneGCS ile ${result.appliedConstraintsCount} dikey/yatay kısıt çözüldü (${result.changedPointsCount} nokta düzeltildi)`, + ); + } else { + setNotice(`PlaneGCS doğrulaması tamamlandı (${result.appliedConstraintsCount} kısıt, DOF: ${result.dof})`); + } + playSynthesizedSound("chime"); + } catch (err) { + setNotice(err instanceof Error ? err.message : "PlaneGCS çözücü yüklenemedi"); + } + }, [commitSketchProfile, sketchProfile, sketchSelection]); + const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => { const next = cloneSketchProfile(sketchProfile); const point = next.points.find((entry) => entry.id === id); @@ -9492,6 +9584,10 @@ export function SketchForgeEditor({ } const selectedNotice = `Exported ${exportable.length} selected shape${exportable.length === 1 ? "" : "s"}`; const finishNotice = (label: string, result: DownloadResult) => { + if (result.mode === "canceled") { + setNotice(`${label} dışa aktarma iptal edildi`); + return; + } if (result.mode === "folder") { setNotice(`Saved ${label} to ${result.path}`); return; @@ -9582,7 +9678,9 @@ export function SketchForgeEditor({ const text = await blob.text(); const result = await downloadTextFile(projectExportFileName(exportName, "step"), text, "application/step"); const skipNote = skipped.length > 0 ? `; skipped ${skipped.length} non-primitive shape${skipped.length === 1 ? "" : "s"}` : ""; - if (result.mode === "folder") { + if (result.mode === "canceled") { + setNotice("STEP dışa aktarma iptal edildi"); + } else if (result.mode === "folder") { setNotice(`Saved STEP (${exportedCount} bod${exportedCount === 1 ? "y" : "ies"}) to ${result.path}${skipNote}`); } else { setNotice(`Exported STEP B-Rep with ${exportedCount} bod${exportedCount === 1 ? "y" : "ies"}${skipNote}`); @@ -9634,7 +9732,13 @@ export function SketchForgeEditor({ } else { const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; const result = await downloadBlobFile(projectExportFileName(exportName, "skf"), new Blob([buffer], { type: SKF_MEDIA_TYPE })); - setNotice(result.mode === "folder" ? `Saved editable SketchForge project to ${result.path}` : "Saved editable SketchForge project (.skf)"); + setNotice( + result.mode === "canceled" + ? "Proje dışa aktarma iptal edildi" + : result.mode === "folder" + ? `Saved editable SketchForge project to ${result.path}` + : "Saved editable SketchForge project (.skf)", + ); } } catch (error) { setNotice(error instanceof Error ? error.message : "Could not save SketchForge project"); @@ -9699,7 +9803,7 @@ export function SketchForgeEditor({ const projectFiles = files.filter((file) => /\.skf$/i.test(file.name)); if (projectFiles.length) { if (files.length !== 1) { - setNotice("Aynı anda yalnızca bir .skf projesi açılabilir; STL, OBJ, STEP, DXF, DWG, GLB ve SVG geometrisini ayrı ayrı içe aktarın"); + setNotice("Aynı anda yalnızca bir .skf projesi açılabilir; STL, OBJ, STEP, IFC, DXF, DWG, GLB ve SVG geometrisini ayrı ayrı içe aktarın"); return; } if (!onOpenSkfProjectFile) { @@ -9734,12 +9838,13 @@ export function SketchForgeEditor({ const isImage = (file.type.startsWith("image/") && file.type !== "image/svg+xml") || /\.(png|jpe?g|webp|bmp)$/i.test(file.name); const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null); const isStep = sourceFormat === "step"; + const isIfc = sourceFormat === "ifc"; const isObj = sourceFormat === "obj"; const isSvg = sourceFormat === "svg"; const isDxf = sourceFormat === "dxf"; const isDwg = sourceFormat === "dwg"; const isGlb = sourceFormat === "glb"; - if (!isImage && (!sourceFormat || (!isStep && !isSvg && !isDxf && !isDwg && !isGlb && !importExtensionSupported(file.name)))) { + if (!isImage && (!sourceFormat || (!isStep && !isIfc && !isSvg && !isDxf && !isDwg && !isGlb && !importExtensionSupported(file.name)))) { failures.push({ fileName: file.name, reason: "Desteklenmeyen dosya türü" }); continue; } @@ -9747,9 +9852,11 @@ export function SketchForgeEditor({ const statusText = `"${file.name}" içe aktarılıyor (${index + 1}/${files.length})${ isStep ? " — OpenCascade B-Rep çekirdeği yükleniyor" - : isDwg - ? " — LibreDWG WebAssembly motoru ile çözümleniyor (~6 MB)" - : "" + : isIfc + ? " — web-ifc BIM WebAssembly motoru ile çözümleniyor" + : isDwg + ? " — LibreDWG WebAssembly motoru ile çözümleniyor (~6 MB)" + : "" }`; setNotice(statusText); setImportStatusMessage(statusText); @@ -9767,6 +9874,9 @@ export function SketchForgeEditor({ if (isStep) { const { importedShapeFromStep } = await import("@/lib/stepImport"); nextShape = await importedShapeFromStep(file.name, buffer); + } else if (isIfc) { + const { importedShapeFromIfc } = await import("@/lib/ifcImport"); + nextShape = await importedShapeFromIfc(file.name, bytes); } else if (isObj) { nextShape = importedShapeFromObj(file.name, new TextDecoder().decode(bytes)); } else if (isSvg) { @@ -10952,6 +11062,397 @@ export function SketchForgeEditor({ updateSketchUpPrefs, ]); + useEffect(() => { + const onFlushProjectSync = () => { + syncProjectShapes(shapesRef.current, true, true); + }; + const onDesktopCommand = (event: Event) => { + const action = (event as CustomEvent).detail; + if (!action) return; + const activeEl = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const editingInput = Boolean( + activeEl && (activeEl.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(activeEl.tagName)), + ); + const inSketchMode = sketchActive && toolbarMode === "sketch"; + + if (action.startsWith("draw:shape-")) { + const shapeId = action.slice("draw:shape-".length); + const asset = toolbarShapeAssets.find((item) => item.id === shapeId); + if (asset) { + addShape(asset); + } + return; + } + + if (action.startsWith("tray:")) { + const section = action.slice("tray:".length) as DefaultTraySectionId; + openTraySection(section); + return; + } + + switch (action) { + case "file:import": + setTopPanel("import"); + break; + case "file:export-panel": + setTopPanel("export"); + break; + case "file:export-skf": + void exportSkfDesign(projectName, workspaceSettings.historyLimit, "download"); + break; + case "file:export-stl": + exportDesign("stl", projectName); + break; + case "file:export-3mf": + exportDesign("3mf", projectName); + break; + case "file:export-step": + void exportStepDesign(projectName); + break; + case "file:export-obj": + exportDesign("obj", projectName); + break; + case "file:export-glb": + exportDesign("glb", projectName); + break; + case "file:export-dxf": + exportDesign("dxf", projectName); + break; + case "file:export-svg": + exportDesign("svg", projectName); + break; + case "edit:undo": + if (editingInput) document.execCommand("undo"); + else if (inSketchMode) sketchUndo(); + else undo(); + break; + case "edit:redo": + if (editingInput) document.execCommand("redo"); + else if (inSketchMode) sketchRedo(); + else redo(); + break; + case "edit:cut": + if (editingInput) document.execCommand("cut"); + else cutSelected(); + break; + case "edit:copy": + if (editingInput) document.execCommand("copy"); + else copySelected(); + break; + case "edit:paste": + if (editingInput) document.execCommand("paste"); + else void pasteShape(); + break; + case "edit:duplicate": + if (!editingInput) duplicateSelected(); + break; + case "edit:delete": + if (!editingInput) { + if (inSketchMode) deleteSelectedSketchEntity(); + else deleteSelected(); + } + break; + case "edit:select-all": + if (editingInput) { + document.execCommand("selectAll"); + } else { + setSelectedIds(shapesRef.current.filter((shape) => !shape.hidden).map((shape) => shape.id)); + setNotice("Tüm görünür nesneler seçildi"); + } + break; + case "edit:clear-selection": + setSelectedIds([]); + setNotice("Seçim bırakıldı"); + break; + case "edit:make-component": + handleMakeComponent(); + break; + case "edit:make-unique": + handleMakeUnique(); + break; + case "edit:group": + void groupSelected(); + break; + case "edit:ungroup": + ungroupSelected(); + break; + case "edit:intersect": + void intersectSelected(); + break; + case "edit:make-solid": + setSelectionHoleMode(false); + break; + case "edit:make-hole": + setSelectionHoleMode(true); + break; + case "edit:mirror": + toggleMirrorMode(); + break; + case "edit:align": + toggleAlignMode(); + break; + case "edit:drop-to-workplane": + dropSelectedToWorkplane(); + break; + case "edit:snap-to-grid": + snapSelected(); + break; + case "edit:chamfer": + if (edgeModifier?.kind === "chamfer") cancelEdgeModifier(); + else startEdgeModifier("chamfer"); + break; + case "edit:fillet": + if (edgeModifier?.kind === "fillet") cancelEdgeModifier(); + else startEdgeModifier("fillet"); + break; + case "edit:hide": + toggleHidden(); + break; + case "edit:show-hidden": + showHidden(); + break; + case "edit:lock": + toggleLocked(); + break; + case "view:toggle-left-toolset": + updateSketchUpPrefs({ showLeftToolset: !sketchUpPrefs.showLeftToolset }); + break; + case "view:toggle-tray": + updateSketchUpPrefs({ showDefaultTray: !sketchUpPrefs.showDefaultTray }); + break; + case "view:toggle-secondary-ribbon": + updateSketchUpPrefs({ showSecondaryRibbon: !sketchUpPrefs.showSecondaryRibbon }); + break; + case "view:sky-ground": + updateSketchUpPrefs({ skyGroundEnabled: !sketchUpPrefs.skyGroundEnabled }); + break; + case "view:back-edges": + updateSketchUpPrefs({ backEdgesEnabled: !sketchUpPrefs.backEdgesEnabled }); + break; + case "view:xray": + setXRayMode((prev) => !prev); + break; + case "view:style-shaded": + setActiveVisualStyle("shaded"); + break; + case "view:style-monochrome": + setActiveVisualStyle("monochrome"); + break; + case "view:style-hidden-line": + setActiveVisualStyle("hidden-line"); + break; + case "view:style-wireframe": + setActiveVisualStyle("wireframe"); + break; + case "view:style-blueprint": + setActiveVisualStyle("blueprint"); + break; + case "view:style-clay": + setActiveVisualStyle("clay"); + break; + case "view:style-cyberpunk": + setActiveVisualStyle("cyberpunk"); + break; + case "view:layers": + setIsLayersModalOpen(true); + break; + case "view:solar": + setIsSolarModalOpen(true); + break; + case "view:clear-guides": + setArchitecturalGuides([]); + setNotice("Tüm kılavuz çizgileri temizlendi"); + break; + case "view:zoom-extents": + window.dispatchEvent(new CustomEvent("snapcad:zoom-extents")); + break; + case "view:reset-camera": + window.dispatchEvent(new CustomEvent("snapcad:reset-view")); + break; + case "view:toggle-projection": + window.dispatchEvent(new CustomEvent("snapcad:toggle-projection")); + break; + case "camera:isometric": + handleCameraViewPreset("isometric"); + break; + case "camera:top": + handleCameraViewPreset("top"); + break; + case "camera:bottom": + handleCameraViewPreset("bottom"); + break; + case "camera:front": + handleCameraViewPreset("front"); + break; + case "camera:back": + handleCameraViewPreset("back"); + break; + case "camera:left": + handleCameraViewPreset("left"); + break; + case "camera:right": + handleCameraViewPreset("right"); + break; + case "camera:two-point": + handleCameraViewPreset("two-point"); + break; + case "camera:zoom-selection": + handleCameraViewPreset("selection"); + break; + case "camera:previous": + handleCameraViewPreset("previous"); + break; + case "draw:sketch-extrude": + beginSketch("extrude"); + break; + case "draw:sketch-revolve": + beginSketch("revolve"); + break; + case "draw:sketch-edit": + beginSketchEdit(); + break; + case "draw:house-scene": + createHouseScene(false); + break; + case "tool:select": + case "tool:eraser": + case "tool:paint": + case "tool:line": + case "tool:freehand": + case "tool:arc": + case "tool:rectangle": + case "tool:circle": + case "tool:polygon": + case "tool:3d-text": + case "tool:move": + case "tool:push-pull": + case "tool:rotate": + case "tool:scale": + case "tool:offset": + case "tool:follow-me": + case "tool:tape": + case "tool:protractor": + case "tool:axes": + case "tool:section": + case "tool:orbit": + case "tool:pan": + case "tool:zoom": + case "tool:walk": + handleSelectSketchUpTool(action.slice("tool:".length) as SketchUpToolId); + break; + case "tool:wall-opening": + setIsWallOpeningModalOpen(true); + break; + case "tool:terrain": + setIsTerrainModalOpen(true); + break; + case "tool:structural-test": + handleRunStructuralTest(); + break; + case "tool:ar-preview": + setIsARModalOpen(true); + break; + case "tool:physics-toggle": + window.dispatchEvent(new CustomEvent("snapcad:toggle-physics")); + setNotice("Fizik & Yerçekimi Simülasyonu değiştirildi"); + break; + case "tool:physics-reset": + window.dispatchEvent(new CustomEvent("snapcad:reset-physics")); + setNotice("Fizik Simülasyonu sıfırlandı"); + break; + case "window:keymap-classic": + updateSketchUpPrefs({ keymapProfile: "classic-sketchup" }); + setNotice("Kısayol Profili: Mimari Klasik aktif"); + break; + case "window:keymap-standard": + updateSketchUpPrefs({ keymapProfile: "snapcad-standard" }); + setNotice("Kısayol Profili: SnapCAD Erişilebilir aktif"); + break; + case "window:workspace-settings": + window.dispatchEvent(new CustomEvent("sketchforge:open-workspace-settings")); + break; + case "help:audit": + handleOpenAudit(); + break; + case "help:voice": + setIsVoiceCadModalOpen(true); + break; + case "help:radar": + triggerRadarScan(); + break; + case "help:shortcuts": + triggerShortcutHelp(); + break; + case "help:tutorial": + setIsInteractiveTutorialOpen(true); + break; + case "help:daily-challenges": + setIsDailyChallengesOpen(true); + break; + default: + break; + } + }; + window.addEventListener("snapcad:flush-project-sync", onFlushProjectSync); + window.addEventListener(DESKTOP_MENU_COMMAND_EVENT, onDesktopCommand); + return () => { + window.removeEventListener("snapcad:flush-project-sync", onFlushProjectSync); + window.removeEventListener(DESKTOP_MENU_COMMAND_EVENT, onDesktopCommand); + }; + }, [ + addShape, + beginSketch, + beginSketchEdit, + cancelEdgeModifier, + copySelected, + createHouseScene, + cutSelected, + deleteSelected, + deleteSelectedSketchEntity, + dropSelectedToWorkplane, + duplicateSelected, + edgeModifier?.kind, + exportDesign, + exportSkfDesign, + exportStepDesign, + groupSelected, + handleCameraViewPreset, + handleMakeComponent, + handleMakeUnique, + handleOpenAudit, + handleRunStructuralTest, + handleSelectSketchUpTool, + intersectSelected, + openTraySection, + pasteShape, + projectName, + redo, + setSelectionHoleMode, + showHidden, + sketchActive, + sketchRedo, + sketchUndo, + sketchUpPrefs.backEdgesEnabled, + sketchUpPrefs.showDefaultTray, + sketchUpPrefs.showLeftToolset, + sketchUpPrefs.showSecondaryRibbon, + sketchUpPrefs.skyGroundEnabled, + snapSelected, + startEdgeModifier, + syncProjectShapes, + toggleAlignMode, + toggleHidden, + toggleLocked, + toggleMirrorMode, + toolbarMode, + triggerRadarScan, + triggerShortcutHelp, + undo, + ungroupSelected, + updateSketchUpPrefs, + workspaceSettings.historyLimit, + ]); + const secondaryRibbonVisible = sketchUpPrefs.showSecondaryRibbon || sketchActive; const defaultTrayVisible = sketchUpPrefs.showDefaultTray && !(toolbarMode === "sketch" && sketchActive); @@ -11150,6 +11651,7 @@ export function SketchForgeEditor({ }} guidesCount={architecturalGuides.length} onOffsetSketch={() => offsetCurrentSketch(-15)} + onSolveSketchConstraints={solveCurrentSketchConstraints} xRayMode={xRayMode} onToggleXRay={() => { setXRayMode((prev) => !prev); @@ -11769,7 +12271,7 @@ export function SketchForgeEditor({ className="hidden-file-input" type="file" multiple - accept=".dwg,.DWG,.dxf,.DXF,.step,.STEP,.stp,.STP,.stl,.STL,.obj,.OBJ,.glb,.GLB,.gltf,.GLTF,.svg,.SVG,.png,.jpg,.jpeg,.webp,.bmp" + accept=".ifc,.IFC,.dwg,.DWG,.dxf,.DXF,.step,.STEP,.stp,.STP,.stl,.STL,.obj,.OBJ,.glb,.GLB,.gltf,.GLTF,.svg,.SVG,.png,.jpg,.jpeg,.webp,.bmp" onChange={(event) => { if (event.currentTarget.files) { selectFiles(event.currentTarget.files); @@ -11921,6 +12423,7 @@ function SecondaryToolbar({ onClearGuides, guidesCount = 0, onOffsetSketch, + onSolveSketchConstraints, xRayMode = false, onToggleXRay, onOpenLayers, @@ -11993,6 +12496,7 @@ function SecondaryToolbar({ onClearGuides?: () => void; guidesCount?: number; onOffsetSketch?: () => void; + onSolveSketchConstraints?: () => void; xRayMode?: boolean; onToggleXRay?: () => void; onOpenLayers?: () => void; @@ -12515,11 +13019,21 @@ function SecondaryToolbar({
-
Ölçüm
+
Ölçüm & Kısıt
+ {onOffsetSketch ? ( + + ) : null} + {onSolveSketchConstraints ? ( + + ) : null}
@@ -12805,7 +13319,7 @@ function TopActionPanel({ }} > - STL, OBJ, STEP, DXF, DWG, GLB, SVG veya Kat Planı Görselleri (PNG, JPG) + STL, OBJ, STEP, IFC, DXF, DWG, GLB, SVG veya Kat Planı Görselleri (PNG, JPG) veya bilgisayarınızdan seçmek için tıklayın
diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index e5450ea..1ce488b 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -367,6 +367,7 @@ type ThreeState = { lastViewCubeSync: number; rotationHandleSides: RotationHandleSides | null; getCursorToolMode?: () => ViewportCursorMode; + getRenderStyle?: () => ViewportRenderStyle; skyBackdropTexture?: THREE.Texture | null; disposeInteractionListeners: () => void; resize: () => void; @@ -1308,6 +1309,42 @@ function rulerEdgeMatchesTopology(state: ThreeState, edge: RulerEdgeAttachment) }); } +function visibleSnapDepthLimit( + state: ThreeState, + targets: THREE.Object3D[], + clientX: number, + clientY: number, +): { rayOrigin: THREE.Vector3; rayDir: THREE.Vector3; maxDepth: number } | null { + const renderStyle = state.getRenderStyle?.() ?? DEFAULT_RENDER_STYLE; + if (renderStyle.visualStyle === "wireframe" || renderStyle.xRay || renderStyle.backEdges || targets.length === 0) { + return null; + } + const rect = state.renderer.domElement.getBoundingClientRect(); + state.pointer.x = ((clientX - rect.left) / Math.max(1, rect.width)) * 2 - 1; + state.pointer.y = -((clientY - rect.top) / Math.max(1, 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 && !entry.object.userData.cutPreview); + if (!surfaceHit) return null; + const hitDepth = surfaceHit.point.clone().sub(state.raycaster.ray.origin).dot(state.raycaster.ray.direction); + return { + rayOrigin: state.raycaster.ray.origin.clone(), + rayDir: state.raycaster.ray.direction.clone(), + maxDepth: hitDepth + Math.max(0.25, Math.abs(hitDepth) * 0.0025), + }; +} + +function isWorldPointOccluded( + point: THREE.Vector3, + limit: { rayOrigin: THREE.Vector3; rayDir: THREE.Vector3; maxDepth: number } | null, +): boolean { + if (!limit) return false; + const depth = point.clone().sub(limit.rayOrigin).dot(limit.rayDir); + return depth > limit.maxDepth; +} + function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: number, clientY: number): RulerCandidate | null { const rect = state.renderer.domElement.getBoundingClientRect(); const pointerX = clientX - rect.left; @@ -1320,6 +1357,7 @@ function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: state.camera.updateMatrixWorld(); targets.forEach((target) => target.updateWorldMatrix(true, true)); + const depthLimit = visibleSnapDepthLimit(state, targets, clientX, clientY); const vertexCandidates: Array<{ distance: number; candidate: RulerCandidate }> = []; const edgeCandidates: Array<{ distance: number; candidate: RulerCandidate }> = []; @@ -1359,6 +1397,7 @@ function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: }; const endpointIndexes = worldPoints[0].distanceToSquared(worldPoints[worldPoints.length - 1]) < 1e-10 ? [0] : [0, worldPoints.length - 1]; endpointIndexes.forEach((index) => { + if (isWorldPointOccluded(worldPoints[index], depthLimit)) return; const screen = projectToScreen(worldPoints[index], state); const distance = Math.hypot(pointerX - screen.x, pointerY - screen.y); if (distance <= 9) { @@ -1383,6 +1422,7 @@ function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: const distance = Math.hypot(pointerX - (aScreen.x + dx * amount), pointerY - (aScreen.y + dy * amount)); if (distance <= 12) { const world = worldPoints[index].clone().lerp(worldPoints[index + 1], amount); + if (isWorldPointOccluded(world, depthLimit)) continue; const normalizedA = normalizedPoints[index]; const normalizedB = normalizedPoints[index + 1]; edgeCandidates.push({ @@ -1451,6 +1491,8 @@ function pickModifierEdgeFromScreen(state: ThreeState, edges: CadModifierEdge[], const pointerY = clientY - rect.top; const pointA = new THREE.Vector3(); const pointB = new THREE.Vector3(); + const midpoint = new THREE.Vector3(); + const depthLimit = visibleSnapDepthLimit(state, state.shapeLayer.children, clientX, clientY); let nearestId: number | null = null; let nearestDistance = MODIFIER_EDGE_PICK_RADIUS_PX; state.camera.updateMatrixWorld(); @@ -1458,6 +1500,8 @@ function pickModifierEdgeFromScreen(state: ThreeState, edges: CadModifierEdge[], for (let index = 0; index + 5 < edge.points.length; index += 3) { pointA.set(edge.points[index], edge.points[index + 1], edge.points[index + 2]); pointB.set(edge.points[index + 3], edge.points[index + 4], edge.points[index + 5]); + midpoint.copy(pointA).add(pointB).multiplyScalar(0.5); + if (isWorldPointOccluded(midpoint, depthLimit)) continue; const a = projectCadPointToCanvas(pointA, state, rect); const b = projectCadPointToCanvas(pointB, state, rect); if (!a || !b) continue; @@ -2814,8 +2858,19 @@ export function WorkplaneViewport({ physicsSandboxRef.current?.reset(); }, []); + const togglePhysicsRef = useRef(togglePhysics); + togglePhysicsRef.current = togglePhysics; + const resetPhysicsRef = useRef(resetPhysics); + resetPhysicsRef.current = resetPhysics; + useEffect(() => { + const onTogglePhysics = () => togglePhysicsRef.current(); + const onResetPhysics = () => resetPhysicsRef.current(); + window.addEventListener("snapcad:toggle-physics", onTogglePhysics); + window.addEventListener("snapcad:reset-physics", onResetPhysics); return () => { + window.removeEventListener("snapcad:toggle-physics", onTogglePhysics); + window.removeEventListener("snapcad:reset-physics", onResetPhysics); physicsSandboxRef.current?.stop(); }; }, []); @@ -3357,6 +3412,7 @@ export function WorkplaneViewport({ const state = createThreeScene(host); state.getCursorToolMode = () => cursorToolModeRef.current; + state.getRenderStyle = () => renderStyleRef.current; threeRef.current = state; rebuildWorkplane(state, workspaceRef.current, resolvedThemeRef.current, placementWorkplaneRef.current); applySceneBackdrop(state, renderStyleRef.current, skyGroundEnabledRef.current, workspaceRef.current); @@ -5574,6 +5630,24 @@ export function WorkplaneViewport({ const box = new THREE.Box3(); let hasValidBox = false; currentShapes.forEach((shape) => { + const object = findShapeObject(state, shape.id); + if (object) { + object.updateMatrixWorld(true); + const objBox = new THREE.Box3().setFromObject(object); + if ( + !objBox.isEmpty() && + Number.isFinite(objBox.min.x) && + Number.isFinite(objBox.min.y) && + Number.isFinite(objBox.min.z) && + Number.isFinite(objBox.max.x) && + Number.isFinite(objBox.max.y) && + Number.isFinite(objBox.max.z) + ) { + box.union(objBox); + hasValidBox = true; + return; + } + } const halfW = (shape.width ?? shape.size ?? 20) / 2; const halfD = (shape.depth ?? shape.size ?? 20) / 2; const h = Math.max(0.5, shape.height ?? 20); @@ -5593,7 +5667,11 @@ export function WorkplaneViewport({ const size = box.getSize(new THREE.Vector3()); const maxDim = Math.max(size.x, size.y, size.z, 20); applySceneCameraRange(state, maxDim); - const distance = Math.max(30, (maxDim / 2) / Math.tan(THREE.MathUtils.degToRad(CAMERA_FOV / 2)) * 1.35); + const canvas = state.renderer.domElement; + const aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight); + let halfFovDeg = CAMERA_FOV / 2; + if (aspect < 1) halfFovDeg *= aspect; + const distance = Math.max(30, (maxDim / 2) / Math.tan(THREE.MathUtils.degToRad(Math.max(5, halfFovDeg))) * 1.35); const offset = state.camera.position.clone().sub(state.controls.target); const direction = offset.lengthSq() > 0.001 @@ -5606,8 +5684,6 @@ export function WorkplaneViewport({ if (state.camera instanceof THREE.OrthographicCamera) { state.camera.zoom = 1; - const canvas = state.renderer.domElement; - const aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight); updateOrthographicFrustum(state.camera, aspect, (maxDim / 2) * 1.35); } state.camera.updateProjectionMatrix(); @@ -5699,7 +5775,11 @@ export function WorkplaneViewport({ const maxDim = Math.max(size.x, size.y, size.z, 15); applySceneCameraRange(state, maxDim); const camFov = state.camera instanceof THREE.PerspectiveCamera ? state.camera.fov : 45; - const distance = Math.max(25, (maxDim / 2) / Math.tan(THREE.MathUtils.degToRad(camFov / 2)) * 1.35); + const selCanvas = state.renderer.domElement; + const selAspect = selCanvas.clientWidth / Math.max(1, selCanvas.clientHeight); + let selHalfFovDeg = camFov / 2; + if (selAspect < 1) selHalfFovDeg *= selAspect; + const distance = Math.max(25, (maxDim / 2) / Math.tan(THREE.MathUtils.degToRad(Math.max(5, selHalfFovDeg))) * 1.35); const offset = state.camera.position.clone().sub(state.controls.target); const direction = offset.lengthSq() > 0.001 @@ -6065,13 +6145,13 @@ export function WorkplaneViewport({ ) { event.preventDefault(); resetView(); - } else if ((event.key === "Z" && event.shiftKey) || (key === "z" && event.shiftKey)) { + } else if (!event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey && (event.code === "KeyZ" || key === "z" || event.key === "Z")) { event.preventDefault(); zoomExtents(); - } else if (event.altKey && (key === "z" || event.key === "Z")) { + } else if (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyZ" || key === "z" || event.key === "Z")) { event.preventDefault(); zoomSelection(); - } else if (event.altKey && (key === "p" || event.key === "P")) { + } else if (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyP" || key === "p" || event.key === "P")) { event.preventDefault(); zoomPrevious(); } else if ( diff --git a/apps/web/src/components/snapcad/AccessibilityCenter.tsx b/apps/web/src/components/snapcad/AccessibilityCenter.tsx index 866fcb8..f1df594 100644 --- a/apps/web/src/components/snapcad/AccessibilityCenter.tsx +++ b/apps/web/src/components/snapcad/AccessibilityCenter.tsx @@ -338,11 +338,11 @@ export function GlobalAccessibilityToolbar({ useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { - if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") { + if ((event.ctrlKey || event.metaKey) && (event.code === "KeyK" || event.key.toLowerCase() === "k")) { event.preventDefault(); setPaletteOpen((v) => !v); setDrawerOpen(false); - } else if (event.altKey && event.key.toLowerCase() === "a") { + } else if (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyA" || event.key.toLowerCase() === "a")) { event.preventDefault(); setDrawerOpen((v) => !v); setPaletteOpen(false); @@ -355,11 +355,17 @@ export function GlobalAccessibilityToolbar({ setDrawerOpen(true); setPaletteOpen(false); }; + const onOpenCommandPalette = () => { + setPaletteOpen(true); + setDrawerOpen(false); + }; window.addEventListener("keydown", onKeyDown); window.addEventListener("snapcad:open-a11y-drawer", onOpenA11yDrawer); + window.addEventListener("snapcad:open-command-palette", onOpenCommandPalette); return () => { window.removeEventListener("keydown", onKeyDown); window.removeEventListener("snapcad:open-a11y-drawer", onOpenA11yDrawer); + window.removeEventListener("snapcad:open-command-palette", onOpenCommandPalette); }; }, []); diff --git a/apps/web/src/components/snapcad/CircuitsStudio.tsx b/apps/web/src/components/snapcad/CircuitsStudio.tsx index c753793..470ec27 100644 --- a/apps/web/src/components/snapcad/CircuitsStudio.tsx +++ b/apps/web/src/components/snapcad/CircuitsStudio.tsx @@ -361,12 +361,12 @@ export default function CircuitsStudio({ initialTemplateId, onBackToProjects }: if ((e.target as HTMLElement).tagName === "INPUT" || (e.target as HTMLElement).tagName === "TEXTAREA") return; if (e.key === "Delete" || e.key === "Backspace") { if (selectedId) removeComponent(selectedId); - } else if (e.key === "r" || e.key === "R") { + } else if (!e.ctrlKey && !e.metaKey && !e.altKey && (e.key === "r" || e.key === "R")) { rotateSelectedComponent(); - } else if ((e.ctrlKey || e.metaKey) && e.key === "z") { + } else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (e.code === "KeyZ" || e.key.toLowerCase() === "z")) { e.preventDefault(); handleUndo(); - } else if ((e.ctrlKey || e.metaKey) && (e.key === "y" || (e.shiftKey && e.key === "Z"))) { + } else if ((e.ctrlKey || e.metaKey) && (e.code === "KeyY" || e.key.toLowerCase() === "y" || (e.shiftKey && (e.code === "KeyZ" || e.key.toLowerCase() === "z")))) { e.preventDefault(); handleRedo(); } diff --git a/apps/web/src/components/snapcad/ClassroomsStudio.tsx b/apps/web/src/components/snapcad/ClassroomsStudio.tsx index 67dcb5f..91a2daf 100644 --- a/apps/web/src/components/snapcad/ClassroomsStudio.tsx +++ b/apps/web/src/components/snapcad/ClassroomsStudio.tsx @@ -31,6 +31,7 @@ import { X, Zap, } from "lucide-react"; +import { cloudApiFetch } from "@/lib/cloudApi"; import type { WorkplaneShape } from "@/types/sketchforge"; export interface Classroom { @@ -506,7 +507,7 @@ export default function ClassroomsStudio({ setClassDetailLoading(true); announce(`${classroom.title} sınıfı ayrıntıları yükleniyor.`); try { - const res = await fetch( + const res = await cloudApiFetch( `/cloud-api.php?action=classroom_details&classroom_id=${classroom.id}`, { cache: "no-store" } ); @@ -538,7 +539,7 @@ export default function ClassroomsStudio({ const fetchSessionAndClassrooms = useCallback(async () => { setLoading(true); try { - const sessRes = await fetch("/cloud-api.php?action=session", { cache: "no-store" }); + const sessRes = await cloudApiFetch("/cloud-api.php?action=session", { cache: "no-store" }); const sessData = await sessRes.json(); if (sessData.ok) { if (sessData.authenticated && sessData.user) { @@ -554,7 +555,7 @@ export default function ClassroomsStudio({ } // Sınıfları çek - const listRes = await fetch("/cloud-api.php?action=classroom_list", { cache: "no-store" }); + const listRes = await cloudApiFetch("/cloud-api.php?action=classroom_list", { cache: "no-store" }); const listData = await listRes.json(); if (listData.ok) { const tClassrooms: Classroom[] = listData.teacher_classrooms || []; @@ -577,7 +578,7 @@ export default function ClassroomsStudio({ void openClassroomDetails(found, false); } else { try { - const singleRes = await fetch(`/cloud-api.php?action=classroom_details&classroom_id=${encodeURIComponent(initialClassId)}`); + const singleRes = await cloudApiFetch(`/cloud-api.php?action=classroom_details&classroom_id=${encodeURIComponent(initialClassId)}`); const singleData = await singleRes.json(); if (singleData.ok && singleData.classroom) { targetClass = singleData.classroom; @@ -640,7 +641,7 @@ export default function ClassroomsStudio({ if (!createForm.title.trim()) return; try { - const res = await fetch("/cloud-api.php?action=classroom_create", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_create", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(createForm), @@ -677,7 +678,7 @@ export default function ClassroomsStudio({ setEditSubmitting(true); try { - const res = await fetch("/cloud-api.php?action=classroom_update", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_update", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -719,7 +720,7 @@ export default function ClassroomsStudio({ setDeleteSubmitting(true); try { - const res = await fetch("/cloud-api.php?action=classroom_delete", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -757,7 +758,7 @@ export default function ClassroomsStudio({ if (!joinForm.class_code.trim()) return; try { - const res = await fetch("/cloud-api.php?action=classroom_join", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_join", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -801,7 +802,7 @@ export default function ClassroomsStudio({ if (!window.confirm(`${member.display_name} için yeni bir PIN oluşturulsun mu?`)) return; try { - const res = await fetch("/cloud-api.php?action=classroom_reset_pin", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_reset_pin", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -828,7 +829,7 @@ export default function ClassroomsStudio({ const handleOpenProjectInStudio = async (project: ClassroomProject) => { announce(`${project.student_name} öğrencisinin ${project.title} projesi stüdyoya yükleniyor.`); try { - const res = await fetch(`/cloud-api.php?action=classroom_get_project&project_id=${project.id}`, { cache: "no-store" }); + const res = await cloudApiFetch(`/cloud-api.php?action=classroom_get_project&project_id=${project.id}`, { cache: "no-store" }); const data = await res.json(); if (data.ok && data.project) { const studioType = project.studio_type; @@ -865,7 +866,7 @@ export default function ClassroomsStudio({ if (!activeClassroom || !activityForm.title.trim()) return; try { - const res = await fetch("/cloud-api.php?action=classroom_create_activity", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_create_activity", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -911,7 +912,7 @@ export default function ClassroomsStudio({ chosenLocal.id ); } else { - const res = await fetch("/cloud-api.php?action=classroom_submit_project", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_submit_project", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -945,7 +946,7 @@ export default function ClassroomsStudio({ if (!activeClassroom || !showGradeModal) return; try { - const res = await fetch("/cloud-api.php?action=classroom_grade_project", { + const res = await cloudApiFetch("/cloud-api.php?action=classroom_grade_project", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -975,7 +976,7 @@ export default function ClassroomsStudio({ const handleLogoutGuest = async () => { if (!confirm("Misafir öğrenci oturumunuzu kapatmak istiyor musunuz?")) return; try { - await fetch("/cloud-api.php?action=logout", { method: "POST" }); + await cloudApiFetch("/cloud-api.php?action=logout", { method: "POST" }); setGuestStudent(null); await fetchSessionAndClassrooms(); setActiveClassroom(null); diff --git a/apps/web/src/components/snapcad/PlatformFooter.tsx b/apps/web/src/components/snapcad/PlatformFooter.tsx index 63069a0..69d382c 100644 --- a/apps/web/src/components/snapcad/PlatformFooter.tsx +++ b/apps/web/src/components/snapcad/PlatformFooter.tsx @@ -1,6 +1,7 @@ "use client"; import { Box, ShieldCheck } from "lucide-react"; +import { useIsDesktopRuntime } from "@/lib/desktopBridge"; interface PlatformFooterProps { onNavigateSection?: ( @@ -21,6 +22,9 @@ interface PlatformFooterProps { } export function PlatformFooter({ onNavigateSection, className = "" }: PlatformFooterProps) { + const isDesktop = useIsDesktopRuntime(); + if (isDesktop) return null; + const handleNav = ( section: | "home" diff --git a/apps/web/src/components/snapcad/PwaManager.tsx b/apps/web/src/components/snapcad/PwaManager.tsx index 66d892a..4f57e10 100644 --- a/apps/web/src/components/snapcad/PwaManager.tsx +++ b/apps/web/src/components/snapcad/PwaManager.tsx @@ -1,6 +1,7 @@ "use client"; import { useEffect, useState } from "react"; +import { isDesktopRuntime } from "@/lib/desktopBridge"; import { SERVICE_WORKER_URL } from "@/lib/serviceWorker"; interface BeforeInstallPromptEvent extends Event { @@ -14,6 +15,7 @@ export function PwaManager() { const [showBanner, setShowBanner] = useState(false); useEffect(() => { + if (isDesktopRuntime()) return; // 1. Register Service Worker let removeLoadListener: (() => void) | undefined; if (typeof window !== "undefined" && "serviceWorker" in navigator) { diff --git a/apps/web/src/components/snapcad/TechnicalDrawingStudio.tsx b/apps/web/src/components/snapcad/TechnicalDrawingStudio.tsx index f9662b1..39eea8f 100644 --- a/apps/web/src/components/snapcad/TechnicalDrawingStudio.tsx +++ b/apps/web/src/components/snapcad/TechnicalDrawingStudio.tsx @@ -34,6 +34,13 @@ import { type CadBezierCurve, type Point2D, } from "@/lib/cad2dEngine"; +import { offsetPolygon } from "@/lib/offsetKernel"; +import { + buildAnalyticFallbackProjection, + computeModelProjectionAsync, + mapProjectionSegmentsToSheet, + type ModelProjectionCache, +} from "@/lib/technicalProjectionBridge"; export type VocationalDepartmentId = | "project" @@ -920,6 +927,47 @@ export function TechnicalDrawingStudio({ return activePreset.shapes; }, [selectedSource, projectShapes, activePreset]); + const fallbackProjection = useMemo( + () => buildAnalyticFallbackProjection(activeShapes), + [activeShapes], + ); + const [hlrProjection, setHlrProjection] = useState<{ + key: unknown; + sectionAA: boolean; + data: ModelProjectionCache; + } | null>(null); + + useEffect(() => { + const controller = new AbortController(); + const shapesRef = activeShapes; + const sectionRef = sectionAAEnabled; + + computeModelProjectionAsync(shapesRef, { + sectionAAEnabled: sectionRef, + radialSegments: 28, + signal: controller.signal, + }) + .then((projected) => { + if (!controller.signal.aborted) { + setHlrProjection({ key: shapesRef, sectionAA: sectionRef, data: projected }); + } + }) + .catch(() => { + // Aborted on rapid preset/scene switch; keep current/fallback projection + }); + + return () => { + controller.abort(); + }; + }, [activeShapes, sectionAAEnabled]); + + const activeProjection = + hlrProjection && + hlrProjection.key === activeShapes && + hlrProjection.sectionAA === sectionAAEnabled + ? hlrProjection.data + : fallbackProjection; + const handleSelectSource = (sourceId: VocationalDepartmentId) => { setSelectedSource(sourceId); if (sourceId === "project") { @@ -1030,14 +1078,19 @@ export function TechnicalDrawingStudio({ }, [activeShapes]); // Build 2D CAD primitives in sheet coordinates (840 x 594 virtual A4/A3 canvas) + // Uses true 3D BVH Hidden Line Removal + Planar Section A-A cuts from three-edge-projection const blueprintPrimitives = useMemo(() => { const items: Primitive2D[] = []; const scaleMultiplier = titleBlock.scale === "2:1" ? 2.1 : titleBlock.scale === "1:2" ? 0.85 : 1.35; - const cxModel = (geometryMetrics.minX + geometryMetrics.maxX) / 2; - const cyModel = (geometryMetrics.minY + geometryMetrics.maxY) / 2; - const czModel = (geometryMetrics.minZ + geometryMetrics.maxZ) / 2; + const projBounds = activeProjection.bounds; + const cxModel = activeProjection.center.cx; + const cyModel = activeProjection.center.cy; + const czModel = activeProjection.center.cz; + const projWidthX = Math.max(1, Math.round((projBounds.maxX - projBounds.minX) * 10) / 10); + const projHeightY = Math.max(1, Math.round((projBounds.maxY - projBounds.minY) * 10) / 10); + const projDepthZ = Math.max(1, Math.round((projBounds.maxZ - projBounds.minZ) * 10) / 10); // View centers on the 840x594 sheet const frontOrigin = @@ -1060,82 +1113,43 @@ export function TechnicalDrawingStudio({ const s = viewMode === "quad" ? scaleMultiplier : scaleMultiplier * 1.45; - // 1. FRONT VIEW (X-Y plane) or SECTION A-A + // 1. FRONT VIEW (X-Y plane) or A-A FULL SECTION VIEW (via PlanarIntersectionGenerator + BVH HLR) if (viewMode === "quad" || viewMode === "front_section") { + items.push( + ...mapProjectionSegmentsToSheet(activeProjection.views.front, frontOrigin, s, { + includeHidden: !sectionAAEnabled, + includeSectionHatch: sectionAAEnabled, + }), + ); + + // Vertical centerlines for cylindrical / hole features for (const shape of activeShapes) { - const w = shape.width * s; - const h = shape.height * s; - const cy = shapeCenterY(shape); - const x = frontOrigin.x + (shape.x - cxModel) * s - w / 2; - const y = frontOrigin.y - (cy - cyModel) * s - h / 2; - - if (!shape.hole) { - items.push({ - kind: "rect", - layer: "VISIBLE", - x, - y, - w, - h, - label: shape.name - }); - - // If Section A-A is enabled and shape intersects Z=0 plane, draw 45-degree hatch lines - const crossesSectionPlane = - Math.abs(shape.z - czModel) <= shape.depth / 2 + 1; - if (sectionAAEnabled && crossesSectionPlane) { - const step = 9; - for (let offset = -h; offset < w; offset += step) { - const xStart = Math.max(x, x + offset); - const yStart = offset < 0 ? y - offset : y; - const xEnd = Math.min(x + w, x + offset + h); - const yEnd = offset + h > w ? y + (w - offset) : y + h; - if (xEnd > xStart && yEnd > yStart) { - items.push({ - kind: "line", - layer: "HATCH", - x: xStart, - y: yStart, - x2: xEnd, - y2: yEnd - }); - } - } - } - } else { - // Hole in front view: HIDDEN dashed unless Section A-A cuts right through this hole! - const cutBySection = - sectionAAEnabled && Math.abs(shape.z - czModel) <= shape.depth / 2 + 2; - items.push({ - kind: "rect", - layer: cutBySection ? "VISIBLE" : "HIDDEN", - x, - y, - w, - h - }); - // Vertical centerline of the hole/cylinder + if (shape.hole || shape.kind === "cylinder" || shape.kind === "cone") { + const h = shape.height * s; + const cy = shapeCenterY(shape); + const cx = frontOrigin.x + (shape.x - cxModel) * s; + const topShapeY = frontOrigin.y - (cy - cyModel) * s - h / 2; items.push({ kind: "line", layer: "CENTER", - x: x + w / 2, - y: y - 8, - x2: x + w / 2, - y2: y + h + 8 + x: cx, + y: topShapeY - 8, + x2: cx, + y2: topShapeY + h + 8, }); } } // Main symmetry centerline for Front view - const totalW = geometryMetrics.widthX * s; - const totalH = geometryMetrics.heightY * s; + const totalW = projWidthX * s; + const totalH = projHeightY * s; items.push({ kind: "line", layer: "CENTER", x: frontOrigin.x, y: frontOrigin.y - totalH / 2 - 16, x2: frontOrigin.x, - y2: frontOrigin.y + totalH / 2 + 16 + y2: frontOrigin.y + totalH / 2 + 16, }); // Overall Width & Height Dimensions on Front View @@ -1152,7 +1166,7 @@ export function TechnicalDrawingStudio({ y: topY - 22, x2: rightX, y2: topY - 22, - label: `${geometryMetrics.widthX} mm` + label: `${projWidthX} mm`, }); items.push({ kind: "line", layer: "DIMENSION", x: leftX, y: topY - 27, x2: leftX, y2: topY - 4 }); items.push({ kind: "line", layer: "DIMENSION", x: rightX, y: topY - 27, x2: rightX, y2: topY - 4 }); @@ -1165,30 +1179,26 @@ export function TechnicalDrawingStudio({ y: topY, x2: leftX - 24, y2: bottomY, - label: `${geometryMetrics.heightY} mm` + label: `${projHeightY} mm`, }); items.push({ kind: "line", layer: "DIMENSION", x: leftX - 29, y: topY, x2: leftX - 4, y2: topY }); items.push({ kind: "line", layer: "DIMENSION", x: leftX - 29, y: bottomY, x2: leftX - 4, y2: bottomY }); } - // 2. TOP VIEW (X-Z plane — Üst Görünüş) + // 2. TOP VIEW (X-Z plane — Üst Görünüş via BVH HLR) if (viewMode === "quad" || viewMode === "top") { + items.push( + ...mapProjectionSegmentsToSheet(activeProjection.views.top, topOrigin, s, { + includeHidden: true, + }), + ); + for (const shape of activeShapes) { const cx = topOrigin.x + (shape.x - cxModel) * s; const cy = topOrigin.y + (shape.z - czModel) * s; - const w = shape.width * s; - const d = shape.depth * s; if (shape.kind === "cylinder" || shape.kind === "sphere" || shape.kind === "cone") { const r = (shape.width / 2) * s; - items.push({ - kind: "circle", - layer: "VISIBLE", - x: cx, - y: cy, - r, - label: shape.hole ? `Ø${shape.width}` : undefined - }); // Crosshair centerlines for every circular feature items.push({ kind: "line", @@ -1196,7 +1206,7 @@ export function TechnicalDrawingStudio({ x: cx - r - 6, y: cy, x2: cx + r + 6, - y2: cy + y2: cy, }); items.push({ kind: "line", @@ -1204,23 +1214,25 @@ export function TechnicalDrawingStudio({ x: cx, y: cy - r - 6, x2: cx, - y2: cy + r + 6 - }); - } else { - items.push({ - kind: "rect", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x: cx - w / 2, - y: cy - d / 2, - w, - h: d + y2: cy + r + 6, }); + if (shape.hole) { + items.push({ + kind: "line", + layer: "DIMENSION", + x: cx + r * 0.707, + y: cy - r * 0.707, + x2: cx + r + 10, + y2: cy - r - 6, + label: `Ø${shape.width}`, + }); + } } } // Section Plane A-A Cutting Line on Top View - const totalW = geometryMetrics.widthX * s; - const totalD = geometryMetrics.depthZ * s; + const totalW = projWidthX * s; + const totalD = projDepthZ * s; if (sectionAAEnabled) { items.push({ kind: "line", @@ -1229,7 +1241,7 @@ export function TechnicalDrawingStudio({ y: topOrigin.y, x2: topOrigin.x + totalW / 2 + 22, y2: topOrigin.y, - label: "A - A KESİT HATTI" + label: "A - A KESİT HATTI", }); } @@ -1244,155 +1256,48 @@ export function TechnicalDrawingStudio({ y: topZ, x2: leftX - 24, y2: bottomZ, - label: `${geometryMetrics.depthZ} mm` + label: `${projDepthZ} mm`, }); } - // 3. LEFT SIDE VIEW (Z-Y plane — Sol Yan Görünüş) + // 3. LEFT SIDE VIEW (Z-Y plane — Sol Yan Görünüş via BVH HLR) if (viewMode === "quad" || viewMode === "side") { + items.push( + ...mapProjectionSegmentsToSheet(activeProjection.views.side, sideOrigin, s, { + includeHidden: true, + }), + ); + for (const shape of activeShapes) { - const w = shape.depth * s; - const h = shape.height * s; - const cy = shapeCenterY(shape); - const x = sideOrigin.x + (shape.z - czModel) * s - w / 2; - const y = sideOrigin.y - (cy - cyModel) * s - h / 2; - - items.push({ - kind: "rect", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x, - y, - w, - h - }); - if (shape.kind === "cylinder" || shape.hole) { + const h = shape.height * s; + const cy = shapeCenterY(shape); + const cx = sideOrigin.x + (shape.z - czModel) * s; + const topShapeY = sideOrigin.y - (cy - cyModel) * s - h / 2; items.push({ kind: "line", layer: "CENTER", - x: x + w / 2, - y: y - 7, - x2: x + w / 2, - y2: y + h + 7 + x: cx, + y: topShapeY - 7, + x2: cx, + y2: topShapeY + h + 7, }); } } } - // 4. ISOMETRIC 30°/30° AXONOMETRIC PROJECTION + // 4. ISOMETRIC 30°/30° ORTHOGRAPHIC PROJECTION (BVH HLR) if (viewMode === "quad" || viewMode === "isometric") { - const isoScale = s * 0.72; - const cos30 = Math.cos(Math.PI / 6); - const sin30 = 0.5; - const projectIso = (px: number, py: number, pz: number) => { - const rx = (px - cxModel) * isoScale; - const ry = (py - cyModel) * isoScale; - const rz = (pz - czModel) * isoScale; - return { - x: isoOrigin.x + (rx - rz) * cos30, - y: isoOrigin.y - ry + (rx + rz) * sin30 - }; - }; - - for (const shape of activeShapes) { - const hx = shape.width / 2; - const hy = shape.height / 2; - const hz = shape.depth / 2; - const sx = shape.x; - const sy = shapeCenterY(shape); - const sz = shape.z; - - if (shape.kind === "cylinder") { - // Approximate top & bottom isometric ellipses via 16-segment polygon - const segs = 16; - for (let i = 0; i < segs; i++) { - const a1 = (i / segs) * Math.PI * 2; - const a2 = ((i + 1) / segs) * Math.PI * 2; - const top1 = projectIso(sx + Math.cos(a1) * hx, sy + hy, sz + Math.sin(a1) * hz); - const top2 = projectIso(sx + Math.cos(a2) * hx, sy + hy, sz + Math.sin(a2) * hz); - items.push({ - kind: "line", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x: top1.x, - y: top1.y, - x2: top2.x, - y2: top2.y - }); - if (!shape.hole) { - const bot1 = projectIso(sx + Math.cos(a1) * hx, sy - hy, sz + Math.sin(a1) * hz); - const bot2 = projectIso(sx + Math.cos(a2) * hx, sy - hy, sz + Math.sin(a2) * hz); - items.push({ - kind: "line", - layer: "VISIBLE", - x: bot1.x, - y: bot1.y, - x2: bot2.x, - y2: bot2.y - }); - } - } - // Side silhouette lines of cylinder - const leftTop = projectIso(sx - hx, sy + hy, sz - hz * 0.35); - const leftBot = projectIso(sx - hx, sy - hy, sz - hz * 0.35); - const rightTop = projectIso(sx + hx, sy + hy, sz + hz * 0.35); - const rightBot = projectIso(sx + hx, sy - hy, sz + hz * 0.35); - items.push({ - kind: "line", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x: leftTop.x, - y: leftTop.y, - x2: leftBot.x, - y2: leftBot.y - }); - items.push({ - kind: "line", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x: rightTop.x, - y: rightTop.y, - x2: rightBot.x, - y2: rightBot.y - }); - } else { - const corners = [ - projectIso(sx - hx, sy - hy, sz - hz), - projectIso(sx + hx, sy - hy, sz - hz), - projectIso(sx + hx, sy - hy, sz + hz), - projectIso(sx - hx, sy - hy, sz + hz), - projectIso(sx - hx, sy + hy, sz - hz), - projectIso(sx + hx, sy + hy, sz - hz), - projectIso(sx + hx, sy + hy, sz + hz), - projectIso(sx - hx, sy + hy, sz + hz) - ]; - const edges: Array<[number, number]> = [ - [0, 1], - [1, 2], - [2, 3], - [3, 0], - [4, 5], - [5, 6], - [6, 7], - [7, 4], - [0, 4], - [1, 5], - [2, 6], - [3, 7] - ]; - for (const [i1, i2] of edges) { - items.push({ - kind: "line", - layer: shape.hole ? "HIDDEN" : "VISIBLE", - x: corners[i1].x, - y: corners[i1].y, - x2: corners[i2].x, - y2: corners[i2].y - }); - } - } - } + items.push( + ...mapProjectionSegmentsToSheet(activeProjection.views.isometric, isoOrigin, s, { + isIsometric: true, + includeHidden: false, + }), + ); } return items; - }, [activeShapes, geometryMetrics, viewMode, sectionAAEnabled, titleBlock.scale]); + }, [activeShapes, activeProjection, viewMode, sectionAAEnabled, titleBlock.scale]); // Interactive click on the 2D CAD Sheet const handleCanvasClick = (event: React.MouseEvent) => { @@ -1482,27 +1387,30 @@ export function TechnicalDrawingStudio({ pts = [...lastShape.points]; } if (pts.length >= 3) { - const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length; - const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length; - const offsetPts = pts.map((p) => { - const dx = p.x - cx; - const dy = p.y - cy; - const dist = Math.hypot(dx, dy) || 1; - return { x: p.x + (dx / dist) * 14, y: p.y + (dy / dist) * 14 }; - }); - setCustomEntities((prev) => [ - ...prev, - { - id: `cad-offset-${Date.now()}`, - type: "polygon", - x1: offsetPts[0].x, - y1: offsetPts[0].y, - points: offsetPts, - label: "Ofset +10mm Et Kalınlığı", - layer: "VISIBLE" - } - ]); - setStatusBanner("Paralel ofset (+10 mm et kalınlığı) üretildi."); + const expanded = offsetPolygon( + pts.map((p) => ({ x: p.x, z: p.y })), + 10 * 1.35, + 3.0, + { joinType: "miter" }, + ); + const offsetPts: Point2D[] = expanded.map((p) => ({ x: p.x, y: p.z })); + if (offsetPts.length >= 3) { + setCustomEntities((prev) => [ + ...prev, + { + id: `cad-offset-${Date.now()}`, + type: "polygon", + x1: offsetPts[0].x, + y1: offsetPts[0].y, + points: offsetPts, + label: "Ofset +10mm Et Kalınlığı", + layer: "VISIBLE" + } + ]); + setStatusBanner("Clipper2 paralel ofset (+10 mm et kalınlığı) üretildi."); + } else { + setStatusBanner("Ofset geometrisi üretilemedi."); + } } return; } @@ -2087,7 +1995,7 @@ export function TechnicalDrawingStudio({ setDarkBlueprintTheme((v) => !v); } // 9. Sesli Kılavuz / Yardım: '?' veya 'H' - else if (key === "?" || (e.shiftKey && key === "?") || key === "h") { + else if (!shortcut && !e.altKey && (key === "?" || key === "h" || e.code === "KeyH")) { e.preventDefault(); const helpText = "Teknik Resim Kısayolları: İ tuşu çizim denetçisi. O tuşu DWG ve DXF yükleme. G tuşu CNC ve lazer G-Code indirme. N tuşu sac yerleşimi. D tuşu DXF indirme. P tuşu PDF indirme. B tuşu arka plan teması."; speakTurkish(helpText); diff --git a/apps/web/src/components/snapcad/WebRuntimeChrome.tsx b/apps/web/src/components/snapcad/WebRuntimeChrome.tsx new file mode 100644 index 0000000..35aa09c --- /dev/null +++ b/apps/web/src/components/snapcad/WebRuntimeChrome.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { useEffect } from "react"; +import { PwaManager } from "@/components/snapcad/PwaManager"; +import { isDesktopRuntime, useIsDesktopRuntime } from "@/lib/desktopBridge"; + +/** + * Web-only chrome (PWA service worker & browser install prompt). + * Suppressed inside the native SnapCAD Studio desktop application, where it also + * syncs `data-desktop-runtime="true"` on `` for native desktop UX rules. + */ +export function WebRuntimeChrome() { + const isDesktop = useIsDesktopRuntime(); + + useEffect(() => { + if (typeof document === "undefined") return; + if (isDesktopRuntime()) { + document.documentElement.setAttribute("data-desktop-runtime", "true"); + } else { + document.documentElement.removeAttribute("data-desktop-runtime"); + } + }, [isDesktop]); + + if (isDesktop) return null; + + return ; +} diff --git a/apps/web/src/components/snapcad/YakNetCloudBar.tsx b/apps/web/src/components/snapcad/YakNetCloudBar.tsx index 014503e..f88ad1e 100644 --- a/apps/web/src/components/snapcad/YakNetCloudBar.tsx +++ b/apps/web/src/components/snapcad/YakNetCloudBar.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useCallback, useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; import { CheckCircle2, Cloud, @@ -12,6 +13,8 @@ import { Trash2, X, } from "lucide-react"; +import { cloudApiFetch } from "@/lib/cloudApi"; +import { getDesktopBridge, isDesktopRuntime, useIsDesktopRuntime } from "@/lib/desktopBridge"; import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { PlacementWorkplane } from "@/lib/placementWorkplane"; import { formatByteSize, type CloudProjectCollection, type CloudProjectSyncSkip } from "@/lib/cloudProjectSync"; @@ -72,7 +75,9 @@ export function YakNetCloudBar({ const [localOnlyProjects, setLocalOnlyProjects] = useState([]); const [maxProjectBytes, setMaxProjectBytes] = useState(0); const [statusBanner, setStatusBanner] = useState<{ type: "ok" | "err" | "info"; text: string } | null>(null); + const [desktopLoginPending, setDesktopLoginPending] = useState(false); + const isDesktop = useIsDesktopRuntime(); const accountWidgetHostRef = useRef(null); const initialSyncDoneRef = useRef(false); const userRef = useRef(null); @@ -82,7 +87,7 @@ export function YakNetCloudBar({ userRef.current = user; }, [user]); - // 1. CDNJS YakNet Hesap Menüsü Web Component'ini ve Silent SSO Frame'ini yükle + // 1. CDNJS YakNet Hesap Menüsü Web Component'ini ve (yalnızca web tarayıcısında) Silent SSO Frame'ini yükle useEffect(() => { if (typeof window === "undefined") return; @@ -96,6 +101,10 @@ export function YakNetCloudBar({ document.head.appendChild(script); } + // Masaüstü (.exe) çalışma zamanında harici tarayıcı + DPAPI Bearer token kullanıldığından, + // gömülü WebView cookie'si olmayan geliştirici konsolu SSO iframe'i başlatılmaz. + if (isDesktopRuntime()) return; + // YakNet Silent Cross-Subdomain SSO Frame'i doğrudan developer-console üzerinden hazırla const iframeId = "yaknet-sso-iframe-instance"; let iframe = document.getElementById(iframeId) as HTMLIFrameElement | null; @@ -123,7 +132,7 @@ export function YakNetCloudBar({ try { const collection = await onCollectLocalProjectsForCloud({ maxProjectBytes }); const localPayloads = collection.projects; - const res = await fetch("/cloud-api.php?action=sync_all", { + const res = await cloudApiFetch("/cloud-api.php?action=sync_all", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -132,6 +141,13 @@ export function YakNetCloudBar({ }), }); const data = await res.json(); + if (data?.token_invalid) { + setUser(null); + userRef.current = null; + setCloudList([]); + setCloudProjectCount(0); + initialSyncDoneRef.current = false; + } if (res.ok && data.ok && Array.isArray(data.projects)) { const serverSkipped: CloudProjectSyncSkip[] = Array.isArray(data.skipped) ? data.skipped.map((entry: { id?: string; name?: string; reason?: string; bytes?: number }) => ({ @@ -204,7 +220,7 @@ export function YakNetCloudBar({ try { // İstemciden gelen SSO verisi güvenilmez; sunucudaki doğrulanmış OAuth // oturumunu sorgularız. Oturum yoksa hiçbir şey yapmayız. - const res = await fetch("/cloud-api.php?action=session", { + const res = await cloudApiFetch("/cloud-api.php?action=session", { method: "GET", cache: "no-store", }); @@ -257,12 +273,31 @@ export function YakNetCloudBar({ // 4. SSO Çıkış İşlemi const handleSsoLogout = useCallback( async (redirect = false) => { + setDesktopLoginPending(false); setUser(null); userRef.current = null; setCloudList([]); setCloudProjectCount(0); + initialSyncDoneRef.current = false; + + const desktop = getDesktopBridge(); + if (desktop?.logoutYakNet) { + try { + await desktop.logoutYakNet(); + } catch { + // ignore + } + window.dispatchEvent( + new CustomEvent("yaknet-session-synced", { + detail: { authenticated: false, user: null }, + }), + ); + onNotice?.("YakNet masaüstü oturumunuz güvenli bir şekilde kapatıldı."); + return; + } + try { - await fetch("/cloud-api.php?action=logout", { method: "POST" }); + await cloudApiFetch("/cloud-api.php?action=logout", { method: "POST" }); } catch { // ignore } @@ -275,13 +310,43 @@ export function YakNetCloudBar({ window.location.href = "/logout.php"; } }, - [], + [onNotice], ); + // 4b. Masaüstü Uygulamasında Harici Tarayıcı Üzerinden YakNet Girişi + const handleStartDesktopLogin = useCallback(async () => { + const desktop = getDesktopBridge(); + if (!desktop?.startYakNetLogin) { + window.location.href = "/login.php"; + return; + } + setDesktopLoginPending(true); + setStatusBanner({ + type: "info", + text: "Varsayılan tarayıcınızda YakNet giriş sayfası açılıyor. Onayladığınızda oturumunuz otomatik olarak bağlanacaktır.", + }); + try { + const result = await desktop.startYakNetLogin(); + if (!result.started) { + setDesktopLoginPending(false); + setStatusBanner({ + type: "err", + text: result.error || "Harici tarayıcıda YakNet girişi başlatılamadı.", + }); + } + } catch { + setDesktopLoginPending(false); + setStatusBanner({ + type: "err", + text: "Harici tarayıcıda YakNet girişi başlatılamadı.", + }); + } + }, []); + // 5. Oturum durumunu sunucudan kontrol et const checkSession = useCallback(async () => { try { - const res = await fetch("/cloud-api.php?action=session", { cache: "no-store" }); + const res = await cloudApiFetch("/cloud-api.php?action=session", { cache: "no-store" }); if (!res.ok) return; const data = await res.json(); if (data.ok) { @@ -308,7 +373,7 @@ export function YakNetCloudBar({ } }, [performCloudSync]); - // 6. Global SSO Olaylarını Dinle (YAKNET_SSO_STATUS & yaknet-auth) + // 6. Global SSO Olaylarını ve Masaüstü OAuth Köprüsünü Dinle useEffect(() => { if (typeof window === "undefined") return; @@ -316,7 +381,7 @@ export function YakNetCloudBar({ if (!e.data || e.data.type !== "YAKNET_SSO_STATUS") return; if (e.data.authenticated && e.data.user) { void syncSsoSession(e.data.user); - } else if (e.data.authenticated === false && userRef.current) { + } else if (e.data.authenticated === false && userRef.current && !isDesktopRuntime()) { void handleSsoLogout(false); } }; @@ -326,7 +391,7 @@ export function YakNetCloudBar({ if (customEvt.detail) { if (customEvt.detail.authenticated && customEvt.detail.user) { void syncSsoSession(customEvt.detail.user); - } else if (customEvt.detail.authenticated === false && userRef.current) { + } else if (customEvt.detail.authenticated === false && userRef.current && !isDesktopRuntime()) { void handleSsoLogout(false); } } @@ -335,11 +400,59 @@ export function YakNetCloudBar({ window.addEventListener("message", handleWindowMessage); window.addEventListener("yaknet-auth", handleYaknetAuthEvent); + const desktop = getDesktopBridge(); + const unsubDesktopAuth = desktop?.onAuthUpdated?.((event) => { + if (typeof event.pending === "boolean") { + setDesktopLoginPending(event.pending); + } else if (!event.pending) { + setDesktopLoginPending(false); + } + + if (event.error) { + setModalOpen(true); + setStatusBanner({ type: "err", text: `YakNet Giriş Hatası: ${event.error}` }); + onNotice?.(`YakNet Giriş Hatası: ${event.error}`); + return; + } + + if (event.authenticated && event.user) { + setUser(event.user); + userRef.current = event.user; + initialSyncDoneRef.current = false; + if (event.cloudLoginCompleted) { + setStatusBanner({ + type: "ok", + text: `YakNet hesabınız bağlandı (${event.user.name}). Tasarımlarınız eşitleniyor...`, + }); + onNotice?.("YakNet hesabınızla giriş yapıldı. Tasarımlarınız eşitleniyor..."); + } + window.dispatchEvent( + new CustomEvent("yaknet-session-synced", { + detail: { authenticated: true, user: event.user }, + }), + ); + void checkSession(); + } else if (event.loggedOut) { + setUser(null); + userRef.current = null; + setCloudList([]); + setCloudProjectCount(0); + initialSyncDoneRef.current = false; + setStatusBanner({ type: "info", text: "YakNet oturumunuz güvenli bir şekilde kapatıldı." }); + window.dispatchEvent( + new CustomEvent("yaknet-session-synced", { + detail: { authenticated: false, user: null }, + }), + ); + } + }); + return () => { window.removeEventListener("message", handleWindowMessage); window.removeEventListener("yaknet-auth", handleYaknetAuthEvent); + unsubDesktopAuth?.(); }; - }, [handleSsoLogout, syncSsoSession]); + }, [checkSession, handleSsoLogout, onNotice, syncSsoSession]); useEffect(() => { void checkSession(); @@ -437,7 +550,7 @@ export function YakNetCloudBar({ const handleDeleteCloudProject = async (projectUid: string) => { try { - const res = await fetch("/cloud-api.php?action=delete", { + const res = await cloudApiFetch("/cloud-api.php?action=delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "delete", project_uid: projectUid }), @@ -518,24 +631,25 @@ export function YakNetCloudBar({ />
- {/* YakNet Bulut Tasarım Yönetimi Modalı */} - {modalOpen ? ( -
{ - if (e.target === e.currentTarget) setModalOpen(false); - }} - > + {/* YakNet Bulut Tasarım Yönetimi Modalı (topbar transform stacking-context dışında tam ekran Portal) */} + {modalOpen && typeof document !== "undefined" + ? createPortal( +
{ + if (e.target === e.currentTarget) setModalOpen(false); + }} + >
{dbConnected ? "Bulut Bağlantısı Aktif" : "Çevrimdışı Mod"} + {isDesktop && user ? " • Kalıcı Masaüstü Oturumu" : ""} {lastSyncedAt ? ` • Son Eşitleme: ${new Date(lastSyncedAt).toLocaleTimeString("tr-TR")}` : ""}
@@ -702,26 +817,75 @@ export function YakNetCloudBar({ {syncing ? "Eşitleniyor..." : "Şimdi Eşitle"} -
- - Çıkış Yap - + {isDesktop ? ( + + ) : ( + + + Çıkış Yap + + )} + ) : isDesktop ? ( + ) : ( ) : null}
-
- ) : null} + , + document.body, + ) + : null} ); } diff --git a/apps/web/src/lib/appUpdates.ts b/apps/web/src/lib/appUpdates.ts index f7ab078..e272fa9 100644 --- a/apps/web/src/lib/appUpdates.ts +++ b/apps/web/src/lib/appUpdates.ts @@ -1,4 +1,14 @@ -export const OFFICIAL_UPDATE_GUIDE_URL = "https://github.com/Formsmith746/SketchForge-3D#update-sketchforge-later"; +export const OFFICIAL_UPDATE_GUIDE_URL = "https://snap.yakhub.com.tr"; + +export type AppUpdateLifecycle = + | "idle" + | "checking" + | "available" + | "not-available" + | "downloading" + | "downloaded" + | "error" + | "unsupported"; export type AppUpdateStatus = { currentVersion: string; @@ -9,6 +19,9 @@ export type AppUpdateStatus = { installationReady: boolean; requiresUpdateKey: boolean; updateMode?: "local" | "server" | "desktop"; + status?: AppUpdateLifecycle; + downloaded?: boolean; + progressPercent?: number; checkError?: string; }; diff --git a/apps/web/src/lib/cad2dEngine.ts b/apps/web/src/lib/cad2dEngine.ts index 3e6496f..1d9633e 100644 --- a/apps/web/src/lib/cad2dEngine.ts +++ b/apps/web/src/lib/cad2dEngine.ts @@ -1,9 +1,11 @@ -import polygonClipping, { - type Geom, - type MultiPolygon as PcMultiPolygon, - type Polygon as PcPolygon, - type Ring as PcRing, -} from "polygon-clipping"; +import { + Clipper, + ClipType, + FillRule, + Point64, + type Path64, + type Paths64, +} from "clipper2-js"; import { Bezier } from "bezier-js"; export interface Point2D { @@ -20,101 +22,194 @@ export interface CadCompoundPolygon { export type CadMultiPolygon = CadCompoundPolygon[]; -/** - * Converts internal Point2D array to polygon-clipping Ring format [x, y][]. - */ -export function polygonToClippingRing(polygon: CadPolygon): PcRing { +const CAD2D_SCALE = 10000; + +function stripConsecutiveAndClosingDuplicates(pts: Path64): Path64 { + if (pts.length === 0) return []; + const out: Path64 = []; + for (let i = 0; i < pts.length; i++) { + const pt = pts[i]; + const prev = out[out.length - 1]; + if (!prev || prev.x !== pt.x || prev.y !== pt.y) { + out.push(pt); + } + } + while (out.length > 1 && out[0].x === out[out.length - 1].x && out[0].y === out[out.length - 1].y) { + out.pop(); + } + // Remove collinear duplicate vertices along straight segments + if (out.length >= 3) { + const simplified: Path64 = []; + const n = out.length; + for (let i = 0; i < n; i++) { + const a = out[(i - 1 + n) % n]; + const b = out[i]; + const c = out[(i + 1) % n]; + const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x); + const dot = (b.x - a.x) * (c.x - b.x) + (b.y - a.y) * (c.y - b.y); + if (cross === 0 && dot > 0) { + continue; + } + simplified.push(b); + } + if (simplified.length >= 3) return simplified; + } + return out; +} + +function toClipperPath(polygon: CadPolygon): Path64 { if (polygon.length === 0) return []; - const ring: PcRing = polygon.map((pt) => [pt.x, pt.y]); - // Ensure ring is closed - const first = ring[0]; - const last = ring[ring.length - 1]; - if (first[0] !== last[0] || first[1] !== last[1]) { - ring.push([first[0], first[1]]); + const raw: Point64[] = []; + for (let i = 0; i < polygon.length; i++) { + const pt = polygon[i]; + if (!Number.isFinite(pt.x) || !Number.isFinite(pt.y)) continue; + raw.push(new Point64(Math.round(pt.x * CAD2D_SCALE), Math.round(pt.y * CAD2D_SCALE))); } - return ring; + const clean = stripConsecutiveAndClosingDuplicates(raw); + if (clean.length < 3) return []; + // Normalize outer ring winding to positive area so FillRule.NonZero behaves uniformly + return Clipper.area(clean) < 0 ? Clipper.reversePath(clean) : clean; +} + +function fromClipperPath(path: Path64): CadPolygon { + const clean = stripConsecutiveAndClosingDuplicates(path); + if (clean.length < 3) return []; + const pts: CadPolygon = []; + for (let i = 0; i < clean.length; i++) { + pts.push({ + x: clean[i].x / CAD2D_SCALE, + y: clean[i].y / CAD2D_SCALE, + }); + } + return pts; +} + +function pointInPolygon(pt: Point2D, ring: CadPolygon): boolean { + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const xi = ring[i].x; + const yi = ring[i].y; + const xj = ring[j].x; + const yj = ring[j].y; + const intersect = + yi > pt.y !== yj > pt.y && + pt.x < ((xj - xi) * (pt.y - yi)) / (yj - yi || 1e-12) + xi; + if (intersect) inside = !inside; + } + return inside; +} + +function polygonInteriorSamplePoint(ring: CadPolygon): Point2D { + let sx = 0; + let sy = 0; + for (const pt of ring) { + sx += pt.x; + sy += pt.y; + } + const centroid = { x: sx / ring.length, y: sy / ring.length }; + if (pointInPolygon(centroid, ring)) return centroid; + return ring[0]; +} + +function pathsToCadMultiPolygon(paths: Paths64): CadMultiPolygon { + const outers: Array<{ poly: CadPolygon; area: number }> = []; + const holes: Array<{ poly: CadPolygon; sample: Point2D }> = []; + + for (let i = 0; i < paths.length; i++) { + const raw = stripConsecutiveAndClosingDuplicates(paths[i]); + if (raw.length < 3) continue; + const area = Clipper.area(raw); + if (Math.abs(area) < 1) continue; + const poly = fromClipperPath(raw); + if (poly.length < 3) continue; + if (area > 0) { + outers.push({ poly, area }); + } else { + holes.push({ poly, sample: polygonInteriorSamplePoint(poly) }); + } + } + + // Largest-to-smallest sort ensures holes attach to the tightest enclosing island if nested + outers.sort((a, b) => a.area - b.area); + const result: CadMultiPolygon = outers.map((o) => ({ outer: o.poly, holes: [] })); + + for (const hole of holes) { + let attached = false; + for (let i = 0; i < outers.length; i++) { + if (pointInPolygon(hole.sample, outers[i].poly)) { + result[i].holes.push(hole.poly); + attached = true; + break; + } + } + if (!attached) { + result.push({ outer: hole.poly, holes: [] }); + } + } + + return result; +} + +function runClipperBoolean(clipType: ClipType, polyA: CadPolygon, polyB: CadPolygon): CadMultiPolygon { + const pathA = toClipperPath(polyA); + const pathB = toClipperPath(polyB); + const subject: Paths64 = pathA.length >= 3 ? [pathA] : []; + const clip: Paths64 = pathB.length >= 3 ? [pathB] : []; + const solution = Clipper.BooleanOp(clipType, subject, clip, FillRule.NonZero); + return pathsToCadMultiPolygon(solution); } /** - * Converts a polygon-clipping Ring back to Point2D array, stripping redundant closing vertex. - */ -export function clippingRingToPolygon(ring: PcRing): CadPolygon { - if (ring.length <= 1) return []; - const points: CadPolygon = []; - const end = ring.length > 2 && ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1] - ? ring.length - 1 - : ring.length; - for (let i = 0; i < end; i++) { - points.push({ x: ring[i][0], y: ring[i][1] }); - } - return points; -} - -function pcMultiPolygonToCad(multiPoly: PcMultiPolygon): CadMultiPolygon { - return multiPoly.map((poly: PcPolygon) => { - const outer = poly.length > 0 ? clippingRingToPolygon(poly[0]) : []; - const holes = poly.slice(1).map((holeRing) => clippingRingToPolygon(holeRing)); - return { outer, holes }; - }); -} - -/** - * Performs 2D Boolean Union (A ∪ B) on two polygons. + * Performs 2D Boolean Union (A ∪ B) on two polygons via Clipper2. */ export function polygon2dUnion(polyA: CadPolygon, polyB: CadPolygon): CadMultiPolygon { - const ringA = polygonToClippingRing(polyA); - const ringB = polygonToClippingRing(polyB); - if (ringA.length < 3) return ringB.length >= 3 ? pcMultiPolygonToCad([[ringB]]) : []; - if (ringB.length < 3) return pcMultiPolygonToCad([[ringA]]); - - const geomA: PcPolygon[] = [[ringA]]; - const geomB: PcPolygon[] = [[ringB]]; - const result = polygonClipping.union(geomA as Geom, geomB as Geom); - return pcMultiPolygonToCad(result); + const pathA = toClipperPath(polyA); + const pathB = toClipperPath(polyB); + if (pathA.length < 3) { + return pathB.length >= 3 ? [{ outer: fromClipperPath(pathB), holes: [] }] : []; + } + if (pathB.length < 3) { + return [{ outer: fromClipperPath(pathA), holes: [] }]; + } + return runClipperBoolean(ClipType.Union, polyA, polyB); } /** - * Performs 2D Boolean Difference (A - B) on two polygons (e.g., cutting a hole inside plate A). + * Performs 2D Boolean Difference (A - B) on two polygons (e.g., cutting a hole inside plate A) via Clipper2. */ export function polygon2dDifference(polyA: CadPolygon, polyB: CadPolygon): CadMultiPolygon { - const ringA = polygonToClippingRing(polyA); - const ringB = polygonToClippingRing(polyB); - if (ringA.length < 3) return []; - if (ringB.length < 3) return pcMultiPolygonToCad([[ringA]]); - - const geomA: PcPolygon[] = [[ringA]]; - const geomB: PcPolygon[] = [[ringB]]; - const result = polygonClipping.difference(geomA as Geom, geomB as Geom); - return pcMultiPolygonToCad(result); + const pathA = toClipperPath(polyA); + const pathB = toClipperPath(polyB); + if (pathA.length < 3) return []; + if (pathB.length < 3) { + return [{ outer: fromClipperPath(pathA), holes: [] }]; + } + return runClipperBoolean(ClipType.Difference, polyA, polyB); } /** - * Performs 2D Boolean Intersection (A ∩ B) on two polygons. + * Performs 2D Boolean Intersection (A ∩ B) on two polygons via Clipper2. */ export function polygon2dIntersection(polyA: CadPolygon, polyB: CadPolygon): CadMultiPolygon { - const ringA = polygonToClippingRing(polyA); - const ringB = polygonToClippingRing(polyB); - if (ringA.length < 3 || ringB.length < 3) return []; - - const geomA: PcPolygon[] = [[ringA]]; - const geomB: PcPolygon[] = [[ringB]]; - const result = polygonClipping.intersection(geomA as Geom, geomB as Geom); - return pcMultiPolygonToCad(result); + const pathA = toClipperPath(polyA); + const pathB = toClipperPath(polyB); + if (pathA.length < 3 || pathB.length < 3) return []; + return runClipperBoolean(ClipType.Intersection, polyA, polyB); } /** - * Performs 2D Boolean XOR (A ⊕ B) on two polygons. + * Performs 2D Boolean XOR (A ⊕ B) on two polygons via Clipper2. */ export function polygon2dXor(polyA: CadPolygon, polyB: CadPolygon): CadMultiPolygon { - const ringA = polygonToClippingRing(polyA); - const ringB = polygonToClippingRing(polyB); - if (ringA.length < 3) return ringB.length >= 3 ? pcMultiPolygonToCad([[ringB]]) : []; - if (ringB.length < 3) return pcMultiPolygonToCad([[ringA]]); - - const geomA: PcPolygon[] = [[ringA]]; - const geomB: PcPolygon[] = [[ringB]]; - const result = polygonClipping.xor(geomA as Geom, geomB as Geom); - return pcMultiPolygonToCad(result); + const pathA = toClipperPath(polyA); + const pathB = toClipperPath(polyB); + if (pathA.length < 3) { + return pathB.length >= 3 ? [{ outer: fromClipperPath(pathB), holes: [] }] : []; + } + if (pathB.length < 3) { + return [{ outer: fromClipperPath(pathA), holes: [] }]; + } + return runClipperBoolean(ClipType.Xor, polyA, polyB); } /* ========================================================================= */ @@ -240,7 +335,6 @@ export function cadBezierIntersections(curveA: CadBezierCurve, curveB: CadBezier const intersects = bA.intersects(bB); return intersects.map((pairStr) => { - // pairs are string parameter values like "0.5/0.2" const tA = parseFloat(typeof pairStr === "string" ? pairStr.split("/")[0] : String(pairStr)); const pt = bA.get(isNaN(tA) ? 0.5 : tA); return { x: pt.x, y: pt.y }; @@ -298,7 +392,6 @@ export function applyParallelConstraint( if (flen < 1e-6) return [m1, m2]; const mlen = Math.hypot(m2.x - m1.x, m2.y - m1.y); - // Check direction alignment const dot = (m2.x - m1.x) * fdx + (m2.y - m1.y) * fdy; const sign = dot >= 0 ? 1 : -1; @@ -330,11 +423,9 @@ export function applyPerpendicularConstraint( if (flen < 1e-6) return [m1, m2]; const mlen = Math.hypot(m2.x - m1.x, m2.y - m1.y); - // Perpendicular unit vector (-dy, dx) const perpX = -fdy / flen; const perpY = fdx / flen; - // Choose the direction closest to current movingLine vector const currentDx = m2.x - m1.x; const currentDy = m2.y - m1.y; const dot = currentDx * perpX + currentDy * perpY; @@ -362,7 +453,6 @@ export function applyTangentConstraint( const d = Math.hypot(dx, dy); if (d <= radius) { - // Point is inside or on circle, return normal tangent at perimeter const angle = Math.atan2(dy, dx); const tangentPoint = { x: circleCenter.x + Math.cos(angle + Math.PI / 2) * radius, @@ -371,7 +461,6 @@ export function applyTangentConstraint( return [lineStartPoint, tangentPoint]; } - // Tangent angle offset const alpha = Math.asin(radius / d); const baseAngle = Math.atan2(circleCenter.y - lineStartPoint.y, circleCenter.x - lineStartPoint.x); const tangentAngle = baseAngle - alpha; diff --git a/apps/web/src/lib/cloudApi.ts b/apps/web/src/lib/cloudApi.ts new file mode 100644 index 0000000..9effe83 --- /dev/null +++ b/apps/web/src/lib/cloudApi.ts @@ -0,0 +1,53 @@ +"use client"; + +import { getDesktopBridge, normalizeCloudApiPath } from "@/lib/desktopBridge"; + +export type CloudApiRequestInit = { + method?: string; + headers?: Record; + body?: string; + cache?: RequestCache; +}; + +/** + * Dispatches `/cloud-api.php?...` requests transparently across both web browsers + * and the packaged Electron desktop runtime. + * + * Inside the Electron desktop executable (`127.0.0.1`), relative fetches would hit + * Next.js and 404. Routing via `desktopBridge.cloudRequest` sends the request cleanly + * from Electron main process over HTTPS with the user's DPAPI-encrypted long-lived + * desktop Bearer token — zero CORS issues and zero token exposure in `localStorage`. + */ +export async function cloudApiFetch(pathWithQuery: string, init: CloudApiRequestInit = {}): Promise { + const normalized = normalizeCloudApiPath(pathWithQuery); + if (!normalized) { + throw new Error(`Geçersiz bulut API yolu: ${pathWithQuery}`); + } + + const desktop = getDesktopBridge(); + if (desktop?.cloudRequest) { + const result = await desktop.cloudRequest({ + path: normalized, + method: init.method ?? "GET", + headers: init.headers, + body: init.body, + }); + if (!result.ok && result.status === 0) { + throw new Error(result.error || "YakNet Bulut servisine şu anda ulaşılamıyor."); + } + const status = Number.isFinite(result.status) && result.status >= 100 && result.status <= 599 ? result.status : 502; + return new Response(result.bodyText ?? "", { + status, + headers: { + "Content-Type": result.contentType || "application/json; charset=utf-8", + }, + }); + } + + return fetch(normalized, { + method: init.method, + headers: init.headers, + body: init.body, + cache: init.cache, + }); +} diff --git a/apps/web/src/lib/cloudComponents.ts b/apps/web/src/lib/cloudComponents.ts index 351689e..a98c2f7 100644 --- a/apps/web/src/lib/cloudComponents.ts +++ b/apps/web/src/lib/cloudComponents.ts @@ -1,3 +1,4 @@ +import { cloudApiFetch } from "@/lib/cloudApi"; import { createLocalId } from "@/lib/localIds"; import { normalizeSketchUpPrefs, type SketchUpWorkspacePrefs } from "@/lib/sketchupInterface"; import type { WorkplaneShape } from "@/types/sketchforge"; @@ -180,7 +181,7 @@ export async function listCloudComponents(params?: { if (params?.q && params.q.trim()) { search.set("q", params.q.trim()); } - const res = await fetch(`/cloud-api.php?${search.toString()}`, { + const res = await cloudApiFetch(`/cloud-api.php?${search.toString()}`, { method: "GET", cache: "no-store", }); @@ -221,7 +222,7 @@ export async function getCloudComponent(componentUid: string): Promise<{ action: "component_get", component_uid: componentUid, }); - const res = await fetch(`/cloud-api.php?${search.toString()}`, { + const res = await cloudApiFetch(`/cloud-api.php?${search.toString()}`, { method: "GET", cache: "no-store", }); @@ -248,7 +249,7 @@ export async function publishCloudComponent( error?: string; }> { try { - const res = await fetch("/cloud-api.php?action=component_publish", { + const res = await cloudApiFetch("/cloud-api.php?action=component_publish", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -286,7 +287,7 @@ export async function deleteCloudComponent(componentUid: string): Promise<{ error?: string; }> { try { - const res = await fetch("/cloud-api.php?action=component_delete", { + const res = await cloudApiFetch("/cloud-api.php?action=component_delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -314,7 +315,7 @@ export async function getCloudUserPrefs(): Promise<{ prefs: SketchUpWorkspacePrefs | null; }> { try { - const res = await fetch("/cloud-api.php?action=prefs_get", { + const res = await cloudApiFetch("/cloud-api.php?action=prefs_get", { method: "GET", cache: "no-store", }); @@ -340,7 +341,7 @@ export async function saveCloudUserPrefs( prefs: SketchUpWorkspacePrefs, ): Promise<{ ok: boolean; error?: string }> { try { - const res = await fetch("/cloud-api.php?action=prefs_save", { + const res = await cloudApiFetch("/cloud-api.php?action=prefs_save", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ diff --git a/apps/web/src/lib/desktopBridge.ts b/apps/web/src/lib/desktopBridge.ts new file mode 100644 index 0000000..1ab0001 --- /dev/null +++ b/apps/web/src/lib/desktopBridge.ts @@ -0,0 +1,315 @@ +"use client"; + +import { useEffect, useState } from "react"; +import type { DesktopMenuAction, SnapCadDesktopBridge } from "@/types/desktop"; + +const VALID_DESKTOP_MENU_ACTIONS = new Set([ + "file:new", + "file:open", + "file:save", + "file:save-as", + "file:save-and-quit", + "file:import", + "file:export-panel", + "file:export-skf", + "file:export-stl", + "file:export-3mf", + "file:export-step", + "file:export-obj", + "file:export-glb", + "file:export-dxf", + "file:export-svg", + "file:dashboard", + "edit:undo", + "edit:redo", + "edit:cut", + "edit:copy", + "edit:paste", + "edit:duplicate", + "edit:delete", + "edit:select-all", + "edit:clear-selection", + "edit:make-component", + "edit:make-unique", + "edit:group", + "edit:ungroup", + "edit:intersect", + "edit:make-solid", + "edit:make-hole", + "edit:mirror", + "edit:align", + "edit:drop-to-workplane", + "edit:snap-to-grid", + "edit:chamfer", + "edit:fillet", + "edit:hide", + "edit:show-hidden", + "edit:lock", + "view:toggle-left-toolset", + "view:toggle-tray", + "view:toggle-secondary-ribbon", + "view:sky-ground", + "view:back-edges", + "view:xray", + "view:style-shaded", + "view:style-monochrome", + "view:style-hidden-line", + "view:style-wireframe", + "view:style-blueprint", + "view:style-clay", + "view:style-cyberpunk", + "view:layers", + "view:solar", + "view:clear-guides", + "view:zoom-extents", + "view:reset-camera", + "view:toggle-projection", + "camera:isometric", + "camera:top", + "camera:bottom", + "camera:front", + "camera:back", + "camera:left", + "camera:right", + "camera:two-point", + "camera:zoom-selection", + "camera:previous", + "draw:shape-box", + "draw:shape-cylinder", + "draw:shape-sphere", + "draw:shape-cone", + "draw:shape-pyramid", + "draw:shape-wedge", + "draw:shape-round-roof", + "draw:shape-half-sphere", + "draw:shape-torus", + "draw:shape-tube", + "draw:shape-gear", + "draw:sketch-extrude", + "draw:sketch-revolve", + "draw:sketch-edit", + "draw:house-scene", + "tool:select", + "tool:eraser", + "tool:paint", + "tool:line", + "tool:freehand", + "tool:arc", + "tool:rectangle", + "tool:circle", + "tool:polygon", + "tool:3d-text", + "tool:move", + "tool:push-pull", + "tool:rotate", + "tool:scale", + "tool:offset", + "tool:follow-me", + "tool:tape", + "tool:protractor", + "tool:axes", + "tool:section", + "tool:orbit", + "tool:pan", + "tool:zoom", + "tool:walk", + "tool:wall-opening", + "tool:terrain", + "tool:structural-test", + "tool:ar-preview", + "tool:physics-toggle", + "tool:physics-reset", + "tray:entity-info", + "tray:outliner", + "tray:components", + "tray:materials", + "tray:styles", + "tray:tags", + "tray:shadows", + "tray:scenes", + "tray:instructor", + "window:drawing", + "window:circuits", + "window:codeblocks", + "window:classrooms", + "window:shared", + "window:challenges", + "window:customization", + "window:about", + "window:contact", + "window:kvkk", + "window:terms", + "window:security", + "window:keymap-classic", + "window:keymap-standard", + "window:command-palette", + "window:a11y", + "window:workspace-settings", + "window:settings", + "help:audit", + "help:voice", + "help:radar", + "help:shortcuts", + "help:tutorial", + "help:daily-challenges", +]); + +const GLOBAL_DESKTOP_MENU_ACTIONS = new Set([ + "file:new", + "file:open", + "file:save", + "file:save-as", + "file:save-and-quit", + "file:import", + "file:dashboard", + "window:drawing", + "window:circuits", + "window:codeblocks", + "window:classrooms", + "window:shared", + "window:challenges", + "window:customization", + "window:about", + "window:contact", + "window:kvkk", + "window:terms", + "window:security", + "window:command-palette", + "window:a11y", + "window:settings", + "help:shortcuts", +]); + +export function isEditorOnlyMenuAction(action: DesktopMenuAction): boolean { + return !GLOBAL_DESKTOP_MENU_ACTIONS.has(action); +} + +export const DESKTOP_MENU_COMMAND_EVENT = "snapcad:desktop-menu-command"; + +/** + * Returns the injected Electron desktop preload bridge when running inside + * the SnapCAD Studio desktop executable, or null in web / static builds. + */ +export function getDesktopBridge(): SnapCadDesktopBridge | null { + if (typeof window === "undefined") return null; + return window.snapcadDesktop ?? window.sketchforgeDesktop ?? null; +} + +/** + * True when running inside the Electron desktop shell rather than a web browser. + */ +export function isDesktopRuntime(): boolean { + if (typeof window === "undefined") return false; + if (getDesktopBridge() !== null) return true; + return typeof navigator !== "undefined" && /\bElectron\//i.test(navigator.userAgent || ""); +} + +/** + * Hydration-safe hook that flips true on mount only inside Electron. + * Web and static-export HTML remain identical across SSR and hydration. + */ +export function useIsDesktopRuntime(): boolean { + const [isDesktop, setIsDesktop] = useState(false); + + useEffect(() => { + setIsDesktop(isDesktopRuntime()); + }, []); + + return isDesktop; +} + +/** + * Normalizes a native desktop window title (`* Project — SnapCAD Studio`). + */ +export function sanitizeDesktopTitle(rawName?: string | null, dirty = false): string { + const cleaned = String(rawName ?? "") + .replace(/[\r\n\t\u0000-\u001f\u007f]+/g, " ") + .replace(/\s+/g, " ") + .trim() + .slice(0, 120); + const prefix = dirty ? "* " : ""; + if (!cleaned || cleaned.toLowerCase() === "snapcad studio") { + return `${prefix}SnapCAD Studio`; + } + if (cleaned.endsWith("— SnapCAD Studio") || cleaned.endsWith("- SnapCAD Studio")) { + return `${prefix}${cleaned}`; + } + return `${prefix}${cleaned} — SnapCAD Studio`; +} + +/** + * Runtime guard for menu actions arriving over Electron IPC. + */ +export function parseMenuAction(value: unknown): DesktopMenuAction | null { + if (typeof value !== "string") return null; + return VALID_DESKTOP_MENU_ACTIONS.has(value as DesktopMenuAction) ? (value as DesktopMenuAction) : null; +} + +/** + * Validates that an external link target uses an explicit http/https protocol. + */ +export function isAllowedExternalUrl(rawUrl: unknown): boolean { + if (typeof rawUrl !== "string") return false; + const trimmed = rawUrl.trim(); + if (!trimmed || trimmed.length > 4096) return false; + try { + const parsed = new URL(trimmed); + return parsed.protocol === "https:" || parsed.protocol === "http:"; + } catch { + return false; + } +} + +/** + * Validates and normalizes relative SnapCAD Cloud API endpoints (`/cloud-api.php?...`) + * before forwarding over Electron IPC. Rejects host-smuggling or arbitrary URLs. + */ +export function normalizeCloudApiPath(rawPath: unknown): string | null { + if (typeof rawPath !== "string") return null; + const trimmed = rawPath.trim(); + if (!trimmed || trimmed.length > 4096) return null; + if (trimmed === "/cloud-api.php" || trimmed.startsWith("/cloud-api.php?")) { + return trimmed; + } + return null; +} + +/** + * Converts low-level updater transport errors into concise Turkish UI messages. + */ +export function formatFriendlyUpdateError(rawMessage?: unknown): string { + const text = typeof rawMessage === "string" ? rawMessage.trim() : ""; + if (!text) return "Güncelleme denetlenemedi."; + const lower = text.toLowerCase(); + if (lower.includes("404") || lower.includes("latest.yml") || lower.includes("cannot find")) { + return "Güncelleme sunucusunda henüz yeni bir masaüstü kurulum paketi yayınlanmadı."; + } + if (lower.includes("err_network") || lower.includes("enotfound") || lower.includes("econnrefused") || lower.includes("etimedout") || lower.includes("fetch failed")) { + return "Güncelleme sunucusuna bağlanılamadı. İnternet bağlantınızı kontrol edin."; + } + return text; +} + +/** + * Builds Electron file-dialog extension filters from a suggested filename. + */ +export function exportFiltersForFilename(filename: string): Array<{ name: string; extensions: string[] }> { + const lower = filename.trim().toLowerCase(); + if (lower.endsWith(".skf")) return [{ name: "SnapCAD Projesi (.skf)", extensions: ["skf"] }]; + if (lower.endsWith(".stl")) return [{ name: "STL 3B Model (.stl)", extensions: ["stl"] }]; + if (lower.endsWith(".step") || lower.endsWith(".stp")) return [{ name: "STEP B-Rep (.step)", extensions: ["step", "stp"] }]; + if (lower.endsWith(".obj")) return [{ name: "Wavefront OBJ (.obj)", extensions: ["obj"] }]; + if (lower.endsWith(".glb")) return [{ name: "Binary glTF (.glb)", extensions: ["glb"] }]; + if (lower.endsWith(".3mf")) return [{ name: "3D Manufacturing (.3mf)", extensions: ["3mf"] }]; + if (lower.endsWith(".dxf")) return [{ name: "AutoCAD DXF (.dxf)", extensions: ["dxf"] }]; + if (lower.endsWith(".svg")) return [{ name: "Vektör SVG (.svg)", extensions: ["svg"] }]; + return [{ name: "Tüm Dosyalar", extensions: ["*"] }]; +} + +/** + * Dispatches a validated desktop menu command onto `window` for mounted studio views. + */ +export function dispatchDesktopMenuCommand(action: DesktopMenuAction): void { + if (typeof window === "undefined") return; + window.dispatchEvent(new CustomEvent(DESKTOP_MENU_COMMAND_EVENT, { detail: action })); +} diff --git a/apps/web/src/lib/glbImport.ts b/apps/web/src/lib/glbImport.ts index 8e8fc19..b9a72c0 100644 --- a/apps/web/src/lib/glbImport.ts +++ b/apps/web/src/lib/glbImport.ts @@ -1,6 +1,7 @@ import * as THREE from "three"; import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; import { createLocalId } from "@/lib/localIds"; +import { cleanTriangleSoup, normalizeClosedMeshWinding } from "@/lib/meshSanitizer"; import type { WorkplaneShape } from "@/types/sketchforge"; /** @@ -23,20 +24,26 @@ export async function importedShapeFromGlb(fileName: string, buffer: ArrayBuffer if (!posAttr) return; mesh.updateWorldMatrix(true, false); + const mirrored = mesh.matrixWorld.determinant() < 0; - for (let i = 0; i < posAttr.count; i++) { - tempVec.fromBufferAttribute(posAttr, i); - tempVec.applyMatrix4(mesh.matrixWorld); - rawPositions.push(tempVec.x, tempVec.y, tempVec.z); + for (let i = 0; i + 2 < posAttr.count; i += 3) { + const order = mirrored ? [i, i + 2, i + 1] : [i, i + 1, i + 2]; + for (const vi of order) { + tempVec.fromBufferAttribute(posAttr, vi); + tempVec.applyMatrix4(mesh.matrixWorld); + rawPositions.push(tempVec.x, tempVec.y, tempVec.z); + } } if (geom !== mesh.geometry) geom.dispose(); } }); - if (rawPositions.length === 0) { + const cleaned = cleanTriangleSoup(rawPositions); + if (cleaned.positions.length < 9) { throw new Error("GLB/GLTF dosyasında içe aktarılabilecek 3B geometri bulunamadı."); } + const cleanPositions = normalizeClosedMeshWinding(cleaned.positions).positions; let minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, @@ -45,13 +52,13 @@ export async function importedShapeFromGlb(fileName: string, buffer: ArrayBuffer maxY = Number.NEGATIVE_INFINITY, maxZ = Number.NEGATIVE_INFINITY; - for (let p = 0; p < rawPositions.length; p += 3) { - minX = Math.min(minX, rawPositions[p]); - maxX = Math.max(maxX, rawPositions[p]); - minY = Math.min(minY, rawPositions[p + 1]); - maxY = Math.max(maxY, rawPositions[p + 1]); - minZ = Math.min(minZ, rawPositions[p + 2]); - maxZ = Math.max(maxZ, rawPositions[p + 2]); + for (let p = 0; p < cleanPositions.length; p += 3) { + minX = Math.min(minX, cleanPositions[p]); + maxX = Math.max(maxX, cleanPositions[p]); + minY = Math.min(minY, cleanPositions[p + 1]); + maxY = Math.max(maxY, cleanPositions[p + 1]); + minZ = Math.min(minZ, cleanPositions[p + 2]); + maxZ = Math.max(maxZ, cleanPositions[p + 2]); } const width = Math.max(0.1, maxX - minX); @@ -61,11 +68,11 @@ export async function importedShapeFromGlb(fileName: string, buffer: ArrayBuffer const centerZ = (minZ + maxZ) / 2; const positions: number[] = []; - for (let p = 0; p < rawPositions.length; p += 3) { + for (let p = 0; p < cleanPositions.length; p += 3) { positions.push( - rawPositions[p] - centerX, - rawPositions[p + 1] - minY, - rawPositions[p + 2] - centerZ, + cleanPositions[p] - centerX, + cleanPositions[p + 1] - minY, + cleanPositions[p + 2] - centerZ, ); } diff --git a/apps/web/src/lib/ifcImport.ts b/apps/web/src/lib/ifcImport.ts new file mode 100644 index 0000000..4baadd8 --- /dev/null +++ b/apps/web/src/lib/ifcImport.ts @@ -0,0 +1,322 @@ +/** + * IFC (BIM) Browser & Desktop Importer for SnapCAD Studio + * Powered by web-ifc (MPL-2.0, local offline WebAssembly). + * Geometry import: IFC2X3 / IFC4 / IFC4X3 -> sanitized Y-up millimeter WorkplaneShape. + */ +import * as THREE from "three"; +import { createLocalId } from "@/lib/localIds"; +import { cleanTriangleSoup, normalizeClosedMeshWinding } from "@/lib/meshSanitizer"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +interface WebIfcApiLike { + Init(customLocateFileHandler?: (path: string, prefix: string) => string, forceSingleThread?: boolean): Promise; + OpenModel(data: Uint8Array, settings?: Record): number; + CloseModel(modelID: number): void; + GetModelSchema(modelID: number): string; + StreamAllMeshes( + modelID: number, + meshCallback: (mesh: { + expressID: number; + geometries: { + size(): number; + get(index: number): { + geometryExpressID: number; + flatTransformation: ArrayLike; + color: { x: number; y: number; z: number; w: number }; + }; + }; + }) => void, + ): void; + GetGeometry( + modelID: number, + geometryExpressID: number, + ): { + GetVertexData(): number; + GetVertexDataSize(): number; + GetIndexData(): number; + GetIndexDataSize(): number; + delete(): void; + }; + GetVertexArray(ptr: number, size: number): Float32Array; + GetIndexArray(ptr: number, size: number): Uint32Array; +} + +let cachedIfcApiPromise: Promise | null = null; +let ifcImportQueue: Promise = Promise.resolve(); + +async function getIfcApi(): Promise { + if (!cachedIfcApiPromise) { + cachedIfcApiPromise = (async () => { + const WebIFC = await import("web-ifc"); + const api = new WebIFC.IfcAPI() as unknown as WebIfcApiLike; + if (typeof window !== "undefined") { + await api.Init((path: string) => `/ifc/${path}`, true); + } else { + await api.Init(undefined, true); + } + return api; + })().catch((error) => { + cachedIfcApiPromise = null; + throw error; + }); + } + return cachedIfcApiPromise; +} + +export interface ImportedIfcDetails { + shape: WorkplaneShape; + schema: string; + productCount: number; + meshCount: number; + skippedCount: number; + triangleCount: number; +} + +function validateIfcHeader(bytes: Uint8Array): void { + const sampleLength = Math.min(bytes.byteLength, 1024 * 1024); + const header = new TextDecoder("utf-8", { fatal: false }).decode( + bytes.subarray(0, sampleLength), + ); + if ( + !/^\s*(?:\uFEFF)?\s*ISO-10303-21\s*;/i.test(header) || + !/FILE_SCHEMA\s*\(\s*\(\s*'IFC/i.test(header) + ) { + throw new Error("Bu dosya geçerli bir IFC (STEP BIM) modeli içermiyor."); + } +} + +export async function importedShapeWithDetailsFromIfc( + fileName: string, + bytes: Uint8Array, +): Promise { + const task = ifcImportQueue.then(() => + extractIfcGeometry(fileName, bytes), + ); + ifcImportQueue = task.catch(() => {}); + return task; +} + +export async function importedShapeFromIfc( + fileName: string, + bytes: Uint8Array, +): Promise { + const result = await importedShapeWithDetailsFromIfc(fileName, bytes); + return result.shape; +} + +async function extractIfcGeometry( + fileName: string, + bytes: Uint8Array, +): Promise { + validateIfcHeader(bytes); + const api = await getIfcApi(); + let modelID = -1; + + try { + modelID = api.OpenModel(bytes, { + COORDINATE_TO_ORIGIN: false, + CIRCLE_SEGMENTS: 32, + }); + if (modelID < 0) { + throw new Error("Desteklenmeyen IFC şeması veya okunamayan dosya."); + } + + const schema = api.GetModelSchema(modelID) || "IFC"; + const rawPositions: number[] = []; + const scaleMmMatrix = new THREE.Matrix4().makeScale(1000, 1000, 1000); + const localMatrix = new THREE.Matrix4(); + const vertexVec = new THREE.Vector3(); + + let productCount = 0; + let meshCount = 0; + let skippedCount = 0; + let representativeColor: string | null = null; + + api.StreamAllMeshes(modelID, (flat) => { + const partCount = flat.geometries.size(); + if (!partCount) return; + let productHadMesh = false; + + for (let part = 0; part < partCount; part += 1) { + const placed = flat.geometries.get(part); + let handle: ReturnType | null = null; + try { + handle = api.GetGeometry(modelID, placed.geometryExpressID); + const vertices = api.GetVertexArray( + handle.GetVertexData(), + handle.GetVertexDataSize(), + ); + const indices = api.GetIndexArray( + handle.GetIndexData(), + handle.GetIndexDataSize(), + ); + if (!vertices.length || !indices.length) { + skippedCount += 1; + continue; + } + + const vertexCount = vertices.length / 6; + if (!Number.isInteger(vertexCount) || indices.length % 3 !== 0) { + throw new Error(`Geçersiz IFC ağ verisi (#${flat.expressID}).`); + } + + const tf = placed.flatTransformation; + if (tf.length !== 16) { + throw new Error(`Geçersiz IFC yerleşim matrisi (#${flat.expressID}).`); + } + for (let k = 0; k < 16; k++) { + if (!Number.isFinite(tf[k])) { + throw new Error(`Sonlu olmayan IFC koordinatı (#${flat.expressID}).`); + } + } + + // web-ifc returns coordinates in metres, Y-up. Scale directly into millimetres. + localMatrix.fromArray(Array.from(tf)); + localMatrix.premultiply(scaleMmMatrix); + const mirrored = localMatrix.determinant() < 0; + + for (let t = 0; t + 2 < indices.length; t += 3) { + const i0 = indices[t]; + const i1 = mirrored ? indices[t + 2] : indices[t + 1]; + const i2 = mirrored ? indices[t + 1] : indices[t + 2]; + if (i0 >= vertexCount || i1 >= vertexCount || i2 >= vertexCount) { + throw new Error(`Geçersiz IFC üçgen indeksi (#${flat.expressID}).`); + } + + const triIndices = [i0, i1, i2]; + for (const vi of triIndices) { + const base = vi * 6; + const px = vertices[base]; + const py = vertices[base + 1]; + const pz = vertices[base + 2]; + if (!Number.isFinite(px) || !Number.isFinite(py) || !Number.isFinite(pz)) { + throw new Error(`Geçersiz IFC tepe koordinatı (#${flat.expressID}).`); + } + vertexVec.set(px, py, pz).applyMatrix4(localMatrix); + rawPositions.push(vertexVec.x, vertexVec.y, vertexVec.z); + } + } + + if (!representativeColor && placed.color) { + const clamp01 = (v: number, fb: number) => + Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : fb; + const r = Math.round(clamp01(placed.color.x, 0.58) * 255); + const g = Math.round(clamp01(placed.color.y, 0.64) * 255); + const b = Math.round(clamp01(placed.color.z, 0.72) * 255); + representativeColor = `#${((r << 16) | (g << 8) | b) + .toString(16) + .padStart(6, "0")}`; + } + + meshCount += 1; + productHadMesh = true; + } finally { + if (handle) handle.delete(); + } + } + + if (productHadMesh) productCount += 1; + }); + + if (rawPositions.length < 9) { + throw new Error("Bu IFC dosyasında içe aktarılabilecek kullanılabilir 3B geometri bulunamadı."); + } + + // Sanitize degenerate faces and normalize reversed closed winding + const sanitized = cleanTriangleSoup(rawPositions); + const normalized = normalizeClosedMeshWinding(sanitized.positions); + const cleanPositions = normalized.positions; + if (cleanPositions.length < 9) { + throw new Error("IFC içe aktarımındaki tüm üçgenler geçersiz veya sıfır alanlı."); + } + + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + + for (let i = 0; i + 2 < cleanPositions.length; i += 3) { + const x = cleanPositions[i]; + const y = cleanPositions[i + 1]; + const z = cleanPositions[i + 2]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (z < minZ) minZ = z; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + if (z > maxZ) maxZ = z; + } + + const spanX = Math.max(0.1, maxX - minX); + const spanY = Math.max(0.1, maxY - minY); + const spanZ = Math.max(0.1, maxZ - minZ); + const centerX = (minX + maxX) / 2; + const centerZ = (minZ + maxZ) / 2; + + const positions = new Array(cleanPositions.length); + for (let i = 0; i + 2 < cleanPositions.length; i += 3) { + positions[i] = cleanPositions[i] - centerX; + positions[i + 1] = cleanPositions[i + 1] - minY; + positions[i + 2] = cleanPositions[i + 2] - centerZ; + } + + const geom = new THREE.BufferGeometry(); + geom.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + geom.computeVertexNormals(); + const normAttr = geom.getAttribute("normal"); + const normals = new Array(positions.length); + for (let i = 0; i < normAttr.count; i += 1) { + normals[i * 3] = normAttr.getX(i); + normals[i * 3 + 1] = normAttr.getY(i); + normals[i * 3 + 2] = normAttr.getZ(i); + } + geom.dispose(); + + const width = Math.max(1, spanX); + const height = Math.max(1, spanY); + const depth = Math.max(1, spanZ); + const triangleCount = Math.floor(positions.length / 9); + + const shape: WorkplaneShape = { + id: createLocalId("uploaded-ifc"), + name: fileName.replace(/\.[^.]+$/, "") || "Imported IFC", + kind: "mesh", + color: representativeColor ?? "#64748b", + x: 0, + z: 0, + size: Math.max(width, depth), + width, + depth, + height, + rotation: 0, + rotationX: 0, + rotationZ: 0, + importedMesh: { + positions, + normals, + baseWidth: width, + baseDepth: depth, + baseHeight: height, + triangleCount, + sourceFormat: "ifc", + }, + locked: false, + hidden: false, + }; + + return { + shape, + schema, + productCount, + meshCount, + skippedCount, + triangleCount, + }; + } finally { + if (modelID >= 0) { + api.CloseModel(modelID); + } + } +} diff --git a/apps/web/src/lib/importExtensions.ts b/apps/web/src/lib/importExtensions.ts index 62b7641..2aade15 100644 --- a/apps/web/src/lib/importExtensions.ts +++ b/apps/web/src/lib/importExtensions.ts @@ -1,4 +1,4 @@ -const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "obj", "svg", "dxf", "glb", "gltf", "dwg"]); +const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "obj", "svg", "dxf", "glb", "gltf", "dwg", "ifc"]); function fileExtension(fileName: string) { return fileName.split(".").pop()?.toLowerCase() ?? ""; diff --git a/apps/web/src/lib/meshSanitizer.ts b/apps/web/src/lib/meshSanitizer.ts new file mode 100644 index 0000000..6af603c --- /dev/null +++ b/apps/web/src/lib/meshSanitizer.ts @@ -0,0 +1,369 @@ +/** + * Mesh Sanitizer & Orientation Guard for SnapCAD Studio + * Adapted from NassCAD data-integrity fixes (`_nasCleanTriangles`, `_nasNormalizeClosedMesh`). + */ +import * as THREE from "three"; + +export interface SanitizedTriangleSoup { + positions: number[]; + normals?: number[]; + droppedTriangles: number; + triangleCount: number; +} + +export interface NormalizedMeshResult { + positions: number[]; + normals?: number[]; + signedVolume: number; + closed: boolean; + wasFlipped: boolean; +} + +const DEGENERATE_AREA_SQ_EPS = 1e-24; +const CLOSED_EDGE_QUANTIZE_INV = 1000; // 0.001 mm tolerance + +function isFiniteTriplet(arr: number[], offset: number): boolean { + return ( + Number.isFinite(arr[offset]) && + Number.isFinite(arr[offset + 1]) && + Number.isFinite(arr[offset + 2]) + ); +} + +/** + * Strips degenerate (zero-area, repeated-vertex) or non-finite triangles from flat + * non-indexed triangle soup (`9` floats per triangle). + */ +export function cleanTriangleSoup( + rawPositions: number[], + rawNormals?: number[], +): SanitizedTriangleSoup { + const hasMatchingNormals = + Array.isArray(rawNormals) && rawNormals.length === rawPositions.length; + const positions: number[] = []; + const normals: number[] | undefined = hasMatchingNormals ? [] : undefined; + let droppedTriangles = 0; + + for (let i = 0; i + 8 < rawPositions.length; i += 9) { + if ( + !isFiniteTriplet(rawPositions, i) || + !isFiniteTriplet(rawPositions, i + 3) || + !isFiniteTriplet(rawPositions, i + 6) + ) { + droppedTriangles += 1; + continue; + } + + const ax = rawPositions[i]; + const ay = rawPositions[i + 1]; + const az = rawPositions[i + 2]; + const bx = rawPositions[i + 3]; + const by = rawPositions[i + 4]; + const bz = rawPositions[i + 5]; + const cx = rawPositions[i + 6]; + const cy = rawPositions[i + 7]; + const cz = rawPositions[i + 8]; + + const abx = bx - ax; + const aby = by - ay; + const abz = bz - az; + const acx = cx - ax; + const acy = cy - ay; + const acz = cz - az; + + const nx = aby * acz - abz * acy; + const ny = abz * acx - abx * acz; + const nz = abx * acy - aby * acx; + const areaSq4 = nx * nx + ny * ny + nz * nz; + + if (!Number.isFinite(areaSq4) || areaSq4 <= DEGENERATE_AREA_SQ_EPS) { + droppedTriangles += 1; + continue; + } + + for (let k = 0; k < 9; k++) { + positions.push(rawPositions[i + k]); + } + if (normals && rawNormals) { + let validNormalTriplet = true; + for (let k = 0; k < 9; k++) { + if (!Number.isFinite(rawNormals[i + k])) { + validNormalTriplet = false; + break; + } + } + if (validNormalTriplet) { + for (let k = 0; k < 9; k++) { + normals.push(rawNormals[i + k]); + } + } else { + // Compute flat face normal fallback so matching normal buffer never gets NaN + const invLen = 1 / Math.sqrt(areaSq4); + const fnx = nx * invLen; + const fny = ny * invLen; + const fnz = nz * invLen; + normals.push(fnx, fny, fnz, fnx, fny, fnz, fnx, fny, fnz); + } + } + } + + return { + positions, + normals, + droppedTriangles, + triangleCount: Math.floor(positions.length / 9), + }; +} + +/** + * Computes signed tetrahedral volume relative to first vertex `(ox, oy, oz)`. + * Positive value indicates outward CCW winding; negative value indicates inverted CW winding. + */ +export function computeSignedVolumeFromPositions(positions: number[]): number { + if (positions.length < 9) return 0; + const ox = positions[0]; + const oy = positions[1]; + const oz = positions[2]; + let sum6 = 0; + + for (let i = 0; i + 8 < positions.length; i += 9) { + const ax = positions[i] - ox; + const ay = positions[i + 1] - oy; + const az = positions[i + 2] - oz; + const bx = positions[i + 3] - ox; + const by = positions[i + 4] - oy; + const bz = positions[i + 5] - oz; + const cx = positions[i + 6] - ox; + const cy = positions[i + 7] - oy; + const cz = positions[i + 8] - oz; + + sum6 += + ax * (by * cz - bz * cy) + + ay * (bz * cx - bx * cz) + + az * (bx * cy - by * cx); + } + + return sum6 / 6; +} + +function vertexKey(x: number, y: number, z: number): string { + const qx = Math.round(x * CLOSED_EDGE_QUANTIZE_INV) || 0; + const qy = Math.round(y * CLOSED_EDGE_QUANTIZE_INV) || 0; + const qz = Math.round(z * CLOSED_EDGE_QUANTIZE_INV) || 0; + return `${qx},${qy},${qz}`; +} + +/** + * Checks whether every quantized undirected edge in a triangle soup is shared by an even + * number of half-edges (i.e. a closed watertight surface with no boundary cracks). + */ +export function isTriangleSoupWatertightClosed( + positions: number[], + maxTriangles = 150_000, +): boolean { + const triCount = Math.floor(positions.length / 9); + if (triCount < 4 || triCount > maxTriangles) return false; + + const undirectedEdgeCounts = new Map(); + for (let i = 0; i + 8 < positions.length; i += 9) { + const k0 = vertexKey(positions[i], positions[i + 1], positions[i + 2]); + const k1 = vertexKey(positions[i + 3], positions[i + 4], positions[i + 5]); + const k2 = vertexKey(positions[i + 6], positions[i + 7], positions[i + 8]); + if (k0 === k1 || k1 === k2 || k2 === k0) return false; + + const pairs: Array<[string, string]> = [ + [k0, k1], + [k1, k2], + [k2, k0], + ]; + for (const [a, b] of pairs) { + const key = a < b ? `${a}|${b}` : `${b}|${a}`; + undirectedEdgeCounts.set(key, (undirectedEdgeCounts.get(key) ?? 0) + 1); + } + } + + for (const count of undirectedEdgeCounts.values()) { + if (count % 2 !== 0) return false; + } + return undirectedEdgeCounts.size >= 6; +} + +/** + * Detects inverted closed meshes (negative signed volume on watertight shell) and + * reverses triangle winding + vertex normals so CSG booleans and STL/STEP exports stay valid. + */ +export function normalizeClosedMeshWinding( + rawPositions: number[], + rawNormals?: number[], + assumeClosed = false, +): NormalizedMeshResult { + const signedVolume = computeSignedVolumeFromPositions(rawPositions); + const closed = assumeClosed || isTriangleSoupWatertightClosed(rawPositions); + + if (!closed || signedVolume >= -1e-9 || rawPositions.length < 9) { + return { + positions: rawPositions, + normals: rawNormals, + signedVolume, + closed, + wasFlipped: false, + }; + } + + const positions = [...rawPositions]; + const hasNormals = + Array.isArray(rawNormals) && rawNormals.length === rawPositions.length; + const normals = hasNormals && rawNormals ? [...rawNormals] : undefined; + + for (let i = 0; i + 8 < positions.length; i += 9) { + // Swap vertex 1 (i+3..i+5) and vertex 2 (i+6..i+8) + for (let k = 0; k < 3; k++) { + const tmp = positions[i + 3 + k]; + positions[i + 3 + k] = positions[i + 6 + k]; + positions[i + 6 + k] = tmp; + } + if (normals) { + for (let k = 0; k < 3; k++) { + const tmp = normals[i + 3 + k]; + normals[i + 3 + k] = normals[i + 6 + k]; + normals[i + 6 + k] = tmp; + } + for (let k = 0; k < 9; k++) { + normals[i + k] = -normals[i + k]; + } + } + } + + return { + positions, + normals, + signedVolume: -signedVolume, + closed, + wasFlipped: true, + }; +} + +/** + * Sanitizes a THREE.BufferGeometry in-place by dropping degenerate / zero-area triangles + * while preserving group draw ranges, and optionally normalizing inverted closed winding. + */ +export function sanitizeBufferGeometry( + geometry: THREE.BufferGeometry, + options?: { normalizeClosedWinding?: boolean; assumeClosed?: boolean }, +): THREE.BufferGeometry { + const posAttr = geometry.getAttribute("position"); + if (!posAttr || posAttr.itemSize !== 3 || posAttr.count < 3) { + return geometry; + } + + const indexAttr = geometry.getIndex(); + const srcIndex = indexAttr?.array; + const totalIndices = srcIndex ? srcIndex.length : posAttr.count; + const removedByGroup = new Uint32Array(geometry.groups.length); + let filteredIndices: number[] | null = null; + + for (let t = 0; t + 2 < totalIndices; t += 3) { + const a = srcIndex ? Number(srcIndex[t]) : t; + const b = srcIndex ? Number(srcIndex[t + 1]) : t + 1; + const c = srcIndex ? Number(srcIndex[t + 2]) : t + 2; + + const ax = posAttr.getX(a); + const ay = posAttr.getY(a); + const az = posAttr.getZ(a); + const bx = posAttr.getX(b); + const by = posAttr.getY(b); + const bz = posAttr.getZ(b); + const cx = posAttr.getX(c); + const cy = posAttr.getY(c); + const cz = posAttr.getZ(c); + + const abx = bx - ax; + const aby = by - ay; + const abz = bz - az; + const acx = cx - ax; + const acy = cy - ay; + const acz = cz - az; + const nx = aby * acz - abz * acy; + const ny = abz * acx - abx * acz; + const nz = abx * acy - aby * acx; + const areaSq4 = nx * nx + ny * ny + nz * nz; + + const badTriangle = + a === b || + b === c || + a === c || + !Number.isFinite(areaSq4) || + areaSq4 <= DEGENERATE_AREA_SQ_EPS; + + if (badTriangle) { + if (!filteredIndices) { + filteredIndices = []; + for (let k = 0; k < t; k++) { + filteredIndices.push(srcIndex ? Number(srcIndex[k]) : k); + } + } + geometry.groups.forEach((group, groupIndex) => { + if (t >= group.start && t < group.start + group.count) { + removedByGroup[groupIndex] += 3; + } + }); + continue; + } + + if (filteredIndices) { + filteredIndices.push(a, b, c); + } + } + + if (filteredIndices) { + geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(filteredIndices), 1)); + let droppedBefore = 0; + geometry.groups.forEach((group, groupIndex) => { + group.start -= droppedBefore; + group.count = Math.max(0, group.count - removedByGroup[groupIndex]); + droppedBefore += removedByGroup[groupIndex]; + }); + } + + if (options?.normalizeClosedWinding) { + const activeIndex = geometry.getIndex(); + const count = activeIndex ? activeIndex.count : posAttr.count; + if (count >= 9) { + const idxArr = activeIndex?.array; + const getPt = (idx: number): [number, number, number] => [ + posAttr.getX(idx), + posAttr.getY(idx), + posAttr.getZ(idx), + ]; + const soup: number[] = []; + for (let t = 0; t + 2 < count; t += 3) { + const ia = idxArr ? Number(idxArr[t]) : t; + const ib = idxArr ? Number(idxArr[t + 1]) : t + 1; + const ic = idxArr ? Number(idxArr[t + 2]) : t + 2; + soup.push(...getPt(ia), ...getPt(ib), ...getPt(ic)); + } + const signedVolume = computeSignedVolumeFromPositions(soup); + const closed = options.assumeClosed || isTriangleSoupWatertightClosed(soup); + if (closed && signedVolume < -1e-9) { + if (activeIndex) { + const arr = activeIndex.array as Uint16Array | Uint32Array; + for (let t = 0; t + 2 < arr.length; t += 3) { + const tmp = arr[t + 1]; + arr[t + 1] = arr[t + 2]; + arr[t + 2] = tmp; + } + activeIndex.needsUpdate = true; + } else { + const nonIndexedPositions = normalizeClosedMeshWinding(soup, undefined, true).positions; + geometry.setAttribute( + "position", + new THREE.Float32BufferAttribute(nonIndexedPositions, 3), + ); + } + geometry.computeVertexNormals(); + } + } + } + + return geometry; +} diff --git a/apps/web/src/lib/objImport.ts b/apps/web/src/lib/objImport.ts index db6b294..ea0d1ff 100644 --- a/apps/web/src/lib/objImport.ts +++ b/apps/web/src/lib/objImport.ts @@ -1,6 +1,7 @@ import * as THREE from "three"; import { createLocalId } from "@/lib/localIds"; import { zUpToSketchForge } from "@/lib/meshCoordinates"; +import { cleanTriangleSoup, normalizeClosedMeshWinding } from "@/lib/meshSanitizer"; import type { WorkplaneShape } from "@/types/sketchforge"; type ObjFaceVertex = { @@ -106,9 +107,12 @@ function importedObjShapeFromTriangles( rawPositions: number[], rawNormals: number[] | undefined, ): WorkplaneShape { - if (rawPositions.length < 9 || rawPositions.length % 9 !== 0) { + const cleaned = cleanTriangleSoup(rawPositions, rawNormals); + if (cleaned.positions.length < 9 || cleaned.positions.length % 9 !== 0) { throw new Error("OBJ has no readable mesh geometry"); } + const normalized = normalizeClosedMeshWinding(cleaned.positions, cleaned.normals); + const cleanPositions = normalized.positions; let minX = Number.POSITIVE_INFINITY; let minY = Number.POSITIVE_INFINITY; @@ -117,10 +121,10 @@ function importedObjShapeFromTriangles( let maxY = Number.NEGATIVE_INFINITY; let maxZ = Number.NEGATIVE_INFINITY; - for (let index = 0; index < rawPositions.length; index += 3) { - const x = rawPositions[index]; - const y = rawPositions[index + 1]; - const z = rawPositions[index + 2]; + for (let index = 0; index < cleanPositions.length; index += 3) { + const x = cleanPositions[index]; + const y = cleanPositions[index + 1]; + const z = cleanPositions[index + 2]; minX = Math.min(minX, x); minY = Math.min(minY, y); minZ = Math.min(minZ, z); @@ -138,17 +142,17 @@ function importedObjShapeFromTriangles( const centerX = (minX + maxX) / 2; const centerZ = (minZ + maxZ) / 2; const positions: number[] = []; - for (let index = 0; index < rawPositions.length; index += 3) { + for (let index = 0; index < cleanPositions.length; index += 3) { positions.push( - rawPositions[index] - centerX, - rawPositions[index + 1] - minY, - rawPositions[index + 2] - centerZ, + cleanPositions[index] - centerX, + cleanPositions[index + 1] - minY, + cleanPositions[index + 2] - centerZ, ); } - const normals = rawNormals?.length === rawPositions.length - ? [...rawNormals] - : generatedFaceNormals(rawPositions); + const normals = !normalized.wasFlipped && normalized.normals?.length === cleanPositions.length + ? [...normalized.normals] + : generatedFaceNormals(cleanPositions); const width = Math.max(1, sizeX); const height = Math.max(1, sizeY); const depth = Math.max(1, sizeZ); @@ -173,7 +177,7 @@ function importedObjShapeFromTriangles( baseWidth: width, baseDepth: depth, baseHeight: height, - triangleCount: rawPositions.length / 9, + triangleCount: positions.length / 9, sourceFormat: "obj", }, locked: false, diff --git a/apps/web/src/lib/offsetKernel.ts b/apps/web/src/lib/offsetKernel.ts index 9b95532..66c34cf 100644 --- a/apps/web/src/lib/offsetKernel.ts +++ b/apps/web/src/lib/offsetKernel.ts @@ -1,8 +1,28 @@ +import { + Clipper, + ClipType, + FillRule, + Point64, + type Path64, + type Paths64, +} from "clipper2-js"; +import type { SketchProfile, SketchPoint, SketchSegment } from "@/types/sketchforge"; + export interface Point2D { x: number; z: number; } +export type OffsetJoinType = "miter" | "round" | "bevel"; + +export interface OffsetOptions { + joinType?: OffsetJoinType; + miterLimit?: number; + arcTolerance?: number; +} + +const CLIPPER_SCALE = 10000; + /** * Computes the signed polygon area to determine winding direction. */ @@ -17,114 +37,544 @@ export function polygonSignedArea(points: Point2D[]): number { return area * 0.5; } -/** - * Intersects two 2D lines defined by a point and a direction vector. - */ -function intersectLines( - p1: Point2D, - d1: Point2D, - p2: Point2D, - d2: Point2D, -): Point2D | null { - const cross = d1.x * d2.z - d1.z * d2.x; - if (Math.abs(cross) < 1e-6) { - // Parallel or colinear - return null; +function stripConsecutiveAndCollinear(path: Path64): Path64 { + if (path.length === 0) return []; + const out: Path64 = []; + for (let i = 0; i < path.length; i++) { + const pt = path[i]; + const prev = out[out.length - 1]; + if (!prev || prev.x !== pt.x || prev.y !== pt.y) { + out.push(pt); + } } - const dx = p2.x - p1.x; - const dz = p2.z - p1.z; - const t = (dx * d2.z - dz * d2.x) / cross; - return { - x: p1.x + t * d1.x, - z: p1.z + t * d1.z, - }; + while (out.length > 1 && out[0].x === out[out.length - 1].x && out[0].y === out[out.length - 1].y) { + out.pop(); + } + if (out.length < 3) return out; + + const simplified: Path64 = []; + const n = out.length; + for (let i = 0; i < n; i++) { + const a = out[(i - 1 + n) % n]; + const b = out[i]; + const c = out[(i + 1) % n]; + const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x); + const dot = (b.x - a.x) * (c.x - b.x) + (b.y - a.y) * (c.y - b.y); + if (cross === 0 && dot > 0) { + continue; + } + simplified.push(b); + } + return simplified.length >= 3 ? simplified : out; } -/** - * Offsets a closed 2D polygon (e.g., room perimeter to generate wall thickness). - * @param points Array of 2D vertices (ordered clockwise or counter-clockwise) - * @param distance Offset distance in mm (positive = outward, negative = inward/duvar kalınlığı) - * @param maxMiterRatio Limits miter spikes on sharp corners (default 3.0) - */ -export function offsetPolygon(points: Point2D[], distance: number, maxMiterRatio = 3.0): Point2D[] { - const n = points.length; - if (n < 3 || Math.abs(distance) < 0.001) return [...points]; +function dedupeFloatPolygon(points: Point2D[]): Point2D[] { + const out: Point2D[] = []; + for (const pt of points) { + if (!Number.isFinite(pt.x) || !Number.isFinite(pt.z)) continue; + const prev = out[out.length - 1]; + if (!prev || Math.hypot(pt.x - prev.x, pt.z - prev.z) > 1e-6) { + out.push({ x: pt.x, z: pt.z }); + } + } + while ( + out.length > 1 && + Math.hypot(out[0].x - out[out.length - 1].x, out[0].z - out[out.length - 1].z) <= 1e-6 + ) { + out.pop(); + } + return out; +} - // Check winding order: if area > 0, counter-clockwise - const area = polygonSignedArea(points); - const isCCW = area > 0; - const sign = isCCW ? 1 : -1; +function pointsToPath64(points: Point2D[]): Path64 { + const path: Path64 = []; + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (!Number.isFinite(p.x) || !Number.isFinite(p.z)) continue; + path.push(new Point64(Math.round(p.x * CLIPPER_SCALE), Math.round(p.z * CLIPPER_SCALE))); + } + return stripConsecutiveAndCollinear(path); +} - // 1. Calculate edge vectors and normals - const shiftedLines: Array<{ point: Point2D; dir: Point2D }> = []; - for (let i = 0; i < n; i++) { - const p0 = points[i]; - const p1 = points[(i + 1) % n]; - const dx = p1.x - p0.x; - const dz = p1.z - p0.z; - const len = Math.hypot(dx, dz); - if (len < 1e-5) continue; +function ensurePositivePath(points: Point2D[]): Path64 { + const path = pointsToPath64(points); + if (path.length < 3) return []; + return Clipper.area(path) < 0 ? Clipper.reversePath(path) : path; +} - const dirX = dx / len; - const dirZ = dz / len; - - // Normal pointing outward - const normX = dirZ * sign; - const normZ = -dirX * sign; - - const shiftedP0 = { - x: p0.x + normX * distance, - z: p0.z + normZ * distance, - }; - - shiftedLines.push({ - point: shiftedP0, - dir: { x: dirX, z: dirZ }, +function path64ToPoints(path: Path64): Point2D[] { + const clean = stripConsecutiveAndCollinear(path); + const out: Point2D[] = []; + for (let i = 0; i < clean.length; i++) { + out.push({ + x: Number((clean[i].x / CLIPPER_SCALE).toFixed(4)), + z: Number((clean[i].y / CLIPPER_SCALE).toFixed(4)), }); } + return out; +} - const lineCount = shiftedLines.length; - if (lineCount < 3) return [...points]; +function buildPositiveOutwardMasks( + ccwRing: Point2D[], + distance: number, + joinType: OffsetJoinType, + miterLimit: number, + arcTolerance: number, +): Paths64 { + const masks: Paths64 = []; + const basePath = ensurePositivePath(ccwRing); + if (basePath.length < 3) return masks; + masks.push(basePath); - // 2. Intersect consecutive shifted edges - const result: Point2D[] = []; - for (let i = 0; i < lineCount; i++) { - const prevLine = shiftedLines[(i - 1 + lineCount) % lineCount]; - const currLine = shiftedLines[i]; + const n = ccwRing.length; + const edgeTangents: Point2D[] = []; + const outwardNormals: Point2D[] = []; + const edgeLengths: number[] = []; + const innerPad = Math.max(0.05, Math.min(0.5, distance * 0.15)); - const isect = intersectLines(prevLine.point, prevLine.dir, currLine.point, currLine.dir); - if (isect) { - // Check miter distance to avoid extreme spikes on acute angles - const orig = points[i]; - const distFromOrig = Math.hypot(isect.x - orig.x, isect.z - orig.z); - if (distFromOrig > Math.abs(distance) * maxMiterRatio) { - // Clamp to bevel - const avgNormX = (prevLine.dir.z - currLine.dir.z) * -0.5 * sign; - const avgNormZ = (currLine.dir.x - prevLine.dir.x) * -0.5 * sign; - const avgLen = Math.hypot(avgNormX, avgNormZ) || 1; - result.push({ - x: orig.x + (avgNormX / avgLen) * distance * maxMiterRatio, - z: orig.z + (avgNormZ / avgLen) * distance * maxMiterRatio, - }); - } else { - result.push({ - x: Number(isect.x.toFixed(2)), - z: Number(isect.z.toFixed(2)), - }); - } + for (let i = 0; i < n; i++) { + const a = ccwRing[i]; + const b = ccwRing[(i + 1) % n]; + const dx = b.x - a.x; + const dz = b.z - a.z; + const len = Math.hypot(dx, dz); + edgeLengths.push(len); + if (len < 1e-8) { + edgeTangents.push({ x: 1, z: 0 }); + outwardNormals.push({ x: 0, z: -1 }); } else { - // Parallel fallback - result.push({ - x: Number(currLine.point.x.toFixed(2)), - z: Number(currLine.point.z.toFixed(2)), - }); + edgeTangents.push({ x: dx / len, z: dz / len }); + // For CCW polygon in (x, z), right-hand normal (dz, -dx) points outward + outwardNormals.push({ x: dz / len, z: -dx / len }); + } + + if (len >= 1e-8) { + const nOut = outwardNormals[i]; + // Anchor slightly inside basePath so Clipper union merges shared boundaries cleanly + const strip = ensurePositivePath([ + { x: a.x - nOut.x * innerPad, z: a.z - nOut.z * innerPad }, + { x: a.x + nOut.x * distance, z: a.z + nOut.z * distance }, + { x: b.x + nOut.x * distance, z: b.z + nOut.z * distance }, + { x: b.x - nOut.x * innerPad, z: b.z - nOut.z * innerPad }, + ]); + if (strip.length >= 3) masks.push(strip); } } + for (let i = 0; i < n; i++) { + const prevIdx = (i - 1 + n) % n; + const p = ccwRing[i]; + const tPrev = edgeTangents[prevIdx]; + const tCurr = edgeTangents[i]; + const nPrev = outwardNormals[prevIdx]; + const nCurr = outwardNormals[i]; + + // Cross product of tangents on CCW contour: > 0 means convex outward corner + const turnCross = tPrev.x * tCurr.z - tPrev.z * tCurr.x; + if (turnCross <= 1e-6) continue; + + // Overlap slightly back along incoming/outgoing edges so union has zero touching-only slits + const deltaPrev = Math.min(edgeLengths[prevIdx] * 0.2, innerPad); + const deltaCurr = Math.min(edgeLengths[i] * 0.2, innerPad); + const anchor = { + x: p.x - (nPrev.x + nCurr.x) * (innerPad * 0.5), + z: p.z - (nPrev.z + nCurr.z) * (innerPad * 0.5), + }; + const pPrevOut = { x: p.x + nPrev.x * distance, z: p.z + nPrev.z * distance }; + const pCurrOut = { x: p.x + nCurr.x * distance, z: p.z + nCurr.z * distance }; + const pPrevOverlap = { + x: pPrevOut.x - tPrev.x * deltaPrev, + z: pPrevOut.z - tPrev.z * deltaPrev, + }; + const pCurrOverlap = { + x: pCurrOut.x + tCurr.x * deltaCurr, + z: pCurrOut.z + tCurr.z * deltaCurr, + }; + const pPrevAnchorOverlap = { + x: anchor.x - tPrev.x * deltaPrev, + z: anchor.z - tPrev.z * deltaPrev, + }; + const pCurrAnchorOverlap = { + x: anchor.x + tCurr.x * deltaCurr, + z: anchor.z + tCurr.z * deltaCurr, + }; + + if (joinType === "bevel") { + const poly = ensurePositivePath([ + anchor, + pPrevAnchorOverlap, + pPrevOverlap, + pPrevOut, + pCurrOut, + pCurrOverlap, + pCurrAnchorOverlap, + ]); + if (poly.length >= 3) masks.push(poly); + continue; + } + + if (joinType === "round") { + const a0 = Math.atan2(nPrev.z, nPrev.x); + let a1 = Math.atan2(nCurr.z, nCurr.x); + if (a1 < a0) a1 += Math.PI * 2; + const sweep = a1 - a0; + const stepAngle = Math.acos( + Math.max( + -1, + Math.min(1, 1 - Math.min(arcTolerance, distance * 0.5) / Math.max(distance, 1e-6)), + ), + ); + const steps = Math.max(2, Math.min(32, Math.ceil(sweep / Math.max(stepAngle, 0.12)))); + const fan: Point2D[] = [anchor, pPrevAnchorOverlap, pPrevOverlap, pPrevOut]; + for (let s = 1; s < steps; s++) { + const ang = a0 + (sweep * s) / steps; + fan.push({ x: p.x + Math.cos(ang) * distance, z: p.z + Math.sin(ang) * distance }); + } + fan.push(pCurrOut, pCurrOverlap, pCurrAnchorOverlap); + const fanPath = ensurePositivePath(fan); + if (fanPath.length >= 3) masks.push(fanPath); + continue; + } + + // Miter join clamped by miterLimit + const denom = 1 + nPrev.x * nCurr.x + nPrev.z * nCurr.z; + const miterScale = denom > 1e-6 ? Math.sqrt(2 / denom) : Infinity; + if (denom > 1e-6 && miterScale <= miterLimit) { + const invDenom = distance / denom; + const miterPt: Point2D = { + x: p.x + (nPrev.x + nCurr.x) * invDenom, + z: p.z + (nPrev.z + nCurr.z) * invDenom, + }; + const quad = ensurePositivePath([ + anchor, + pPrevAnchorOverlap, + pPrevOverlap, + miterPt, + pCurrOverlap, + pCurrAnchorOverlap, + ]); + if (quad.length >= 3) masks.push(quad); + } else { + const bx = nPrev.x + nCurr.x; + const bz = nPrev.z + nCurr.z; + const blen = Math.hypot(bx, bz); + if (blen > 1e-6) { + const ux = bx / blen; + const uz = bz / blen; + const capDist = distance * miterLimit; + const cutBase = { x: p.x + ux * capDist, z: p.z + uz * capDist }; + const tx = -uz; + const tz = ux; + const projPrev = (pPrevOut.x - cutBase.x) * ux + (pPrevOut.z - cutBase.z) * uz; + const projCurr = (pCurrOut.x - cutBase.x) * ux + (pCurrOut.z - cutBase.z) * uz; + const denomPrev = tPrev.x * ux + tPrev.z * uz; + const denomCurr = tCurr.x * ux + tCurr.z * uz; + const c1 = + Math.abs(denomPrev) > 1e-5 + ? { + x: pPrevOut.x - (tPrev.x * projPrev) / denomPrev, + z: pPrevOut.z - (tPrev.z * projPrev) / denomPrev, + } + : { x: cutBase.x + tx * distance * 0.25, z: cutBase.z + tz * distance * 0.25 }; + const c2 = + Math.abs(denomCurr) > 1e-5 + ? { + x: pCurrOut.x - (tCurr.x * projCurr) / denomCurr, + z: pCurrOut.z - (tCurr.z * projCurr) / denomCurr, + } + : { x: cutBase.x - tx * distance * 0.25, z: cutBase.z - tz * distance * 0.25 }; + const poly = ensurePositivePath([ + anchor, + pPrevAnchorOverlap, + pPrevOverlap, + c1, + c2, + pCurrOverlap, + pCurrAnchorOverlap, + ]); + if (poly.length >= 3) masks.push(poly); + } else { + const tri = ensurePositivePath([ + anchor, + pPrevAnchorOverlap, + pPrevOverlap, + pPrevOut, + pCurrOut, + pCurrOverlap, + pCurrAnchorOverlap, + ]); + if (tri.length >= 3) masks.push(tri); + } + } + } + + return masks; +} + +function buildInwardErosionMasks( + ccwRing: Point2D[], + distance: number, + joinType: OffsetJoinType, + miterLimit: number, + arcTolerance: number, +): Paths64 { + const masks: Paths64 = []; + const n = ccwRing.length; + const edgeTangents: Point2D[] = []; + const inwardNormals: Point2D[] = []; + + for (let i = 0; i < n; i++) { + const a = ccwRing[i]; + const b = ccwRing[(i + 1) % n]; + const dx = b.x - a.x; + const dz = b.z - a.z; + const len = Math.hypot(dx, dz); + if (len < 1e-8) { + edgeTangents.push({ x: 1, z: 0 }); + inwardNormals.push({ x: 0, z: 1 }); + continue; + } + const tx = dx / len; + const tz = dz / len; + // Inward normal for CCW contour in (x, z) is (-tz, tx) + const nx = -tz; + const nz = tx; + edgeTangents.push({ x: tx, z: tz }); + inwardNormals.push({ x: nx, z: nz }); + + // Extend strip slightly outward (-0.5 mm) so boundary rounding leaves zero hairline slivers + const outerPad = Math.max(0.25, Math.min(2, distance * 0.1)); + const strip = ensurePositivePath([ + { x: a.x - nx * outerPad, z: a.z - nz * outerPad }, + { x: b.x - nx * outerPad, z: b.z - nz * outerPad }, + { x: b.x + nx * distance, z: b.z + nz * distance }, + { x: a.x + nx * distance, z: a.z + nz * distance }, + ]); + if (strip.length >= 3) masks.push(strip); + } + + for (let i = 0; i < n; i++) { + const prevIdx = (i - 1 + n) % n; + const p = ccwRing[i]; + const tPrev = edgeTangents[prevIdx]; + const tCurr = edgeTangents[i]; + const nPrev = inwardNormals[prevIdx]; + const nCurr = inwardNormals[i]; + + const turnCross = tPrev.x * tCurr.z - tPrev.z * tCurr.x; + const tangentDot = tPrev.x * tCurr.x + tPrev.z * tCurr.z; + + if (turnCross < -1e-6) { + // Reflex (concave) corner: fill erosion notch between p_i + d*nPrev and p_i + d*nCurr + const pPrevIn = { x: p.x + nPrev.x * distance, z: p.z + nPrev.z * distance }; + const pCurrIn = { x: p.x + nCurr.x * distance, z: p.z + nCurr.z * distance }; + + if (joinType === "bevel") { + const tri = ensurePositivePath([p, pPrevIn, pCurrIn]); + if (tri.length >= 3) masks.push(tri); + } else if (joinType === "round") { + const a0 = Math.atan2(nPrev.z, nPrev.x); + let a1 = Math.atan2(nCurr.z, nCurr.x); + if (a1 > a0) a1 -= Math.PI * 2; + const sweep = Math.abs(a1 - a0); + const stepAngle = Math.acos(Math.max(-1, Math.min(1, 1 - Math.min(arcTolerance, distance * 0.5) / Math.max(distance, 1e-6)))); + const steps = Math.max(2, Math.min(32, Math.ceil(sweep / Math.max(stepAngle, 0.12)))); + const fan: Point2D[] = [p, pPrevIn]; + for (let s = 1; s < steps; s++) { + const ang = a0 + ((a1 - a0) * s) / steps; + fan.push({ x: p.x + Math.cos(ang) * distance, z: p.z + Math.sin(ang) * distance }); + } + fan.push(pCurrIn); + const fanPath = ensurePositivePath(fan); + if (fanPath.length >= 3) masks.push(fanPath); + } else { + const denom = 1 + nPrev.x * nCurr.x + nPrev.z * nCurr.z; + const miterScale = denom > 1e-6 ? Math.sqrt(2 / denom) : Infinity; + if (denom > 1e-6 && miterScale <= miterLimit) { + const invDenom = distance / denom; + const miterPt = { + x: p.x + (nPrev.x + nCurr.x) * invDenom, + z: p.z + (nPrev.z + nCurr.z) * invDenom, + }; + const quad = ensurePositivePath([p, pPrevIn, miterPt, pCurrIn]); + if (quad.length >= 3) masks.push(quad); + } else { + const tri = ensurePositivePath([p, pPrevIn, pCurrIn]); + if (tri.length >= 3) masks.push(tri); + } + } + } else if (turnCross > 1e-6 && tangentDot < -1e-4) { + // Acute convex corner (< 90 deg): vertex disk sector guarantees full distance-d erosion + // behind p_i where perpendicular rectangles don't reach backward. + const diskPts: Point2D[] = []; + const segments = 12; + for (let k = 0; k < segments; k++) { + const ang = (Math.PI * 2 * k) / segments; + diskPts.push({ x: p.x + Math.cos(ang) * distance, z: p.z + Math.sin(ang) * distance }); + } + const diskPath = ensurePositivePath(diskPts); + if (diskPath.length >= 3) masks.push(diskPath); + } + } + + return masks; +} + +/** + * Offsets one or more closed 2D polygons using Clipper2 (`clipper2-js` `Clipper.BooleanOp`). + * Automatically resolves self-intersections, sharp miter spikes, concave islands, + * and collapses degenerate offset regions cleanly instead of inverting geometry. + * + * Note: Uses Clipper2 Vatti booleans over exact offset primitives because `clipper2-js@1.2.4`'s + * bundled `ClipperOffset` has an upstream C#-port `ref int k` parameter bug. + * + * Positive distance expands outer contours outward; negative distance shrinks inward. + */ +export function offsetPolygonPaths( + polygons: Point2D[][], + distance: number, + options?: OffsetOptions, +): Point2D[][] { + const validInputs = polygons + .map((poly) => dedupeFloatPolygon(poly)) + .filter((poly) => poly.length >= 3); + if (validInputs.length === 0) return []; + if (!Number.isFinite(distance) || Math.abs(distance) < 0.001) { + return validInputs.map((poly) => poly.map((p) => ({ x: p.x, z: p.z }))); + } + + const miterLimit = Math.max(1.1, options?.miterLimit ?? 3.0); + const arcTolerance = Math.max(0.01, options?.arcTolerance ?? 0.25); + const joinType: OffsetJoinType = options?.joinType ?? "miter"; + + const singleInputWasNegativeWinding = + validInputs.length === 1 && polygonSignedArea(validInputs[0]) < 0; + + let solution: Paths64; + if (distance > 0) { + const unionMasks: Paths64 = []; + for (const poly of validInputs) { + const ccw = polygonSignedArea(poly) < 0 ? [...poly].reverse() : poly; + unionMasks.push(...buildPositiveOutwardMasks(ccw, distance, joinType, miterLimit, arcTolerance)); + } + if (unionMasks.length === 0) return []; + solution = Clipper.BooleanOp(ClipType.Union, unionMasks, undefined, FillRule.NonZero); + } else { + const d = -distance; + const subjects: Paths64 = []; + const erosionMasks: Paths64 = []; + for (const poly of validInputs) { + const ccw = polygonSignedArea(poly) < 0 ? [...poly].reverse() : poly; + const subj = ensurePositivePath(ccw); + if (subj.length < 3) continue; + subjects.push(subj); + erosionMasks.push(...buildInwardErosionMasks(ccw, d, joinType, miterLimit, arcTolerance)); + } + if (subjects.length === 0) return []; + solution = Clipper.BooleanOp(ClipType.Difference, subjects, erosionMasks, FillRule.NonZero); + } + + const result: Point2D[][] = []; + for (let i = 0; i < solution.length; i++) { + const clean = stripConsecutiveAndCollinear(solution[i]); + if (clean.length < 3 || Math.abs(Clipper.area(clean)) < 1) continue; + let pts = path64ToPoints(clean); + if (pts.length < 3) continue; + if (singleInputWasNegativeWinding && polygonSignedArea(pts) > 0) { + pts = pts.reverse(); + } else if (!singleInputWasNegativeWinding && polygonSignedArea(pts) < 0) { + pts = pts.reverse(); + } + result.push(pts); + } return result; } -import type { SketchProfile, SketchPoint, SketchSegment } from "@/types/sketchforge"; +/** + * Offsets a single closed 2D polygon (e.g., room perimeter to generate wall thickness). + * @param points Array of 2D vertices (ordered clockwise or counter-clockwise) + * @param distance Offset distance in mm (positive = outward, negative = inward/duvar kalınlığı) + * @param maxMiterRatio Limits miter spikes on sharp corners (default 3.0) + * @param options Optional join type / arc tolerance controls + */ +export function offsetPolygon( + points: Point2D[], + distance: number, + maxMiterRatio = 3.0, + options?: OffsetOptions, +): Point2D[] { + const n = points.length; + if (n < 3 || Math.abs(distance) < 0.001) return [...points]; + + const offsetPaths = offsetPolygonPaths([points], distance, { + joinType: options?.joinType ?? "miter", + miterLimit: options?.miterLimit ?? maxMiterRatio, + arcTolerance: options?.arcTolerance, + }); + + if (offsetPaths.length === 0) return []; + if (offsetPaths.length === 1) return offsetPaths[0]; + + let best = offsetPaths[0]; + let bestArea = Math.abs(polygonSignedArea(best)); + for (let i = 1; i < offsetPaths.length; i++) { + const area = Math.abs(polygonSignedArea(offsetPaths[i])); + if (area > bestArea) { + best = offsetPaths[i]; + bestArea = area; + } + } + return best; +} + +function extractClosedLoopsFromProfile(profile: SketchProfile): Point2D[][] { + if (profile.points.length < 3) return []; + const pointById = new Map(profile.points.map((pt) => [pt.id, pt])); + const adjacency = new Map>(); + for (const pt of profile.points) { + adjacency.set(pt.id, []); + } + const validSegments = profile.segments.filter( + (s) => pointById.has(s.startId) && pointById.has(s.endId), + ); + for (const seg of validSegments) { + adjacency.get(seg.startId)?.push({ nextId: seg.endId, segId: seg.id }); + adjacency.get(seg.endId)?.push({ nextId: seg.startId, segId: seg.id }); + } + + const usedSegments = new Set(); + const loops: Point2D[][] = []; + + for (const seg of validSegments) { + if (usedSegments.has(seg.id)) continue; + const startId = seg.startId; + const first = pointById.get(startId); + if (!first) continue; + + const loop: Point2D[] = []; + let currId = startId; + let closed = false; + for (let guard = 0; guard <= validSegments.length + 1; guard++) { + const currPt = pointById.get(currId); + if (!currPt) break; + loop.push({ x: currPt.x, z: currPt.z }); + const edge = adjacency.get(currId)?.find((item) => !usedSegments.has(item.segId)); + if (!edge) break; + usedSegments.add(edge.segId); + currId = edge.nextId; + if (currId === startId) { + closed = loop.length >= 3; + break; + } + } + if (closed) { + loops.push(loop); + } + } + + if (loops.length > 0) return loops; + return [profile.points.map((p) => ({ x: p.x, z: p.z }))]; +} /** * Creates an offset wall/contour for a closed sketch profile. @@ -132,31 +582,48 @@ import type { SketchProfile, SketchPoint, SketchSegment } from "@/types/sketchfo export function offsetSketchProfile( profile: SketchProfile, distance = -15, // default 15mm wall thickness + options?: OffsetOptions, ): SketchProfile { if (profile.points.length < 3) return profile; - const points2d: Point2D[] = profile.points.map((p) => ({ x: p.x, z: p.z })); - const offsetPoints = offsetPolygon(points2d, distance); + const loops = extractClosedLoopsFromProfile(profile); + const generatedLoops: Point2D[][] = []; + for (const loop of loops) { + const out = offsetPolygonPaths([loop], distance, { + joinType: options?.joinType ?? "miter", + miterLimit: options?.miterLimit ?? 3.0, + arcTolerance: options?.arcTolerance, + }); + generatedLoops.push(...out); + } + + if (generatedLoops.length === 0) { + return profile; + } const prefix = `offset-${Date.now().toString(36)}`; - const newSketchPoints: SketchPoint[] = offsetPoints.map((p, idx) => ({ - id: `${prefix}-pt-${idx}`, - x: p.x, - z: p.z, - mode: "corner", - })); - + const newSketchPoints: SketchPoint[] = []; const newSegments: SketchSegment[] = []; - for (let i = 0; i < newSketchPoints.length; i++) { - const startId = newSketchPoints[i].id; - const endId = newSketchPoints[(i + 1) % newSketchPoints.length].id; - newSegments.push({ - id: `${prefix}-seg-${i}`, - startId, - endId, - kind: "line", - }); - } + + generatedLoops.forEach((loop, loopIdx) => { + const loopPts: SketchPoint[] = loop.map((p, idx) => ({ + id: `${prefix}-l${loopIdx}-pt-${idx}`, + x: Number(p.x.toFixed(2)), + z: Number(p.z.toFixed(2)), + mode: "corner", + })); + newSketchPoints.push(...loopPts); + for (let i = 0; i < loopPts.length; i++) { + const startId = loopPts[i].id; + const endId = loopPts[(i + 1) % loopPts.length].id; + newSegments.push({ + id: `${prefix}-l${loopIdx}-seg-${i}`, + startId, + endId, + kind: "line", + }); + } + }); return { ...profile, diff --git a/apps/web/src/lib/planegcsSolver.ts b/apps/web/src/lib/planegcsSolver.ts new file mode 100644 index 0000000..9c1c9f6 --- /dev/null +++ b/apps/web/src/lib/planegcsSolver.ts @@ -0,0 +1,454 @@ +/** + * FreeCAD PlaneGCS WebAssembly 2D Geometric Constraint Solver integration for SnapCAD Studio. + * Uses @salusoft89/planegcs (LGPL-2.0-or-later) via staged runtime /planegcs/planegcs.wasm. + */ +import { GcsWrapper } from "@salusoft89/planegcs/dist/sketch/gcs_wrapper.js"; +import { Algorithm, SolveStatus } from "@salusoft89/planegcs/dist/planegcs_dist/enums.js"; +import type { SketchPrimitive } from "@salusoft89/planegcs/dist/sketch/sketch_primitive.js"; +import type { SketchProfile, SketchPoint } from "@/types/sketchforge"; + +export interface GcsInputPoint { + id: string; + x: number; + y: number; + fixed?: boolean; +} + +export interface GcsInputLine { + id: string; + p1Id: string; + p2Id: string; +} + +export interface GcsInputCircle { + id: string; + centerId: string; + radius: number; +} + +export type GcsInputConstraint = + | { id: string; type: "horizontal"; lineId: string } + | { id: string; type: "horizontal_points"; p1Id: string; p2Id: string } + | { id: string; type: "vertical"; lineId: string } + | { id: string; type: "vertical_points"; p1Id: string; p2Id: string } + | { id: string; type: "coincident"; p1Id: string; p2Id: string } + | { id: string; type: "distance"; p1Id: string; p2Id: string; distance: number } + | { id: string; type: "parallel"; l1Id: string; l2Id: string } + | { id: string; type: "perpendicular"; l1Id: string; l2Id: string } + | { id: string; type: "equal_length"; l1Id: string; l2Id: string } + | { id: string; type: "angle"; l1Id: string; l2Id: string; angleRad: number } + | { id: string; type: "circle_radius"; circleId: string; radius: number } + | { id: string; type: "tangent_lc"; lineId: string; circleId: string } + | { id: string; type: "concentric"; c1Id: string; c2Id: string } + | { id: string; type: "fix_x"; pointId: string; x: number } + | { id: string; type: "fix_y"; pointId: string; y: number }; + +export interface GcsSolveRequest { + points: GcsInputPoint[]; + lines?: GcsInputLine[]; + circles?: GcsInputCircle[]; + constraints: GcsInputConstraint[]; + maxIterations?: number; + convergenceThreshold?: number; +} + +export interface GcsSolveResult { + solved: boolean; + status: "success" | "converged" | "failed" | "invalid"; + dof: number; + conflictingConstraintIds: string[]; + redundantConstraintIds: string[]; + points: GcsInputPoint[]; + circles: GcsInputCircle[]; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let planegcsModPromise: Promise | null = null; + +/** + * Loads the Emscripten PlaneGCS runtime module in either browser or Node/Vitest. + * Static WASM assets are staged at `/planegcs/planegcs.{js,wasm}` via `scripts/copy-planegcs-wasm.mjs`. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function getPlanegcsModule(): Promise { + if (planegcsModPromise) return planegcsModPromise; + + planegcsModPromise = (async () => { + if (typeof window === "undefined") { + const nodePathSpec = `node:${"path"}`; + const nodeUrlSpec = `node:${"url"}`; + const pathMod = await import(/* webpackIgnore: true */ nodePathSpec); + const urlMod = await import(/* webpackIgnore: true */ nodeUrlSpec); + const jsPath = pathMod.default.resolve( + process.cwd(), + "node_modules/@salusoft89/planegcs/dist/planegcs_dist/planegcs.js", + ); + const fileUrl = urlMod.pathToFileURL(jsPath).href; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mod: any = await import(/* webpackIgnore: true */ fileUrl); + const factory = mod.default ?? mod; + return await factory(); + } else { + const runtimeUrl = "/planegcs/planegcs.js"; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mod: any = await import(/* webpackIgnore: true */ runtimeUrl); + const factory = mod.default ?? mod; + return await factory({ + locateFile: (fileName: string) => `/planegcs/${fileName}`, + }); + } + })().catch((err) => { + planegcsModPromise = null; + throw err; + }); + + return planegcsModPromise; +} + +function mapSolveStatus(code: number): GcsSolveResult["status"] { + switch (code) { + case SolveStatus.Success: + return "success"; + case SolveStatus.Converged: + return "converged"; + case SolveStatus.SuccessfulSolutionInvalid: + return "invalid"; + default: + return "failed"; + } +} + +function pushInputConstraints( + wrapper: GcsWrapper, + constraints: GcsInputConstraint[], + circleById: Map, +): void { + for (const c of constraints) { + let prim: SketchPrimitive | null = null; + switch (c.type) { + case "horizontal": + prim = { id: c.id, type: "horizontal_l", l_id: c.lineId }; + break; + case "horizontal_points": + prim = { id: c.id, type: "horizontal_pp", p1_id: c.p1Id, p2_id: c.p2Id }; + break; + case "vertical": + prim = { id: c.id, type: "vertical_l", l_id: c.lineId }; + break; + case "vertical_points": + prim = { id: c.id, type: "vertical_pp", p1_id: c.p1Id, p2_id: c.p2Id }; + break; + case "coincident": + prim = { id: c.id, type: "p2p_coincident", p1_id: c.p1Id, p2_id: c.p2Id }; + break; + case "distance": + prim = { id: c.id, type: "p2p_distance", p1_id: c.p1Id, p2_id: c.p2Id, distance: c.distance }; + break; + case "parallel": + prim = { id: c.id, type: "parallel", l1_id: c.l1Id, l2_id: c.l2Id }; + break; + case "perpendicular": + prim = { id: c.id, type: "perpendicular_ll", l1_id: c.l1Id, l2_id: c.l2Id }; + break; + case "equal_length": + prim = { id: c.id, type: "equal_length", l1_id: c.l1Id, l2_id: c.l2Id }; + break; + case "angle": + prim = { id: c.id, type: "l2l_angle_ll", l1_id: c.l1Id, l2_id: c.l2Id, angle: c.angleRad }; + break; + case "circle_radius": + prim = { id: c.id, type: "circle_radius", c_id: c.circleId, radius: c.radius }; + break; + case "tangent_lc": + prim = { id: c.id, type: "tangent_lc", l_id: c.lineId, c_id: c.circleId }; + break; + case "concentric": { + const c1 = circleById.get(c.c1Id); + const c2 = circleById.get(c.c2Id); + if (c1 && c2) { + prim = { id: c.id, type: "p2p_coincident", p1_id: c1.centerId, p2_id: c2.centerId }; + } + break; + } + case "fix_x": + prim = { id: c.id, type: "coordinate_x", p_id: c.pointId, x: c.x }; + break; + case "fix_y": + prim = { id: c.id, type: "coordinate_y", p_id: c.pointId, y: c.y }; + break; + } + if (prim) { + wrapper.push_primitive(prim); + } + } +} + +/** + * Solves a 2D parametric sketch system with FreeCAD PlaneGCS (DogLeg -> LM fallback). + */ +export async function solveSketchConstraints(request: GcsSolveRequest): Promise { + const mod = await getPlanegcsModule(); + const wrapper = new GcsWrapper(new mod.GcsSystem(), mod); + + try { + if (request.maxIterations && request.maxIterations > 0) { + wrapper.set_max_iterations(request.maxIterations); + } + if (request.convergenceThreshold && request.convergenceThreshold > 0) { + wrapper.set_convergence_threshold(request.convergenceThreshold); + } + + for (const pt of request.points) { + wrapper.push_primitive({ + id: pt.id, + type: "point", + x: pt.x, + y: pt.y, + fixed: Boolean(pt.fixed), + }); + } + + for (const ln of request.lines ?? []) { + wrapper.push_primitive({ + id: ln.id, + type: "line", + p1_id: ln.p1Id, + p2_id: ln.p2Id, + }); + } + + const circleById = new Map(); + for (const c of request.circles ?? []) { + circleById.set(c.id, c); + wrapper.push_primitive({ + id: c.id, + type: "circle", + c_id: c.centerId, + radius: Math.max(0.01, c.radius), + }); + } + + pushInputConstraints(wrapper, request.constraints, circleById); + + let statusCode = wrapper.solve(Algorithm.DogLeg); + if (statusCode !== SolveStatus.Success && statusCode !== SolveStatus.Converged) { + statusCode = wrapper.solve(Algorithm.LevenbergMarquardt); + } + const solved = statusCode === SolveStatus.Success || statusCode === SolveStatus.Converged; + if (solved) { + wrapper.apply_solution(); + } + + const dof = wrapper.gcs.dof(); + const conflictingConstraintIds = wrapper.has_gcs_conflicting_constraints() + ? wrapper.get_gcs_conflicting_constraints() + : []; + const redundantConstraintIds = wrapper.has_gcs_redundant_constraints() + ? wrapper.get_gcs_redundant_constraints() + : []; + + const solvedPoints: GcsInputPoint[] = request.points.map((orig) => { + const updated = wrapper.sketch_index.get_sketch_point(orig.id); + return { + id: orig.id, + x: Number(updated.x.toFixed(6)), + y: Number(updated.y.toFixed(6)), + fixed: orig.fixed, + }; + }); + + const solvedCircles: GcsInputCircle[] = (request.circles ?? []).map((orig) => { + const updated = wrapper.sketch_index.get_sketch_circle(orig.id); + return { + id: orig.id, + centerId: orig.centerId, + radius: Number(updated.radius.toFixed(6)), + }; + }); + + return { + solved, + status: mapSolveStatus(statusCode), + dof, + conflictingConstraintIds, + redundantConstraintIds, + points: solvedPoints, + circles: solvedCircles, + }; + } finally { + wrapper.destroy_gcs_module(); + } +} + +export interface SnapCadSolveProfileResult { + profile: SketchProfile; + solved: boolean; + status: GcsSolveResult["status"]; + appliedConstraintsCount: number; + dof: number; + changedPointsCount: number; +} + +/** + * Automatically detects nearly horizontal, vertical, and perpendicular segments on a + * SnapCAD `SketchProfile` and enforces exact orthogonal CAD geometry using PlaneGCS. + * Bezier handles shift with their owner points so curves remain smooth. + */ +export async function autoConstrainAndSolveSnapCadProfile( + profile: SketchProfile, + options?: { + snapAngleDeg?: number; + anchorPointId?: string; + }, +): Promise { + if (profile.points.length < 2 || profile.segments.length === 0) { + return { + profile, + solved: false, + status: "invalid", + appliedConstraintsCount: 0, + dof: 0, + changedPointsCount: 0, + }; + } + + const snapRad = ((options?.snapAngleDeg ?? 9) * Math.PI) / 180; + const pointById = new Map(profile.points.map((p) => [p.id, p])); + const anchorId = options?.anchorPointId && pointById.has(options.anchorPointId) + ? options.anchorPointId + : profile.points[0].id; + + const gcsPoints: GcsInputPoint[] = profile.points.map((pt) => ({ + id: pt.id, + x: pt.x, + y: pt.z, + fixed: pt.id === anchorId, + })); + + const lineSegments = profile.segments.filter( + (s) => (s.kind ?? "line") === "line" && pointById.has(s.startId) && pointById.has(s.endId) && s.startId !== s.endId, + ); + if (lineSegments.length === 0) { + return { + profile, + solved: false, + status: "invalid", + appliedConstraintsCount: 0, + dof: 0, + changedPointsCount: 0, + }; + } + + const gcsLines: GcsInputLine[] = lineSegments.map((s) => ({ + id: s.id, + p1Id: s.startId, + p2Id: s.endId, + })); + + const constraints: GcsInputConstraint[] = []; + const lineAngles = new Map(); + + for (const seg of lineSegments) { + const a = pointById.get(seg.startId)!; + const b = pointById.get(seg.endId)!; + const dx = b.x - a.x; + const dz = b.z - a.z; + const len = Math.hypot(dx, dz); + if (len < 1e-4) continue; + const angle = Math.atan2(dz, dx); + lineAngles.set(seg.id, angle); + + const horizontalDev = Math.min(Math.abs(angle), Math.abs(Math.abs(angle) - Math.PI)); + const verticalDev = Math.abs(Math.abs(angle) - Math.PI / 2); + + if (horizontalDev <= snapRad) { + constraints.push({ id: `c-h-${seg.id}`, type: "horizontal", lineId: seg.id }); + } else if (verticalDev <= snapRad) { + constraints.push({ id: `c-v-${seg.id}`, type: "vertical", lineId: seg.id }); + } + } + + // Add perpendicular constraints at corners shared by two unconstrained segments that are nearly 90 deg + const constrainedLines = new Set( + constraints.filter((c) => c.type === "horizontal" || c.type === "vertical").map((c) => ("lineId" in c ? c.lineId : "")), + ); + for (let i = 0; i < lineSegments.length; i++) { + const s1 = lineSegments[i]; + const s2 = lineSegments[(i + 1) % lineSegments.length]; + if (!s2 || s1.id === s2.id) continue; + const sharesVertex = + s1.endId === s2.startId || s1.startId === s2.endId || s1.endId === s2.endId || s1.startId === s2.startId; + if (!sharesVertex) continue; + // Skip if both are already individually constrained as H/V (avoids redundant constraints) + if (constrainedLines.has(s1.id) && constrainedLines.has(s2.id)) continue; + + const a1 = lineAngles.get(s1.id); + const a2 = lineAngles.get(s2.id); + if (a1 === undefined || a2 === undefined) continue; + const dotAbs = Math.abs(Math.cos(a1 - a2)); + if (dotAbs <= Math.sin(snapRad)) { + constraints.push({ id: `c-perp-${s1.id}-${s2.id}`, type: "perpendicular", l1Id: s1.id, l2Id: s2.id }); + } + } + + if (constraints.length === 0) { + return { + profile, + solved: true, + status: "success", + appliedConstraintsCount: 0, + dof: Math.max(0, (gcsPoints.length - 1) * 2), + changedPointsCount: 0, + }; + } + + const solveRes = await solveSketchConstraints({ + points: gcsPoints, + lines: gcsLines, + constraints, + }); + + if (!solveRes.solved) { + return { + profile, + solved: false, + status: solveRes.status, + appliedConstraintsCount: constraints.length, + dof: solveRes.dof, + changedPointsCount: 0, + }; + } + + const solvedById = new Map(solveRes.points.map((pt) => [pt.id, pt])); + let changedPointsCount = 0; + const nextPoints: SketchPoint[] = profile.points.map((orig) => { + const solved = solvedById.get(orig.id); + if (!solved) return orig; + const nextX = Number(solved.x.toFixed(2)); + const nextZ = Number(solved.y.toFixed(2)); + const dx = nextX - orig.x; + const dz = nextZ - orig.z; + if (Math.abs(dx) > 0.005 || Math.abs(dz) > 0.005) { + changedPointsCount += 1; + } + return { + ...orig, + x: nextX, + z: nextZ, + handleIn: orig.handleIn ? { x: Number((orig.handleIn.x + dx).toFixed(2)), z: Number((orig.handleIn.z + dz).toFixed(2)) } : undefined, + handleOut: orig.handleOut ? { x: Number((orig.handleOut.x + dx).toFixed(2)), z: Number((orig.handleOut.z + dz).toFixed(2)) } : undefined, + }; + }); + + return { + profile: { + ...profile, + points: nextPoints, + }, + solved: true, + status: solveRes.status, + appliedConstraintsCount: constraints.length, + dof: solveRes.dof, + changedPointsCount, + }; +} diff --git a/apps/web/src/lib/projectAssets.ts b/apps/web/src/lib/projectAssets.ts index f9c0716..025b9f6 100644 --- a/apps/web/src/lib/projectAssets.ts +++ b/apps/web/src/lib/projectAssets.ts @@ -111,7 +111,7 @@ export async function sha256Hex(bytes: Uint8Array) { export function sourceFormatForFileName(fileName: string): ProjectAssetSourceFormat | null { const extension = fileName.split(".").pop()?.toLowerCase(); - if (extension === "stl" || extension === "obj" || extension === "svg" || extension === "dxf" || extension === "glb" || extension === "dwg") return extension; + if (extension === "stl" || extension === "obj" || extension === "svg" || extension === "dxf" || extension === "glb" || extension === "dwg" || extension === "ifc") return extension; if (extension === "gltf") return "glb"; if (extension === "step" || extension === "stp") return "step"; return null; @@ -120,6 +120,7 @@ export function sourceFormatForFileName(fileName: string): ProjectAssetSourceFor export function defaultMediaTypeForSource(format: ProjectAssetSourceFormat) { if (format === "svg") return "image/svg+xml"; if (format === "step") return "application/step"; + if (format === "ifc") return "application/ifc"; if (format === "obj") return "model/obj"; if (format === "dxf") return "application/dxf"; if (format === "glb") return "model/gltf-binary"; diff --git a/apps/web/src/lib/projection/EdgeGenerator.ts b/apps/web/src/lib/projection/EdgeGenerator.ts new file mode 100644 index 0000000..3505198 --- /dev/null +++ b/apps/web/src/lib/projection/EdgeGenerator.ts @@ -0,0 +1,217 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { BufferGeometry, Matrix4, Object3D, Vector3 } from "three"; +import { MeshBVH } from "three-mesh-bvh"; +import { generateEdges } from "./utils/generateEdges"; +import { generateIntersectionEdges } from "./utils/generateIntersectionEdges"; +import { getAllMeshes } from "./utils/getAllMeshes"; +import { nextFrame } from "./utils/nextFrame"; +import type { ProjectionEdge } from "./utils/ProjectionEdge"; + +const _BtoA = /* @__PURE__ */ new Matrix4(); + +export type EdgeInput = Object3D | BufferGeometry | MeshBVH | Array; + +export class EdgeGenerator { + projectionDirection: Vector3; + thresholdAngle: number; + iterationTime: number; + yOffset: number; + + constructor() { + this.projectionDirection = new Vector3(0, 1, 0); + this.thresholdAngle = 50; + this.iterationTime = 30; + this.yOffset = 1e-6; + } + + getEdges(geometry: EdgeInput, resultEdges: ProjectionEdge[] = []): ProjectionEdge[] { + const currIterationTime = this.iterationTime; + this.iterationTime = Infinity; + + const result = this.getEdgesGenerator(geometry, resultEdges).next().value; + this.iterationTime = currIterationTime; + + return result ?? resultEdges; + } + + async getEdgesAsync(geometry: EdgeInput, resultEdges: ProjectionEdge[] = []): Promise { + const task = this.getEdgesGenerator(geometry, resultEdges); + let res: IteratorResult | undefined; + while (!res || !res.done) { + res = task.next(); + if (!res.done) { + await nextFrame(); + } + } + + return res.value ?? resultEdges; + } + + *getEdgesGenerator( + geometry: EdgeInput, + resultEdges: ProjectionEdge[] = [], + ): Generator { + if (Array.isArray(geometry)) { + for (let i = 0, l = geometry.length; i < l; i++) { + yield* this.getEdgesGenerator(geometry[i], resultEdges); + } + + return resultEdges; + } + + const { projectionDirection, thresholdAngle, iterationTime, yOffset } = this; + if ((geometry as Object3D).isObject3D) { + const obj = geometry as Object3D; + obj.updateWorldMatrix(true, true); + const meshes = getAllMeshes(obj); + let time = performance.now(); + + for (let i = 0; i < meshes.length; i++) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + const mesh = meshes[i]; + const results = yield* generateEdges(mesh.geometry, [], { + matrix: mesh.matrixWorld, + projectionDirection, + thresholdAngle, + iterationTime, + }); + + transformEdges(results, mesh.matrixWorld, yOffset); + + for (let k = 0; k < results.length; k++) { + results[k].mesh = mesh; + resultEdges.push(results[k]); + } + } + + return resultEdges; + } + + const geom = (geometry as MeshBVH).geometry ?? (geometry as BufferGeometry); + return yield* generateEdges(geom, resultEdges, { + projectionDirection, + thresholdAngle, + iterationTime, + }); + } + + getIntersectionEdges(geometry: EdgeInput, resultEdges: ProjectionEdge[] = []): ProjectionEdge[] { + const currIterationTime = this.iterationTime; + this.iterationTime = Infinity; + + const result = this.getIntersectionEdgesGenerator(geometry, resultEdges).next().value; + this.iterationTime = currIterationTime; + + return result ?? resultEdges; + } + + async getIntersectionEdgesAsync( + geometry: EdgeInput, + resultEdges: ProjectionEdge[] = [], + ): Promise { + const task = this.getIntersectionEdgesGenerator(geometry, resultEdges); + let res: IteratorResult | undefined; + while (!res || !res.done) { + res = task.next(); + if (!res.done) { + await nextFrame(); + } + } + + return res.value ?? resultEdges; + } + + *getIntersectionEdgesGenerator( + geometry: EdgeInput, + resultEdges: ProjectionEdge[] = [], + ): Generator { + if (Array.isArray(geometry)) { + for (let i = 0, l = geometry.length; i < l; i++) { + yield* this.getIntersectionEdgesGenerator(geometry[i], resultEdges); + } + + return resultEdges; + } + + const { iterationTime, yOffset } = this; + if ((geometry as Object3D).isObject3D) { + const obj = geometry as Object3D; + obj.updateWorldMatrix(true, true); + const meshes = getAllMeshes(obj); + const bvhs = new Map(); + let time = performance.now(); + + for (let i = 0; i < meshes.length; i++) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + const mesh = meshes[i]; + const meshGeom = mesh.geometry; + if (!bvhs.has(meshGeom)) { + const existing = meshGeom.boundsTree instanceof MeshBVH ? meshGeom.boundsTree : null; + const bvh = existing ?? new MeshBVH(meshGeom, { targetLeafSize: 1 }); + bvhs.set(meshGeom, bvh); + } + } + + time = performance.now(); + for (let i = 0; i < meshes.length; i++) { + for (let j = i; j < meshes.length; j++) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + const meshA = meshes[i]; + const meshB = meshes[j]; + const bvhA = bvhs.get(meshA.geometry); + const bvhB = bvhs.get(meshB.geometry); + if (!bvhA || !bvhB) { + continue; + } + + _BtoA.copy(meshA.matrixWorld).invert().multiply(meshB.matrixWorld); + + const results = generateIntersectionEdges(bvhA, bvhB, _BtoA, [], { iterationTime }); + transformEdges(results, meshA.matrixWorld, yOffset); + + for (let k = 0; k < results.length; k++) { + results[k].mesh = meshA; + resultEdges.push(results[k]); + } + } + } + + return resultEdges; + } + + let bvh: MeshBVH; + if ((geometry as BufferGeometry).isBufferGeometry) { + const bufGeom = geometry as BufferGeometry; + bvh = + bufGeom.boundsTree instanceof MeshBVH + ? bufGeom.boundsTree + : new MeshBVH(bufGeom, { targetLeafSize: 1 }); + } else { + bvh = geometry as MeshBVH; + } + + _BtoA.identity(); + return generateIntersectionEdges(bvh, bvh, _BtoA, resultEdges, { iterationTime }); + } +} + +function transformEdges(list: ProjectionEdge[], matrix: Matrix4, offset = 0): void { + for (let i = 0; i < list.length; i++) { + const line = list[i]; + line.applyMatrix4(matrix); + line.start.y += offset; + line.end.y += offset; + } +} diff --git a/apps/web/src/lib/projection/PlanarIntersectionGenerator.ts b/apps/web/src/lib/projection/PlanarIntersectionGenerator.ts new file mode 100644 index 0000000..aac4859 --- /dev/null +++ b/apps/web/src/lib/projection/PlanarIntersectionGenerator.ts @@ -0,0 +1,72 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Box3, BufferAttribute, BufferGeometry, Line3, Plane, Vector3 } from "three"; +import { type ExtendedTriangle, MeshBVH } from "three-mesh-bvh"; + +const _line = new Line3(); +const _target = new Line3(); +const _vec = new Vector3(); +const EPS = 1e-16; + +export class PlanarIntersectionGenerator { + plane: Plane; + + constructor() { + this.plane = new Plane(new Vector3(0, 1, 0), 0); + } + + generate(input: MeshBVH | BufferGeometry): BufferGeometry { + const { plane } = this; + const bvh = + (input as BufferGeometry).isBufferGeometry + ? (input as BufferGeometry).boundsTree instanceof MeshBVH + ? ((input as BufferGeometry).boundsTree as MeshBVH) + : new MeshBVH(input as BufferGeometry, { targetLeafSize: 1 }) + : (input as MeshBVH); + + const edgesArray: number[] = []; + bvh.shapecast({ + intersectsBounds: (box: Box3) => { + return plane.intersectsBox(box); + }, + + intersectsTriangle: (tri: ExtendedTriangle) => { + const points = [tri.a, tri.b, tri.c] as const; + let foundPoints = 0; + for (let i = 0; i < 3; i++) { + const ni = (i + 1) % 3; + _line.start.copy(points[i]); + _line.end.copy(points[ni]); + + if (plane.intersectLine(_line, _vec)) { + if (foundPoints === 1) { + if (_vec.distanceTo(_target.start) > EPS) { + _target.end.copy(_vec); + foundPoints++; + break; + } + } else { + _target.start.copy(_vec); + foundPoints++; + } + } + } + + if (foundPoints === 2) { + edgesArray.push( + _target.start.x, + _target.start.y, + _target.start.z, + _target.end.x, + _target.end.y, + _target.end.z, + ); + } + }, + }); + + const edgeGeom = new BufferGeometry(); + const edgeBuffer = new BufferAttribute(new Float32Array(edgesArray), 3, false); + edgeGeom.setAttribute("position", edgeBuffer); + return edgeGeom; + } +} diff --git a/apps/web/src/lib/projection/ProjectionGenerator.ts b/apps/web/src/lib/projection/ProjectionGenerator.ts new file mode 100644 index 0000000..824a896 --- /dev/null +++ b/apps/web/src/lib/projection/ProjectionGenerator.ts @@ -0,0 +1,315 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { BufferAttribute, BufferGeometry, Mesh, Object3D, Vector3 } from "three"; +import { MeshBVH, SAH } from "three-mesh-bvh"; +import { EdgeGenerator } from "./EdgeGenerator"; +import { bvhcastEdges } from "./utils/bvhcastEdges"; +import { getAllMeshes } from "./utils/getAllMeshes"; +import type { OverlapRange } from "./utils/getProjectedOverlaps"; +import { LineObjectsBVH } from "./utils/LineObjectsBVH"; +import { nextFrame } from "./utils/nextFrame"; +import { overlapsToLines } from "./utils/overlapUtils"; +import type { ProjectionEdge } from "./utils/ProjectionEdge"; +import { isYProjectedLineDegenerate } from "./utils/triangleLineUtils"; + +const UP_VECTOR = /* @__PURE__ */ new Vector3(0, 1, 0); + +export interface EdgeRange { + start: number; + count: number; +} + +function toLineGeometry(edges: Float32Array[], ranges: EdgeRange[] | null = null): BufferGeometry { + const activeRanges = ranges ?? [{ start: 0, count: edges.length }]; + + let totalCount = 0; + for (let i = 0; i < activeRanges.length; i++) { + totalCount += activeRanges[i].count; + } + + const edgeArray = new Float32Array(totalCount * 6); + let c = 0; + for (let r = 0; r < activeRanges.length; r++) { + const { start, count } = activeRanges[r]; + for (let i = start, l = start + count; i < l; i++) { + const line = edges[i]; + edgeArray[c++] = line[0]; + edgeArray[c++] = 0; + edgeArray[c++] = line[2]; + edgeArray[c++] = line[3]; + edgeArray[c++] = 0; + edgeArray[c++] = line[5]; + } + } + + const edgeGeom = new BufferGeometry(); + const edgeBuffer = new BufferAttribute(edgeArray, 3, false); + edgeGeom.setAttribute("position", edgeBuffer); + return edgeGeom; +} + +export class EdgeSet { + meshToSegments: Map; + private _rangeCache: Map | null; + + constructor() { + this.meshToSegments = new Map(); + this._rangeCache = null; + } + + getLineGeometry(meshes: Mesh[] | null = null): BufferGeometry { + const activeMeshes = meshes !== null ? meshes : Array.from(this.meshToSegments.keys()); + const segments: Float32Array[] = []; + for (let i = 0; i < activeMeshes.length; i++) { + const segs = this.meshToSegments.get(activeMeshes[i]); + if (segs) { + for (let j = 0; j < segs.length; j++) { + segments.push(segs[j]); + } + } + } + + return toLineGeometry(segments); + } + + getAllSegments(): Float32Array[] { + const segments: Float32Array[] = []; + for (const segs of this.meshToSegments.values()) { + for (let i = 0; i < segs.length; i++) { + segments.push(segs[i]); + } + } + return segments; + } + + getRangeForMesh(mesh: Mesh | null): EdgeRange | null { + if (!this._rangeCache) { + this._rangeCache = new Map(); + let start = 0; + for (const [m, segs] of this.meshToSegments) { + this._rangeCache.set(m, { start: start * 2, count: segs.length * 2 }); + start += segs.length; + } + } + + return this._rangeCache.get(mesh) ?? null; + } +} + +export class ProjectionResult { + visibleEdges: EdgeSet; + hiddenEdges: EdgeSet; + + constructor() { + this.visibleEdges = new EdgeSet(); + this.hiddenEdges = new EdgeSet(); + } +} + +interface CollectorOptions { + onProgress?: ((processed: number, total: number) => void) | null; +} + +class ProjectedEdgeCollector { + meshes: Mesh[]; + bvhs: Map; + result: ProjectionResult; + iterationTime: number; + + constructor(scene: Object3D | Object3D[]) { + this.meshes = getAllMeshes(scene); + this.bvhs = new Map(); + this.result = new ProjectionResult(); + this.iterationTime = 30; + } + + addEdges(edges: ProjectionEdge[], options: CollectorOptions = {}): ProjectionResult { + const currIterationTime = this.iterationTime; + this.iterationTime = Infinity; + + const result = this.addEdgesGenerator(edges, options).next().value; + this.iterationTime = currIterationTime; + + return result ?? this.result; + } + + *addEdgesGenerator( + edges: ProjectionEdge[], + options: CollectorOptions = {}, + ): Generator { + if (edges.length === 0) { + return this.result; + } + + const { meshes, bvhs, iterationTime } = this; + let time = performance.now(); + + for (let i = 0; i < meshes.length; i++) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + const mesh = meshes[i]; + const geometry = mesh.geometry; + if (!bvhs.has(geometry)) { + const existing = geometry.boundsTree instanceof MeshBVH ? geometry.boundsTree : null; + const bvh = existing ?? new MeshBVH(geometry); + bvhs.set(geometry, bvh); + } + } + + const edgesBvh = new LineObjectsBVH(edges, { targetLeafSize: 2, strategy: SAH }); + const hiddenOverlapMap: OverlapRange[][] = Array.from({ length: edges.length }, () => []); + + time = performance.now(); + for (let m = 0; m < meshes.length; m++) { + if (performance.now() - time > iterationTime) { + options.onProgress?.(m, meshes.length); + yield; + time = performance.now(); + } + + const mesh = meshes[m]; + const bvh = bvhs.get(mesh.geometry); + if (bvh) { + bvhcastEdges(edgesBvh, bvh, mesh, hiddenOverlapMap); + } + } + + const { result } = this; + for (let i = 0; i < edges.length; i++) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + const line = edges[i]; + const mesh = line.mesh; + const hiddenOverlaps = hiddenOverlapMap[i]; + + if (!result.visibleEdges.meshToSegments.has(mesh)) { + result.visibleEdges.meshToSegments.set(mesh, []); + result.hiddenEdges.meshToSegments.set(mesh, []); + } + + overlapsToLines(line, hiddenOverlaps, false, result.visibleEdges.meshToSegments.get(mesh)); + overlapsToLines(line, hiddenOverlaps, true, result.hiddenEdges.meshToSegments.get(mesh)); + } + + return result; + } +} + +export type ProjectionProgressCallback = ( + percent: number, + message: string, + partialResult?: ProjectionResult, +) => void; + +export interface ProjectionOptions { + onProgress?: ProjectionProgressCallback; + signal?: AbortSignal; +} + +export class ProjectionGenerator { + iterationTime: number; + angleThreshold: number; + includeIntersectionEdges: boolean; + + constructor() { + this.iterationTime = 30; + this.angleThreshold = 50; + this.includeIntersectionEdges = true; + } + + generateSync( + input: Object3D | BufferGeometry | Object3D[], + options: ProjectionOptions = {}, + ): ProjectionResult { + const prevIterationTime = this.iterationTime; + this.iterationTime = Infinity; + try { + const task = this.generate(input, options); + let res = task.next(); + while (!res.done) { + res = task.next(); + } + return res.value ?? new ProjectionResult(); + } finally { + this.iterationTime = prevIterationTime; + } + } + + async generateAsync( + geometry: Object3D | BufferGeometry | Object3D[], + options: ProjectionOptions = {}, + ): Promise { + const { signal } = options; + const task = this.generate(geometry, options); + let res: IteratorResult | undefined; + while (!res || !res.done) { + res = task.next(); + if (!res.done) { + await nextFrame(); + } + signal?.throwIfAborted(); + } + + return res.value ?? new ProjectionResult(); + } + + *generate( + input: Object3D | BufferGeometry | Object3D[], + options: ProjectionOptions = {}, + ): Generator { + const { iterationTime, angleThreshold, includeIntersectionEdges } = this; + const { onProgress } = options; + + const scene: Object3D | Object3D[] = (input as BufferGeometry).isBufferGeometry + ? new Mesh(input as BufferGeometry) + : (input as Object3D | Object3D[]); + + const edgeGenerator = new EdgeGenerator(); + edgeGenerator.iterationTime = iterationTime; + edgeGenerator.thresholdAngle = angleThreshold; + edgeGenerator.projectionDirection.copy(UP_VECTOR); + + onProgress?.(0, "Extracting edges"); + let edges: ProjectionEdge[] = []; + yield* edgeGenerator.getEdgesGenerator(scene, edges); + if (includeIntersectionEdges) { + onProgress?.(0, "Extracting self-intersecting edges"); + yield* edgeGenerator.getIntersectionEdgesGenerator(scene, edges); + } + + onProgress?.(0, "Filtering edges"); + edges = edges.filter((e) => !isYProjectedLineDegenerate(e)); + + edges.sort((a, b) => { + const uuidA = a.mesh?.uuid ?? ""; + const uuidB = b.mesh?.uuid ?? ""; + if (uuidA === uuidB) { + return 0; + } + return uuidA < uuidB ? -1 : 1; + }); + + if (Number.isFinite(iterationTime)) { + yield; + } + + const collector = new ProjectedEdgeCollector(scene); + collector.iterationTime = iterationTime; + + onProgress?.(0, "Clipping edges", collector.result); + yield* collector.addEdgesGenerator(edges, { + onProgress: !onProgress + ? null + : (prog, tot) => { + onProgress(tot > 0 ? prog / tot : 1, "Clipping edges", collector.result); + }, + }); + + return collector.result; + } +} diff --git a/apps/web/src/lib/projection/index.ts b/apps/web/src/lib/projection/index.ts new file mode 100644 index 0000000..e1bc3c3 --- /dev/null +++ b/apps/web/src/lib/projection/index.ts @@ -0,0 +1,5 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +export { ProjectionGenerator, ProjectionResult, EdgeSet, type EdgeRange, type ProjectionOptions, type ProjectionProgressCallback } from "./ProjectionGenerator"; +export { EdgeGenerator, type EdgeInput } from "./EdgeGenerator"; +export { PlanarIntersectionGenerator } from "./PlanarIntersectionGenerator"; +export { ProjectionEdge } from "./utils/ProjectionEdge"; diff --git a/apps/web/src/lib/projection/utils/LineObjectsBVH.ts b/apps/web/src/lib/projection/utils/LineObjectsBVH.ts new file mode 100644 index 0000000..23ad115 --- /dev/null +++ b/apps/web/src/lib/projection/utils/LineObjectsBVH.ts @@ -0,0 +1,48 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { BVH, BVHOptions } from "three-mesh-bvh"; +import type { ProjectionEdge } from "./ProjectionEdge"; + +export interface LineObjectsBVHOptions extends BVHOptions { + heightOffset?: number; +} + +interface BVHInternalApi { + init(options?: BVHOptions): void; +} + +export class LineObjectsBVH extends BVH { + primitiveBuffer: ProjectionEdge[]; + primitiveBufferStride: number; + heightOffset: number; + + get lines(): ProjectionEdge[] { + return this.primitiveBuffer; + } + + constructor(lines: ProjectionEdge[], options: LineObjectsBVHOptions = {}) { + super(); + + this.primitiveBuffer = lines; + this.primitiveBufferStride = 1; + this.heightOffset = options.heightOffset ?? 1e3; + + (this as unknown as BVHInternalApi).init(options); + } + + writePrimitiveBounds(i: number, targetBuffer: Float32Array, writeOffset: number): void { + const { primitiveBuffer, heightOffset } = this; + const { start, end } = primitiveBuffer[i]; + + targetBuffer[writeOffset + 0] = Math.min(start.x, end.x); + targetBuffer[writeOffset + 1] = Math.min(start.y, end.y); + targetBuffer[writeOffset + 2] = Math.min(start.z, end.z); + + targetBuffer[writeOffset + 3] = Math.max(start.x, end.x); + targetBuffer[writeOffset + 4] = Math.max(start.y, end.y) + heightOffset; + targetBuffer[writeOffset + 5] = Math.max(start.z, end.z); + } + + getRootRanges(): Array<{ offset: number; count: number }> { + return [{ offset: 0, count: this.primitiveBuffer.length }]; + } +} diff --git a/apps/web/src/lib/projection/utils/ProjectionEdge.ts b/apps/web/src/lib/projection/utils/ProjectionEdge.ts new file mode 100644 index 0000000..1e88d7d --- /dev/null +++ b/apps/web/src/lib/projection/utils/ProjectionEdge.ts @@ -0,0 +1,16 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, Mesh, Vector3 } from "three"; + +export class ProjectionEdge extends Line3 { + mesh: Mesh | null = null; + + constructor(start?: Vector3, end?: Vector3) { + super(start, end); + } + + copy(source: Line3): this { + super.copy(source); + this.mesh = source instanceof ProjectionEdge ? source.mesh : null; + return this; + } +} diff --git a/apps/web/src/lib/projection/utils/bvhcastEdges.ts b/apps/web/src/lib/projection/utils/bvhcastEdges.ts new file mode 100644 index 0000000..a9fb412 --- /dev/null +++ b/apps/web/src/lib/projection/utils/bvhcastEdges.ts @@ -0,0 +1,100 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { BackSide, DoubleSide, FrontSide, Line3, Material, Mesh, Vector3 } from "three"; +import { ExtendedTriangle, type MeshBVH } from "three-mesh-bvh"; +import { getProjectedLineOverlap } from "./getProjectedLineOverlap"; +import { appendOverlapRange, type OverlapRange } from "./getProjectedOverlaps"; +import type { LineObjectsBVH } from "./LineObjectsBVH"; +import { isLineTriangleEdge, type ExtendedTriangleWithPlane } from "./triangleLineUtils"; +import { trimToBeneathTriPlane } from "./trimToBeneathTriPlane"; + +const UP_VECTOR = new Vector3(0, 1, 0); +const DIST_THRESHOLD = 1e-10; +const _beneathLine = /* @__PURE__ */ new Line3(); +const _overlapLine = /* @__PURE__ */ new Line3(); +const _tri = /* @__PURE__ */ new ExtendedTriangle() as unknown as ExtendedTriangleWithPlane; + +_tri.update = () => { + // override the "update" function so we only calculate the piece we need + _tri.plane.setFromCoplanarPoints(_tri.a, _tri.b, _tri.c); +}; + +export function bvhcastEdges( + edgesBvh: LineObjectsBVH, + bvh: MeshBVH, + mesh: Mesh, + hiddenOverlapMap: OverlapRange[][], +): void { + const { geometry, matrixWorld, material } = mesh; + const primaryMat: Material | undefined = Array.isArray(material) ? material[0] : material; + const side = primaryMat ? primaryMat.side : FrontSide; + const inverted = matrixWorld.determinant() < 0; + const edges = edgesBvh.lines; + const posAttr = geometry.attributes.position; + if (!posAttr) { + return; + } + + edgesBvh.bvhcast(bvh, matrixWorld, { + intersectsRanges: (edgeOffset: number, edgeCount: number, meshOffset: number, meshCount: number) => { + for (let i = meshOffset, l = meshCount + meshOffset; i < l; i++) { + const triIndex = bvh.indirect ? bvh.resolveTriangleIndex(i) : i; + let i0 = 3 * triIndex + 0; + let i1 = 3 * triIndex + 1; + let i2 = 3 * triIndex + 2; + if (geometry.index) { + i0 = geometry.index.getX(i0); + i1 = geometry.index.getX(i1); + i2 = geometry.index.getX(i2); + } + + // Transform mesh triangle to world space + const { a, b, c } = _tri; + a.fromBufferAttribute(posAttr, i0).applyMatrix4(matrixWorld); + b.fromBufferAttribute(posAttr, i1).applyMatrix4(matrixWorld); + c.fromBufferAttribute(posAttr, i2).applyMatrix4(matrixWorld); + _tri.needsUpdate = true; + _tri.update(); + + // Back-face culling matching Three.js winding polarity + if (side !== DoubleSide) { + const faceUp = (_tri.plane.normal.dot(UP_VECTOR) > 0) !== inverted; + if (faceUp === (side === BackSide)) { + continue; + } + } + + const triMaxY = Math.max(a.y, b.y, c.y); + const triMinY = Math.min(a.y, b.y, c.y); + for (let e = edgeOffset, le = edgeCount + edgeOffset; e < le; e++) { + const _line = edges[e]; + const lineMinY = Math.min(_line.start.y, _line.end.y); + const lineMaxY = Math.max(_line.start.y, _line.end.y); + + if (triMaxY <= lineMinY) { + continue; + } + + if (isLineTriangleEdge(_tri, _line)) { + continue; + } + + if (lineMaxY < triMinY) { + _beneathLine.copy(_line); + } else if (!trimToBeneathTriPlane(_tri, _line, _beneathLine)) { + continue; + } + + if (_beneathLine.distance() < DIST_THRESHOLD) { + continue; + } + + if (getProjectedLineOverlap(_beneathLine, _tri, _overlapLine)) { + appendOverlapRange(_line, _overlapLine, hiddenOverlapMap[e]); + } + } + } + + return false; + }, + }); +} diff --git a/apps/web/src/lib/projection/utils/generateEdges.ts b/apps/web/src/lib/projection/utils/generateEdges.ts new file mode 100644 index 0000000..50607ab --- /dev/null +++ b/apps/web/src/lib/projection/utils/generateEdges.ts @@ -0,0 +1,168 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { BufferGeometry, MathUtils, Matrix4, Triangle, Vector3 } from "three"; +import { ProjectionEdge } from "./ProjectionEdge"; + +const EPSILON = 1e-10; +const UP_VECTOR = /* @__PURE__ */ new Vector3(0, 1, 0); +const _v0 = /* @__PURE__ */ new Vector3(); +const _v1 = /* @__PURE__ */ new Vector3(); +const _normal = /* @__PURE__ */ new Vector3(); +const _triangle = /* @__PURE__ */ new Triangle(); +const _triangleLocal = /* @__PURE__ */ new Triangle(); +const _localProjection = /* @__PURE__ */ new Vector3(); +const _invMat = /* @__PURE__ */ new Matrix4(); + +export interface GenerateEdgesOptions { + matrix?: Matrix4 | null; + thresholdAngle?: number; + iterationTime?: number; + projectionDirection?: Vector3; +} + +interface EdgeRecord { + index0: number; + index1: number; + normal: Vector3; +} + +export function* generateEdges( + geometry: BufferGeometry, + target: ProjectionEdge[] = [], + options: GenerateEdgesOptions = {}, +): Generator { + const { + matrix = null, + thresholdAngle = 1, + iterationTime = 30, + projectionDirection = UP_VECTOR, + } = options; + + _localProjection.copy(projectionDirection); + + let isAffine = true; + if (matrix) { + isAffine = + matrix.elements[3] === 0 && + matrix.elements[7] === 0 && + matrix.elements[11] === 0 && + matrix.elements[15] === 1; + + if (isAffine) { + _invMat.copy(matrix).invert(); + _localProjection.transformDirection(_invMat); + } + } + + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle); + + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + if (!positionAttr) { + return target; + } + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + + const indexArr: [number, number, number] = [0, 0, 0]; + const vertKeys: ["a", "b", "c"] = ["a", "b", "c"]; + const hashes = new Array(3); + + const edgeData: Record = Object.create(null); + let time = performance.now(); + + for (let i = 0; i + 2 < indexCount; i += 3) { + if (performance.now() - time > iterationTime) { + yield; + time = performance.now(); + } + + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + + const { a, b, c } = _triangleLocal; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + + if (matrix && !isAffine) { + _triangle.copy(_triangleLocal); + _triangle.a.applyMatrix4(matrix); + _triangle.b.applyMatrix4(matrix); + _triangle.c.applyMatrix4(matrix); + _triangle.getNormal(_normal); + } else { + _triangleLocal.getNormal(_normal); + } + + for (let j = 0; j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangleLocal[vertKeys[j]]; + const v1 = _triangleLocal[vertKeys[jNext]]; + + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + + const sibling = edgeData[reverseHash]; + if (sibling) { + const otherNormal = sibling.normal; + const meetsThreshold = _normal.dot(otherNormal) <= thresholdDot; + + let normDot = _localProjection.dot(_normal); + normDot = Math.abs(normDot) < EPSILON ? 0 : normDot; + + let otherDot = _localProjection.dot(otherNormal); + otherDot = Math.abs(otherDot) < EPSILON ? 0 : otherDot; + + const projectionThreshold = Math.sign(normDot) !== Math.sign(otherDot); + + if (meetsThreshold || projectionThreshold) { + const line = new ProjectionEdge(); + line.start.copy(v0); + line.end.copy(v1); + target.push(line); + } + + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone(), + }; + } + } + } + + for (const key in edgeData) { + const entry = edgeData[key]; + if (entry) { + _v0.fromBufferAttribute(positionAttr, entry.index0); + _v1.fromBufferAttribute(positionAttr, entry.index1); + + const line = new ProjectionEdge(); + line.start.copy(_v0); + line.end.copy(_v1); + target.push(line); + } + } + + return target; +} diff --git a/apps/web/src/lib/projection/utils/generateIntersectionEdges.ts b/apps/web/src/lib/projection/utils/generateIntersectionEdges.ts new file mode 100644 index 0000000..33b85ba --- /dev/null +++ b/apps/web/src/lib/projection/utils/generateIntersectionEdges.ts @@ -0,0 +1,73 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, Matrix4, Triangle, Vector3 } from "three"; +import type { ExtendedTriangle, MeshBVH } from "three-mesh-bvh"; +import { ProjectionEdge } from "./ProjectionEdge"; +import { isLineTriangleEdge, type ExtendedTriangleWithPlane } from "./triangleLineUtils"; + +const _line = /* @__PURE__ */ new Line3(); + +interface ExtendedTriangleIntersectApi { + intersectsTriangle(other: Triangle, target?: Line3, suppressLog?: boolean): boolean; +} + +export function generateIntersectionEdges( + bvhA: MeshBVH, + bvhB: MeshBVH, + matrixBToA: Matrix4, + target: ProjectionEdge[] = [], + _options: { iterationTime?: number } = {}, +): ProjectionEdge[] { + bvhA.bvhcast(bvhB, matrixBToA, { + intersectsTriangles: (tri1: ExtendedTriangle, tri2: ExtendedTriangle) => { + const t1 = tri1 as unknown as ExtendedTriangleWithPlane; + const t2 = tri2 as unknown as ExtendedTriangleWithPlane; + + if (areTrianglesOnEdge(t1, t2)) { + return false; + } + + if (t1.needsUpdate) { + t1.update(); + } + if (t2.needsUpdate) { + t2.update(); + } + + if (Math.abs(t1.plane.normal.dot(t2.plane.normal)) > 1 - 1e-6) { + return false; + } + + if ( + (tri1 as unknown as ExtendedTriangleIntersectApi).intersectsTriangle(tri2, _line, true) && + !isLineTriangleEdge(t1, _line) && + !isLineTriangleEdge(t2, _line) + ) { + target.push(new ProjectionEdge().copy(_line)); + } + + return false; + }, + }); + + return target; +} + +function areVectorsEqual(a: Vector3, b: Vector3): boolean { + return a.distanceTo(b) < 1e-10; +} + +function areTrianglesOnEdge(t1: Triangle, t2: Triangle): boolean { + const pts1 = [t1.a, t1.b, t1.c] as const; + const pts2 = [t2.a, t2.b, t2.c] as const; + let tot = 0; + + for (let i = 0; i < 3; i++) { + for (let j = 0; j < 3; j++) { + if (areVectorsEqual(pts1[i], pts2[j])) { + tot++; + } + } + } + + return tot >= 2; +} diff --git a/apps/web/src/lib/projection/utils/getAllMeshes.ts b/apps/web/src/lib/projection/utils/getAllMeshes.ts new file mode 100644 index 0000000..c15abbd --- /dev/null +++ b/apps/web/src/lib/projection/utils/getAllMeshes.ts @@ -0,0 +1,17 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import type { Mesh, Object3D } from "three"; + +export function getAllMeshes(scene: Object3D | Object3D[]): Mesh[] { + const arr = Array.isArray(scene) ? scene : [scene]; + const result = new Set(); + for (let i = 0, l = arr.length; i < l; i++) { + arr[i].traverse((c) => { + const candidate = c as Mesh; + if (candidate.geometry && candidate.visible) { + result.add(candidate); + } + }); + } + + return Array.from(result); +} diff --git a/apps/web/src/lib/projection/utils/getProjectedLineOverlap.ts b/apps/web/src/lib/projection/utils/getProjectedLineOverlap.ts new file mode 100644 index 0000000..8d41257 --- /dev/null +++ b/apps/web/src/lib/projection/utils/getProjectedLineOverlap.ts @@ -0,0 +1,111 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, Plane, Vector3 } from "three"; +import { ExtendedTriangle } from "three-mesh-bvh"; +import type { ExtendedTriangleWithPlane } from "./triangleLineUtils"; + +const AREA_EPSILON = 1e-16; +const DIST_EPSILON = 1e-16; +const _orthoPlane = /* @__PURE__ */ new Plane(); +const _point = /* @__PURE__ */ new Vector3(); +const _vec = /* @__PURE__ */ new Vector3(); +const _tri = /* @__PURE__ */ new ExtendedTriangle() as unknown as ExtendedTriangleWithPlane; +const _line = /* @__PURE__ */ new Line3(); +const _triLine = /* @__PURE__ */ new Line3(); +const _dir = /* @__PURE__ */ new Vector3(); +const _ortho = /* @__PURE__ */ new Vector3(); +const _triDir = /* @__PURE__ */ new Vector3(); + +// Returns the portion of the line that is overlapping the triangle when projected +export function getProjectedLineOverlap( + line: Line3, + triangle: ExtendedTriangleWithPlane, + lineTarget: Line3 = new Line3(), +): Line3 | null { + _tri.copy(triangle); + _tri.a.y = 0; + _tri.b.y = 0; + _tri.c.y = 0; + _tri.update(); + + _line.copy(line); + _line.start.y = 0; + _line.end.y = 0; + + if (_tri.getArea() <= AREA_EPSILON) { + return null; + } + + const lineDistance = _line.distance(); + if (lineDistance <= DIST_EPSILON) { + return null; + } + + _line.delta(_dir).divideScalar(lineDistance); + _ortho.copy(_dir).cross(_tri.plane.normal).normalize(); + _orthoPlane.setFromNormalAndCoplanarPoint(_ortho, _line.start); + + let intersectCount = 0; + const { points } = _tri; + for (let i = 0; i < 3; i++) { + const p1 = points[i]; + const p2 = points[(i + 1) % 3]; + + const distToStart = _orthoPlane.distanceToPoint(p1); + const distToEnd = _orthoPlane.distanceToPoint(p2); + + const startIntersects = Math.abs(distToStart) < DIST_EPSILON; + const endIntersects = Math.abs(distToEnd) < DIST_EPSILON; + + if (startIntersects && endIntersects) { + continue; + } else if (startIntersects) { + _point.copy(p1); + } else if (endIntersects) { + continue; + } else if ((distToStart < 0.0) === (distToEnd < 0.0)) { + continue; + } else { + const t = distToStart / (distToStart - distToEnd); + _point.lerpVectors(p1, p2, t); + } + + if (intersectCount === 0) { + _triLine.start.copy(_point); + } else if (intersectCount === 1) { + _triLine.end.copy(_point); + } + + intersectCount++; + if (intersectCount === 2) { + break; + } + } + + if (intersectCount === 2) { + _triLine.delta(_triDir).normalize(); + + if (_dir.dot(_triDir) < 0) { + const tmp = _triLine.start; + _triLine.start = _triLine.end; + _triLine.end = tmp; + } + + const s1 = 0; + const e1 = _vec.subVectors(_line.end, _line.start).dot(_dir); + const s2 = _vec.subVectors(_triLine.start, _line.start).dot(_dir); + const e2 = _vec.subVectors(_triLine.end, _line.start).dot(_dir); + const separated1 = e1 <= s2; + const separated2 = e2 <= s1; + + if (separated1 || separated2) { + return null; + } + + line.at(Math.max(s1, s2) / lineDistance, lineTarget.start); + line.at(Math.min(e1, e2) / lineDistance, lineTarget.end); + + return lineTarget; + } + + return null; +} diff --git a/apps/web/src/lib/projection/utils/getProjectedOverlaps.ts b/apps/web/src/lib/projection/utils/getProjectedOverlaps.ts new file mode 100644 index 0000000..59cbfff --- /dev/null +++ b/apps/web/src/lib/projection/utils/getProjectedOverlaps.ts @@ -0,0 +1,78 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, Vector3 } from "three"; + +const DIST_EPSILON = 1e-16; +const _dir = /* @__PURE__ */ new Vector3(); +const _v0 = /* @__PURE__ */ new Vector3(); +const _v1 = /* @__PURE__ */ new Vector3(); + +export type OverlapRange = [number, number]; + +export function appendOverlapRange( + line: Line3, + overlapLine: Line3, + overlapsTarget: OverlapRange[], +): boolean { + const result = getOverlapRange(line, overlapLine); + if (result) { + insertOverlap(result, overlapsTarget); + return true; + } + + return false; +} + +export function getOverlapRange(line: Line3, overlapLine: Line3): OverlapRange | null { + line.delta(_dir); + _v0.subVectors(overlapLine.start, line.start); + _v1.subVectors(overlapLine.end, line.start); + + const length = _dir.length(); + if (length <= DIST_EPSILON) { + return null; + } + + let t0 = _v0.length() / length; + let t1 = _v1.length() / length; + + t0 = Math.min(Math.max(t0, 0), 1); + t1 = Math.min(Math.max(t1, 0), 1); + + if (Math.abs(t0 - t1) <= DIST_EPSILON) { + return null; + } + + return t0 <= t1 ? [t0, t1] : [t1, t0]; +} + +export function insertOverlap(result: OverlapRange, overlapsTarget: OverlapRange[]): void { + let [start, end] = result; + + let left = 0; + let right = overlapsTarget.length; + while (left < right) { + const mid = (left + right) >>> 1; + if (overlapsTarget[mid][0] <= start) { + left = mid + 1; + } else { + right = mid; + } + } + + let insertPoint = Math.max(0, left - 1); + let deleteCount = 0; + for (let i = insertPoint, l = overlapsTarget.length; i < l; i++) { + const [otherStart, otherEnd] = overlapsTarget[i]; + if (start <= otherEnd && end >= otherStart) { + start = Math.min(otherStart, start); + end = Math.max(otherEnd, end); + deleteCount++; + } else if (start >= otherStart) { + insertPoint = i + 1; + } else { + break; + } + } + + overlapsTarget.splice(insertPoint, deleteCount, [start, end]); +} diff --git a/apps/web/src/lib/projection/utils/nextFrame.ts b/apps/web/src/lib/projection/utils/nextFrame.ts new file mode 100644 index 0000000..f9f8aae --- /dev/null +++ b/apps/web/src/lib/projection/utils/nextFrame.ts @@ -0,0 +1,19 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +export const nextFrame = (): Promise => + new Promise((resolve) => { + if (typeof requestAnimationFrame !== "function") { + setTimeout(resolve, 0); + return; + } + + let rafHandle = 0; + let timeoutHandle: ReturnType; + const cb = () => { + cancelAnimationFrame(rafHandle); + clearTimeout(timeoutHandle); + resolve(); + }; + + rafHandle = requestAnimationFrame(cb); + timeoutHandle = setTimeout(cb, 16); + }); diff --git a/apps/web/src/lib/projection/utils/overlapUtils.ts b/apps/web/src/lib/projection/utils/overlapUtils.ts new file mode 100644 index 0000000..975d5d2 --- /dev/null +++ b/apps/web/src/lib/projection/utils/overlapUtils.ts @@ -0,0 +1,51 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3 } from "three"; +import type { OverlapRange } from "./getProjectedOverlaps"; + +const _line = /* @__PURE__ */ new Line3(); + +// Converts the given array of overlaps into line segments +export function overlapsToLines( + line: Line3, + overlaps: OverlapRange[], + invert = false, + target: Float32Array[] = [], +): number { + let invOverlaps: OverlapRange[] = [[0, 1]]; + for (let i = 0, l = overlaps.length; i < l; i++) { + const invOverlap = invOverlaps[i]; + const overlap = overlaps[i]; + invOverlap[1] = overlap[0]; + invOverlaps.push([overlap[1], 1]); + } + + let selected = invOverlaps; + if (invert) { + selected = overlaps; + } + + for (let i = 0, l = selected.length; i < l; i++) { + const { start, end } = line; + const t0 = selected[i][0]; + const t1 = selected[i][1]; + if (Math.abs(t1 - t0) <= 1e-12) { + continue; + } + + _line.start.lerpVectors(start, end, t0); + _line.end.lerpVectors(start, end, t1); + + target.push( + new Float32Array([ + _line.start.x, + _line.start.y, + _line.start.z, + _line.end.x, + _line.end.y, + _line.end.z, + ]), + ); + } + + return selected.length; +} diff --git a/apps/web/src/lib/projection/utils/triangleLineUtils.ts b/apps/web/src/lib/projection/utils/triangleLineUtils.ts new file mode 100644 index 0000000..109dfb5 --- /dev/null +++ b/apps/web/src/lib/projection/utils/triangleLineUtils.ts @@ -0,0 +1,57 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, Vector3 } from "three"; +import type { ExtendedTriangle } from "three-mesh-bvh"; + +const EPSILON = 1e-16; +const UP_VECTOR = /* @__PURE__ */ new Vector3(0, 1, 0); +const _dir = new Vector3(); + +export function isYProjectedLineDegenerate(line: Line3): boolean { + line.delta(_dir).normalize(); + return Math.abs(_dir.dot(UP_VECTOR)) >= 1.0 - EPSILON; +} + +// checks whether the y-projected triangle will be degenerate +export function isYProjectedTriangleDegenerate(tri: ExtendedTriangle): boolean { + const extended = tri as ExtendedTriangleWithPlane; + if (extended.needsUpdate) { + extended.update(); + } + + return Math.abs(extended.plane.normal.dot(UP_VECTOR)) <= EPSILON; +} + +export interface ExtendedTriangleWithPlane extends ExtendedTriangle { + plane: { + normal: Vector3; + constant: number; + setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): unknown; + }; + points: [Vector3, Vector3, Vector3]; + update(): void; +} + +// Is the provided line exactly an edge on the triangle +export function isLineTriangleEdge(tri: ExtendedTriangleWithPlane, line: Line3): boolean { + const { start, end } = line; + const triPoints = tri.points; + let startMatches = false; + let endMatches = false; + + for (let i = 0; i < 3; i++) { + const tp = triPoints[i]; + if (!startMatches && start.distanceToSquared(tp) <= EPSILON) { + startMatches = true; + } + + if (!endMatches && end.distanceToSquared(tp) <= EPSILON) { + endMatches = true; + } + + if (startMatches && endMatches) { + return true; + } + } + + return startMatches && endMatches; +} diff --git a/apps/web/src/lib/projection/utils/trimToBeneathTriPlane.ts b/apps/web/src/lib/projection/utils/trimToBeneathTriPlane.ts new file mode 100644 index 0000000..76fdf1c --- /dev/null +++ b/apps/web/src/lib/projection/utils/trimToBeneathTriPlane.ts @@ -0,0 +1,67 @@ +// Ported from three-edge-projection (MIT License - Copyright (c) 2023 Garrett Johnson) +import { Line3, MathUtils, Plane, Vector3 } from "three"; +import type { ExtendedTriangleWithPlane } from "./triangleLineUtils"; + +const EPSILON = 1e-16; +const UP_VECTOR = /* @__PURE__ */ new Vector3(0, 1, 0); +const _plane = /* @__PURE__ */ new Plane(); +const _planeHit = /* @__PURE__ */ new Vector3(); +const _lineDirection = /* @__PURE__ */ new Vector3(); + +export function trimToBeneathTriPlane( + tri: ExtendedTriangleWithPlane, + line: Line3, + lineTarget: Line3, +): boolean { + if (tri.needsUpdate) { + tri.update(); + } + + // if the plane is not facing up then flip the direction + _plane.normal.copy(tri.plane.normal); + _plane.constant = tri.plane.constant; + if (_plane.normal.dot(UP_VECTOR) < 0) { + _plane.normal.multiplyScalar(-1); + _plane.constant *= -1; + } + + const startDist = _plane.distanceToPoint(line.start); + const endDist = _plane.distanceToPoint(line.end); + const isStartOnPlane = Math.abs(startDist) < EPSILON; + const isStartBelow = startDist < 0; + const isEndBelow = endDist < 0; + + // if the line and plane are coplanar then return that we can't trim + line.delta(_lineDirection).normalize(); + if (Math.abs(_plane.normal.dot(_lineDirection)) < EPSILON) { + if (isStartOnPlane || !isStartBelow) { + return false; + } + lineTarget.copy(line); + return true; + } + + if (isStartBelow && isEndBelow) { + lineTarget.copy(line); + return true; + } + if (!isStartBelow && !isEndBelow) { + return false; + } + + const t = MathUtils.mapLinear(0, startDist, endDist, 0, 1); + line.at(t, _planeHit); + + if (isStartBelow) { + lineTarget.start.copy(line.start); + lineTarget.end.copy(_planeHit); + return true; + } + if (isEndBelow) { + lineTarget.end.copy(line.end); + lineTarget.start.copy(_planeHit); + return true; + } + + return false; +} diff --git a/apps/web/src/lib/serviceWorker.ts b/apps/web/src/lib/serviceWorker.ts index 012aec2..10841f2 100644 --- a/apps/web/src/lib/serviceWorker.ts +++ b/apps/web/src/lib/serviceWorker.ts @@ -8,5 +8,5 @@ * * `apps/web/public/sw.js` içindeki CACHE_NAME ile birlikte artırılmalıdır. */ -export const SERVICE_WORKER_VERSION = "1.2.0"; +export const SERVICE_WORKER_VERSION = "1.2.1"; export const SERVICE_WORKER_URL = `/sw.js?v=${SERVICE_WORKER_VERSION}`; diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts index e7a5032..afb8c65 100644 --- a/apps/web/src/lib/skfProject.ts +++ b/apps/web/src/lib/skfProject.ts @@ -12,7 +12,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, export const SKF_SCHEMA_ID = "com.sketchforge.project"; export const SKF_FORMAT_VERSION = 2; export const SKF_MINIMUM_READER_VERSION = 2; -export const SKF_CREATED_WITH_VERSION = "1.0.9"; +export const SKF_CREATED_WITH_VERSION = process.env.NEXT_PUBLIC_APP_VERSION?.trim() || "1.0.10"; export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip"; export const SKF_LIMITS = { @@ -1174,6 +1174,10 @@ async function defaultSourceImporter(asset: ProjectAsset) { const { importedShapeFromStep } = await import("@/lib/stepImport"); return (await importedShapeFromStep(asset.name, exactArrayBuffer(asset.bytes))).importedMesh as NonNullable; } + if (asset.sourceFormat === "ifc") { + const { importedShapeFromIfc } = await import("@/lib/ifcImport"); + return (await importedShapeFromIfc(asset.name, new Uint8Array(asset.bytes))).importedMesh as NonNullable; + } if (asset.sourceFormat === "dwg") { const { importedShapeFromDwg } = await import("@/lib/dwgKernel"); return (await importedShapeFromDwg(asset.name, new Uint8Array(asset.bytes))).importedMesh as NonNullable; diff --git a/apps/web/src/lib/stlImport.ts b/apps/web/src/lib/stlImport.ts index 254fb84..a77f9cd 100644 --- a/apps/web/src/lib/stlImport.ts +++ b/apps/web/src/lib/stlImport.ts @@ -2,6 +2,7 @@ import * as THREE from "three"; import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js"; import { createLocalId } from "@/lib/localIds"; import { zUpToSketchForge } from "@/lib/meshCoordinates"; +import { cleanTriangleSoup, normalizeClosedMeshWinding } from "@/lib/meshSanitizer"; import type { WorkplaneShape } from "@/types/sketchforge"; const stlLoader = new STLLoader(); @@ -45,10 +46,16 @@ export function importedShapeFromTriangleSoup( rawNormals: number[] | undefined, sourceFormat: NonNullable["sourceFormat"] = "stl", ): WorkplaneShape { + const cleaned = cleanTriangleSoup(rawPositions, rawNormals); + if (cleaned.positions.length < 9) { + throw new Error("STL geometry is empty"); + } + const normalized = normalizeClosedMeshWinding(cleaned.positions, cleaned.normals); + const geometry = new THREE.BufferGeometry(); - geometry.setAttribute("position", new THREE.Float32BufferAttribute(rawPositions, 3)); - if (rawNormals?.length === rawPositions.length) { - geometry.setAttribute("normal", new THREE.Float32BufferAttribute(rawNormals, 3)); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(normalized.positions, 3)); + if (!normalized.wasFlipped && normalized.normals?.length === normalized.positions.length) { + geometry.setAttribute("normal", new THREE.Float32BufferAttribute(normalized.normals, 3)); } else { geometry.computeVertexNormals(); } diff --git a/apps/web/src/lib/technicalProjectionBridge.ts b/apps/web/src/lib/technicalProjectionBridge.ts new file mode 100644 index 0000000..c4a2c50 --- /dev/null +++ b/apps/web/src/lib/technicalProjectionBridge.ts @@ -0,0 +1,1272 @@ +import * as THREE from "three"; +import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js"; +import { ADDITION, Brush, Evaluator, HOLLOW_SUBTRACTION, INTERSECTION, SUBTRACTION } from "three-bvh-csg"; +import { createGearGeometry } from "@/lib/gearGeometry"; +import { cleanTriangleSoup, normalizeClosedMeshWinding } from "@/lib/meshSanitizer"; +import { PlanarIntersectionGenerator, ProjectionGenerator } from "@/lib/projection"; +import { + meshYawDegrees, + mirrorSign, + mirroredAxisCount, + resizedImportedMeshPositions, + shapeDepth, + shapeHasTaper, + shapeTaperScaleAt, + shapeWidth, +} from "@/lib/workplaneShapes"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +export type ProjectedLayerId = "VISIBLE" | "HIDDEN" | "CENTER" | "DIMENSION" | "HATCH" | "ANNOTATION"; +export type ProjectedViewKind = "front" | "top" | "side" | "isometric"; + +export interface NormalizedSegment2D { + x1: number; + y1: number; + x2: number; + y2: number; +} + +export interface NormalizedViewProjection { + visible: NormalizedSegment2D[]; + hidden: NormalizedSegment2D[]; + sectionCut: NormalizedSegment2D[]; +} + +export interface ModelProjectionCache { + center: { cx: number; cy: number; cz: number }; + bounds: { minX: number; maxX: number; minY: number; maxY: number; minZ: number; maxZ: number }; + views: Record; + csgApplied: boolean; + triangleCount: number; +} + +export interface ProjectedPrimitive2D { + kind: "rect" | "circle" | "line"; + layer: ProjectedLayerId; + x: number; + y: number; + w?: number; + h?: number; + r?: number; + x2?: number; + y2?: number; + label?: string; +} + +const CUTTER_PAD = 0.04; +const MAX_CSG_TRIANGLES = 32_000; +const MAX_HLR_TRIANGLES = 48_000; + +function clampNumber(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} + +function ensureNonIndexedPosNormal(geometry: THREE.BufferGeometry): THREE.BufferGeometry { + const nonIndexed = geometry.index ? geometry.toNonIndexed() : geometry; + if (nonIndexed !== geometry) { + geometry.dispose(); + } + const posAttr = nonIndexed.getAttribute("position"); + if (!posAttr) { + return nonIndexed; + } + + let target: THREE.BufferGeometry = nonIndexed; + if (!(nonIndexed instanceof THREE.BufferGeometry)) { + const cloned = new THREE.BufferGeometry(); + cloned.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(posAttr.array as ArrayLike), 3)); + (nonIndexed as THREE.BufferGeometry).dispose(); + target = cloned; + } else { + for (const attrName of Object.keys(target.attributes)) { + if (attrName !== "position" && attrName !== "normal") { + target.deleteAttribute(attrName); + } + } + } + target.computeVertexNormals(); + return target; +} + +function extractPositionsArray(geometry: THREE.BufferGeometry): number[] { + const nonIndexed = geometry.index ? geometry.toNonIndexed() : geometry; + const posAttr = nonIndexed.getAttribute("position"); + const out: number[] = []; + if (posAttr) { + for (let i = 0; i < posAttr.count; i++) { + out.push(posAttr.getX(i), posAttr.getY(i), posAttr.getZ(i)); + } + } + if (nonIndexed !== geometry) { + nonIndexed.dispose(); + } + return out; +} + +function geometryFromCleanPositions(positions: number[]): THREE.BufferGeometry | null { + if (positions.length < 9) { + return null; + } + const cleaned = cleanTriangleSoup(positions); + if (cleaned.triangleCount === 0) { + return null; + } + const finalPositions = normalizeClosedMeshWinding(cleaned.positions).positions; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(finalPositions, 3)); + geometry.computeVertexNormals(); + return geometry; +} + +function mergeGeometriesPosNormal(geometries: THREE.BufferGeometry[]): THREE.BufferGeometry | null { + if (geometries.length === 0) { + return null; + } + const combined: number[] = []; + for (const geom of geometries) { + const arr = extractPositionsArray(geom); + for (let i = 0; i < arr.length; i++) { + combined.push(arr[i]); + } + } + if (combined.length < 9) { + return null; + } + const merged = new THREE.BufferGeometry(); + merged.setAttribute("position", new THREE.Float32BufferAttribute(combined, 3)); + merged.computeVertexNormals(); + return merged; +} + +function createRoofGeometry(width: number, height: number, depth: number): THREE.BufferGeometry { + const w = width / 2; + const d = depth / 2; + const vertices = new Float32Array([ + -w, 0, -d, w, 0, -d, 0, height, -d, + -w, 0, d, w, 0, d, 0, height, d, + ]); + const indices = [ + 0, 2, 1, + 3, 4, 5, + 0, 1, 4, 0, 4, 3, + 0, 3, 5, 0, 5, 2, + 1, 2, 5, 1, 5, 4, + ]; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3)); + geometry.setIndex(indices); + return geometry; +} + +function createWedgeGeometry(width: number, height: number, depth: number): THREE.BufferGeometry { + const w = width / 2; + const d = depth / 2; + const vertices = new Float32Array([ + -w, 0, -d, w, 0, -d, w, height, -d, + -w, 0, d, w, 0, d, w, height, d, + ]); + const indices = [ + 0, 2, 1, + 3, 4, 5, + 0, 1, 4, 0, 4, 3, + 1, 2, 5, 1, 5, 4, + 0, 3, 5, 0, 5, 2, + ]; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3)); + geometry.setIndex(indices); + return geometry; +} + +function createPyramidGeometry(width: number, height: number, depth: number, sides = 4): THREE.BufferGeometry { + const count = Math.max(3, Math.round(sides)); + if (count !== 4) { + const geom = new THREE.ConeGeometry(1, height, count); + geom.scale(width / 2, 1, depth / 2); + geom.translate(0, height / 2, 0); + return geom; + } + const w = width / 2; + const d = depth / 2; + const vertices = new Float32Array([ + -w, 0, -d, w, 0, -d, w, 0, d, -w, 0, d, + 0, height, 0, + ]); + const indices = [ + 0, 1, 2, 0, 2, 3, + 0, 4, 1, + 1, 4, 2, + 2, 4, 3, + 3, 4, 0, + ]; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3)); + geometry.setIndex(indices); + return geometry; +} + +function createRoundRoofGeometry(width: number, height: number, depth: number, sides = 32): THREE.BufferGeometry { + const radius = Math.max(0.01, width / 2); + const segments = Math.max(6, Math.min(48, Math.round(sides))); + const shape = new THREE.Shape(); + shape.moveTo(-radius, 0); + shape.absarc(0, 0, radius, Math.PI, 0, true); + shape.lineTo(-radius, 0); + shape.closePath(); + + const geometry = new THREE.ExtrudeGeometry(shape, { depth, bevelEnabled: false, steps: 1, curveSegments: segments }); + geometry.translate(0, 0, -depth / 2); + geometry.scale(1, height / radius, 1); + return geometry; +} + +function createHalfSphereGeometry(width: number, height: number, depth: number, steps = 16): THREE.BufferGeometry { + const lon = Math.max(8, Math.min(36, Math.round(steps) * 2)); + const lat = Math.max(4, Math.min(18, Math.round(steps / 2))); + const rx = width / 2; + const rz = depth / 2; + const positions: number[] = []; + + const pt = (latIndex: number, lonIndex: number): [number, number, number] => { + const theta = (latIndex / lat) * (Math.PI / 2); + const phi = ((lonIndex % lon) / lon) * Math.PI * 2; + const ring = Math.sin(theta); + return [Math.cos(phi) * rx * ring, Math.cos(theta) * height, Math.sin(phi) * rz * ring]; + }; + const addTri = (a: [number, number, number], b: [number, number, number], c: [number, number, number]) => { + positions.push(...a, ...b, ...c); + }; + + const top: [number, number, number] = [0, height, 0]; + for (let xStep = 0; xStep < lon; xStep++) { + addTri(top, pt(1, xStep + 1), pt(1, xStep)); + } + for (let yStep = 1; yStep < lat; yStep++) { + for (let xStep = 0; xStep < lon; xStep++) { + const next = xStep + 1; + const a = pt(yStep, xStep); + const b = pt(yStep, next); + const c = pt(yStep + 1, next); + const d = pt(yStep + 1, xStep); + addTri(a, c, d); + addTri(a, b, c); + } + } + const bottomCenter: [number, number, number] = [0, 0, 0]; + const capPoint = (lonIndex: number): [number, number, number] => { + const phi = ((lonIndex % lon) / lon) * Math.PI * 2; + return [Math.cos(phi) * rx, 0, Math.sin(phi) * rz]; + }; + for (let xStep = 0; xStep < lon; xStep++) { + addTri(bottomCenter, capPoint(xStep), capPoint(xStep + 1)); + } + + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + geometry.computeVertexNormals(); + return geometry; +} + +function createTorusPrimitiveGeometry(width: number, height: number, depth: number): THREE.BufferGeometry { + const tubeRadius = Math.max(0.1, height / 2); + const majorRadius = Math.max(0.2, Math.min(width, depth) / 2 - tubeRadius); + const geometry = new THREE.TorusGeometry(majorRadius, tubeRadius, 18, 48); + geometry.rotateX(Math.PI / 2); + const outerDiameter = (majorRadius + tubeRadius) * 2; + geometry.scale(width / Math.max(0.001, outerDiameter), 1, depth / Math.max(0.001, outerDiameter)); + geometry.translate(0, height / 2, 0); + return geometry; +} + +function createHollowCylinderGeometry( + width: number, + height: number, + depth: number, + thickness: number, + segments = 32, +): THREE.BufferGeometry { + const outerX = width / 2; + const outerZ = depth / 2; + const safeThickness = clampNumber(thickness, 0.1, Math.max(0.1, Math.min(outerX, outerZ) - 0.1)); + const innerX = Math.max(0.1, outerX - safeThickness); + const innerZ = Math.max(0.1, outerZ - safeThickness); + const count = Math.max(12, Math.min(64, Math.round(segments))); + const positions: number[] = []; + + const pt = (rx: number, rz: number, y: number, idx: number): [number, number, number] => { + const angle = (idx / count) * Math.PI * 2; + return [Math.cos(angle) * rx, y, Math.sin(angle) * rz]; + }; + const addTri = (a: [number, number, number], b: [number, number, number], c: [number, number, number]) => { + positions.push(...a, ...b, ...c); + }; + const addQuad = ( + a: [number, number, number], + b: [number, number, number], + c: [number, number, number], + d: [number, number, number], + ) => { + addTri(a, b, c); + addTri(a, c, d); + }; + + for (let i = 0; i < count; i++) { + const next = i + 1; + const ob0 = pt(outerX, outerZ, 0, i); + const ob1 = pt(outerX, outerZ, 0, next); + const ot0 = pt(outerX, outerZ, height, i); + const ot1 = pt(outerX, outerZ, height, next); + const ib0 = pt(innerX, innerZ, 0, i); + const ib1 = pt(innerX, innerZ, 0, next); + const it0 = pt(innerX, innerZ, height, i); + const it1 = pt(innerX, innerZ, height, next); + + addQuad(ob0, ot0, ot1, ob1); + addQuad(ib1, it1, it0, ib0); + addQuad(ot0, it0, it1, ot1); + addQuad(ob0, ob1, ib1, ib0); + } + + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + geometry.computeVertexNormals(); + return geometry; +} + +function buildLocalPrimitiveGeometry(shape: WorkplaneShape, radialSegments = 32): THREE.BufferGeometry | null { + const width = Math.max(0.05, shapeWidth(shape)); + const depth = Math.max(0.05, shapeDepth(shape)); + const height = Math.max(0.05, shape.height); + const size = Math.min(width, depth); + let geom: THREE.BufferGeometry | null = null; + + switch (shape.kind) { + case "box": + geom = + shape.radius && shape.radius > 0 + ? new RoundedBoxGeometry(width, height, depth, Math.max(1, Math.min(6, shape.steps ?? 4)), shape.radius) + : new THREE.BoxGeometry(width, height, depth); + geom.translate(0, height / 2, 0); + break; + case "cylinder": { + const segs = Math.max(12, Math.min(64, shape.sides ?? radialSegments)); + geom = new THREE.CylinderGeometry(1, 1, height, segs, shape.segments ?? 1); + geom.scale(width / 2, 1, depth / 2); + geom.translate(0, height / 2, 0); + break; + } + case "cone": { + const segs = Math.max(12, Math.min(64, shape.sides ?? radialSegments)); + const baseRadius = shape.baseRadius ?? width / 2; + geom = new THREE.CylinderGeometry(shape.topRadius ?? 0, baseRadius, height, segs); + geom.scale(1, 1, depth / Math.max(0.001, width)); + geom.translate(0, height / 2, 0); + break; + } + case "sphere": + geom = new THREE.SphereGeometry(1, Math.max(12, Math.min(32, radialSegments)), Math.max(8, Math.min(20, Math.round(radialSegments / 2)))); + geom.scale(width / 2, height / 2, depth / 2); + geom.translate(0, height / 2, 0); + break; + case "halfSphere": + geom = createHalfSphereGeometry(width, height, depth, Math.max(8, Math.min(20, shape.steps ?? 16))); + break; + case "pyramid": + geom = createPyramidGeometry(width, height, depth, shape.sides ?? 4); + break; + case "roof": + geom = createRoofGeometry(width, height, depth); + break; + case "roundRoof": + geom = createRoundRoofGeometry(width, height, depth, Math.min(48, shape.sides ?? radialSegments)); + break; + case "wedge": + geom = createWedgeGeometry(width, height, depth); + break; + case "polygon": + geom = new THREE.CylinderGeometry(1, 1, height, 6); + geom.scale(width / 2, 1, depth / 2); + geom.translate(0, height / 2, 0); + break; + case "icosahedron": + geom = new THREE.IcosahedronGeometry(size / 2, 1); + geom.scale(width / size, height / size, depth / size); + geom.translate(0, height / 2, 0); + break; + case "torus": + geom = createTorusPrimitiveGeometry(width, height, depth); + break; + case "ring": + case "tube": + geom = createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, Math.min(48, radialSegments)); + break; + case "gear": + geom = createGearGeometry({ + width, + depth, + height, + teeth: shape.teeth, + toothSize: shape.toothSize, + toothWidth: shape.toothWidth, + centerHoleSize: shape.centerHoleSize, + gearType: shape.gearType, + helixAngle: shape.helixAngle, + helixQuality: shape.helixQuality, + }); + break; + case "sketch": + default: + geom = new THREE.BoxGeometry(width, height, depth); + geom.translate(0, height / 2, 0); + break; + } + + return geom ? ensureNonIndexedPosNormal(geom) : null; +} + +function applyShapeWorldTransform(geometry: THREE.BufferGeometry, shape: WorkplaneShape): THREE.BufferGeometry { + const nonIndexed = ensureNonIndexedPosNormal(geometry); + const posAttr = nonIndexed.getAttribute("position"); + if (!posAttr) { + return nonIndexed; + } + + const centerY = shape.height / 2; + const tapered = shapeHasTaper(shape); + let minLocalY = 0; + let maxLocalY = 1; + if (tapered && posAttr.count > 0) { + minLocalY = Infinity; + maxLocalY = -Infinity; + for (let i = 0; i < posAttr.count; i++) { + const y = posAttr.getY(i); + if (y < minLocalY) minLocalY = y; + if (y > maxLocalY) maxLocalY = y; + } + } + const taperHeight = Math.max(1e-6, maxLocalY - minLocalY); + + const rotMatrix = new THREE.Matrix4().makeRotationFromEuler( + new THREE.Euler( + THREE.MathUtils.degToRad(shape.rotationX ?? 0), + THREE.MathUtils.degToRad(meshYawDegrees(shape)), + THREE.MathUtils.degToRad(shape.rotationZ ?? 0), + "XYZ", + ), + ); + + const mx = mirrorSign(shape.mirrorX); + const my = mirrorSign(shape.mirrorY); + const mz = mirrorSign(shape.mirrorZ); + const reverseWinding = mirroredAxisCount(shape) % 2 === 1; + const vec = new THREE.Vector3(); + + for (let i = 0; i < posAttr.count; i++) { + const x = posAttr.getX(i); + const y = posAttr.getY(i); + const z = posAttr.getZ(i); + const normH = (y - minLocalY) / taperHeight; + const widthScale = tapered ? shapeTaperScaleAt(shape, normH, "width") : 1; + const depthScale = tapered ? shapeTaperScaleAt(shape, normH, "depth") : 1; + vec.set(x * widthScale * mx, (y - centerY) * my, z * depthScale * mz).applyMatrix4(rotMatrix); + posAttr.setXYZ(i, vec.x + shape.x, vec.y + (shape.elevation ?? 0) + centerY, vec.z + shape.z); + } + + if (reverseWinding) { + for (let i = 0; i + 2 < posAttr.count; i += 3) { + const bx = posAttr.getX(i + 1); + const by = posAttr.getY(i + 1); + const bz = posAttr.getZ(i + 1); + posAttr.setXYZ(i + 1, posAttr.getX(i + 2), posAttr.getY(i + 2), posAttr.getZ(i + 2)); + posAttr.setXYZ(i + 2, bx, by, bz); + } + } + + posAttr.needsUpdate = true; + nonIndexed.computeVertexNormals(); + nonIndexed.computeBoundingBox(); + nonIndexed.computeBoundingSphere(); + return nonIndexed; +} + +function padCutterShape(shape: WorkplaneShape): WorkplaneShape { + const width = shapeWidth(shape) + CUTTER_PAD * 2; + const depth = shapeDepth(shape) + CUTTER_PAD * 2; + const height = shape.height + CUTTER_PAD * 2; + return { + ...shape, + width, + depth, + height, + size: Math.max(width, depth), + elevation: (shape.elevation ?? 0) - CUTTER_PAD, + baseRadius: shape.baseRadius ? shape.baseRadius + CUTTER_PAD : shape.baseRadius, + }; +} + +function geometryTriangleCount(geometry: THREE.BufferGeometry): number { + const count = geometry.index ? geometry.index.count : geometry.getAttribute("position")?.count ?? 0; + return Math.floor(count / 3); +} + +function boxesOverlap(a: THREE.Box3, b: THREE.Box3): boolean { + return ( + Math.min(a.max.x, b.max.x) > Math.max(a.min.x, b.min.x) - 0.001 && + Math.min(a.max.y, b.max.y) > Math.max(a.min.y, b.min.y) - 0.001 && + Math.min(a.max.z, b.max.z) > Math.max(a.min.z, b.min.z) - 0.001 + ); +} + +function createCsgEvaluator(): Evaluator { + const evaluator = new Evaluator(); + evaluator.useGroups = false; + evaluator.attributes = ["position", "normal"]; + (evaluator as Evaluator & { useCDTClipping?: boolean }).useCDTClipping = true; + return evaluator; +} + +function hasPositiveGeometryVolume(geometry: THREE.BufferGeometry): boolean { + const posAttr = geometry.getAttribute("position"); + if (!posAttr || posAttr.count < 12) { + return false; + } + geometry.computeBoundingBox(); + const box = geometry.boundingBox; + if (!box) { + return false; + } + const size = new THREE.Vector3(); + box.getSize(size); + return size.x > 0.01 && size.y > 0.01 && size.z > 0.01; +} + +export function buildGeometryForWorkplaneShape( + shape: WorkplaneShape, + options: { radialSegments?: number } = {}, +): THREE.BufferGeometry | null { + if (shape.hidden) { + return null; + } + const radialSegments = options.radialSegments ?? 32; + + if (shape.kind === "mesh" && shape.importedMesh) { + const pos = resizedImportedMeshPositions(shape); + const geom = geometryFromCleanPositions(pos); + return geom ? applyShapeWorldTransform(geom, shape) : null; + } + + if (shape.groupedShapes && shape.groupedShapes.length > 0) { + const childGeoms = buildCompoundSolidGeometries(shape.groupedShapes, radialSegments); + const merged = mergeGeometriesPosNormal(childGeoms.solidGeometries); + childGeoms.solidGeometries.forEach((g) => g.dispose()); + return merged ? applyShapeWorldTransform(merged, shape) : null; + } + + const localGeom = buildLocalPrimitiveGeometry(shape, radialSegments); + return localGeom ? applyShapeWorldTransform(localGeom, shape) : null; +} + +export function buildCompoundSolidGeometries( + shapes: WorkplaneShape[], + radialSegments = 32, +): { solidGeometries: THREE.BufferGeometry[]; triangleCount: number; csgApplied: boolean } { + const active = shapes.filter((s) => !s.hidden); + const solids = active.filter((s) => !s.hole); + const holes = active.filter((s) => s.hole); + + const solidGeoms: THREE.BufferGeometry[] = []; + for (const solid of solids) { + const g = buildGeometryForWorkplaneShape(solid, { radialSegments }); + if (g) { + solidGeoms.push(g); + } + } + + if (solidGeoms.length === 0) { + return { solidGeometries: [], triangleCount: 0, csgApplied: false }; + } + + const holeGeoms: THREE.BufferGeometry[] = []; + for (const hole of holes) { + const g = buildGeometryForWorkplaneShape(padCutterShape(hole), { radialSegments }); + if (g) { + holeGeoms.push(g); + } + } + + const totalTris = + solidGeoms.reduce((sum, g) => sum + geometryTriangleCount(g), 0) + + holeGeoms.reduce((sum, g) => sum + geometryTriangleCount(g), 0); + + if (holeGeoms.length === 0 || totalTris > MAX_CSG_TRIANGLES) { + holeGeoms.forEach((g) => g.dispose()); + return { + solidGeometries: solidGeoms, + triangleCount: solidGeoms.reduce((sum, g) => sum + geometryTriangleCount(g), 0), + csgApplied: false, + }; + } + + // Merge solids together if multiple solids touch/overlap so CSG produces a single unified B-rep without interior seams + const evaluator = createCsgEvaluator(); + let workingResult: THREE.BufferGeometry | null = null; + let csgApplied = false; + + try { + let unionBrush: Brush; + if (solidGeoms.length === 1) { + unionBrush = new Brush(ensureNonIndexedPosNormal(solidGeoms[0].clone())); + unionBrush.updateMatrixWorld(true); + } else { + unionBrush = new Brush(ensureNonIndexedPosNormal(solidGeoms[0].clone())); + unionBrush.updateMatrixWorld(true); + for (let i = 1; i < solidGeoms.length; i++) { + const nextBrush = new Brush(ensureNonIndexedPosNormal(solidGeoms[i].clone())); + nextBrush.updateMatrixWorld(true); + const res = evaluator.evaluate(unionBrush, nextBrush, ADDITION); + res.updateMatrixWorld(true); + unionBrush.geometry.dispose(); + nextBrush.geometry.dispose(); + unionBrush = res; + } + csgApplied = true; + } + + unionBrush.geometry.computeBoundingBox(); + const unionBox = unionBrush.geometry.boundingBox ?? new THREE.Box3(); + + for (const hGeom of holeGeoms) { + hGeom.computeBoundingBox(); + const holeBox = hGeom.boundingBox; + if (holeBox && !boxesOverlap(unionBox, holeBox)) { + continue; + } + const cutterBrush = new Brush(ensureNonIndexedPosNormal(hGeom.clone())); + cutterBrush.updateMatrixWorld(true); + let nextBrush = evaluator.evaluate(unionBrush, cutterBrush, SUBTRACTION); + if (!hasPositiveGeometryVolume(nextBrush.geometry)) { + nextBrush.geometry.dispose(); + nextBrush = evaluator.evaluate(unionBrush, cutterBrush, HOLLOW_SUBTRACTION); + } + if (hasPositiveGeometryVolume(nextBrush.geometry)) { + unionBrush.geometry.dispose(); + nextBrush.updateMatrixWorld(true); + unionBrush = nextBrush; + csgApplied = true; + } else { + nextBrush.geometry.dispose(); + } + cutterBrush.geometry.dispose(); + } + + if (hasPositiveGeometryVolume(unionBrush.geometry)) { + workingResult = ensureNonIndexedPosNormal(unionBrush.geometry); + } else { + unionBrush.geometry.dispose(); + } + } catch { + if (workingResult) { + workingResult.dispose(); + workingResult = null; + } + } finally { + holeGeoms.forEach((g) => g.dispose()); + } + + if (workingResult) { + solidGeoms.forEach((g) => g.dispose()); + return { + solidGeometries: [workingResult], + triangleCount: geometryTriangleCount(workingResult), + csgApplied, + }; + } + + return { + solidGeometries: solidGeoms, + triangleCount: solidGeoms.reduce((sum, g) => sum + geometryTriangleCount(g), 0), + csgApplied: false, + }; +} + +export function getViewOrientationMatrix( + view: ProjectedViewKind, + center: { cx: number; cy: number; cz: number }, +): THREE.Matrix4 { + const translate = new THREE.Matrix4().makeTranslation(-center.cx, -center.cy, -center.cz); + const rot = new THREE.Matrix4(); + + if (view === "top") { + return translate; + } + + if (view === "front") { + // Rotate -90 deg around X: (x, y, z) -> (x, z, -y) + // Projection along -Y looks from +Z toward -Z; screen +u = +X, SVG +v = -Y + rot.set( + 1, 0, 0, 0, + 0, 0, 1, 0, + 0, -1, 0, 0, + 0, 0, 0, 1, + ); + } else if (view === "side") { + // Left view: look from -X toward +X; screen +u = +Z, SVG +v = -Y + // (x, y, z) -> (z, -x, -y) [right-handed, det = +1] + rot.set( + 0, 0, 1, 0, + -1, 0, 0, 0, + 0, -1, 0, 0, + 0, 0, 0, 1, + ); + } else { + // Isometric view looking along normalize(1, 1, 1) -> Y' + const invSqrt2 = Math.SQRT1_2; + const invSqrt3 = 1 / Math.sqrt(3); + const invSqrt6 = 1 / Math.sqrt(6); + rot.set( + invSqrt2, 0, -invSqrt2, 0, + invSqrt3, invSqrt3, invSqrt3, 0, + invSqrt6, -2 * invSqrt6, invSqrt6, 0, + 0, 0, 0, 1, + ); + } + + return rot.multiply(translate); +} + +function segmentArrayToNormalized2D(segments: Float32Array[]): NormalizedSegment2D[] { + const out: NormalizedSegment2D[] = []; + const seen = new Set(); + + for (let i = 0; i < segments.length; i++) { + const s = segments[i]; + const x1 = s[0]; + const y1 = s[2]; + const x2 = s[3]; + const y2 = s[5]; + if (Math.hypot(x2 - x1, y2 - y1) < 1e-3) { + continue; + } + + // Order endpoints canonically to suppress exact bidirectional duplicates + const kA = `${Math.round(x1 * 100)},${Math.round(y1 * 100)}`; + const kB = `${Math.round(x2 * 100)},${Math.round(y2 * 100)}`; + const key = kA <= kB ? `${kA}|${kB}` : `${kB}|${kA}`; + if (seen.has(key)) { + continue; + } + seen.add(key); + + out.push({ x1, y1, x2, y2 }); + } + + return out; +} + +function sliceBehindSectionPlane( + geometries: THREE.BufferGeometry[], + orientedFrontMatrix: THREE.Matrix4, +): THREE.BufferGeometry[] { + // In oriented Front space, Y' > 0 is in front of Z = czModel, Y' <= 0 is behind the section plane + const orientedGeoms = geometries.map((g) => { + const copy = g.clone(); + copy.applyMatrix4(orientedFrontMatrix); + copy.computeVertexNormals(); + copy.computeBoundingBox(); + return copy; + }); + + const bounds = new THREE.Box3(); + orientedGeoms.forEach((g) => { + if (g.boundingBox) bounds.union(g.boundingBox); + }); + + if (bounds.isEmpty() || bounds.min.y >= -0.001) { + return orientedGeoms; + } + + const size = new THREE.Vector3(); + bounds.getSize(size); + const pad = Math.max(20, size.length()); + const minY = bounds.min.y - pad; + const maxY = 1e-4; // tiny positive epsilon avoids vertex-on-plane degeneracy + const slabH = Math.max(0.1, maxY - minY); + + const halfSpaceGeom = new THREE.BoxGeometry(size.x + pad * 2, slabH, size.z + pad * 2); + halfSpaceGeom.translate((bounds.min.x + bounds.max.x) / 2, minY + slabH / 2, (bounds.min.z + bounds.max.z) / 2); + const halfSpaceBrush = new Brush(ensureNonIndexedPosNormal(halfSpaceGeom)); + halfSpaceBrush.updateMatrixWorld(true); + + const evaluator = createCsgEvaluator(); + const sliced: THREE.BufferGeometry[] = []; + + for (const geom of orientedGeoms) { + try { + if ((geom.boundingBox?.max.y ?? 0) <= 0.001) { + sliced.push(geom); + continue; + } + const partBrush = new Brush(ensureNonIndexedPosNormal(geom.clone())); + partBrush.updateMatrixWorld(true); + const res = evaluator.evaluate(partBrush, halfSpaceBrush, INTERSECTION); + partBrush.geometry.dispose(); + if (hasPositiveGeometryVolume(res.geometry)) { + sliced.push(ensureNonIndexedPosNormal(res.geometry)); + geom.dispose(); + } else { + res.geometry.dispose(); + sliced.push(geom); + } + } catch { + sliced.push(geom); + } + } + + halfSpaceBrush.geometry.dispose(); + return sliced; +} + +function projectSectionCutSegments(orientedGeometries: THREE.BufferGeometry[]): NormalizedSegment2D[] { + const generator = new PlanarIntersectionGenerator(); + generator.plane.set(new THREE.Vector3(0, 1, 0), 1e-4); + + const segments: NormalizedSegment2D[] = []; + const seen = new Set(); + + for (const geom of orientedGeometries) { + const lineGeom = generator.generate(geom); + const pos = lineGeom.getAttribute("position"); + if (pos) { + for (let i = 0; i + 1 < pos.count; i += 2) { + const x1 = pos.getX(i); + const y1 = pos.getZ(i); + const x2 = pos.getX(i + 1); + const y2 = pos.getZ(i + 1); + if (Math.hypot(x2 - x1, y2 - y1) < 1e-3) { + continue; + } + const kA = `${Math.round(x1 * 100)},${Math.round(y1 * 100)}`; + const kB = `${Math.round(x2 * 100)},${Math.round(y2 * 100)}`; + const key = kA <= kB ? `${kA}|${kB}` : `${kB}|${kA}`; + if (seen.has(key)) { + continue; + } + seen.add(key); + segments.push({ x1, y1, x2, y2 }); + } + } + lineGeom.dispose(); + } + + return segments; +} + +function projectOrientedGeometriesSync( + orientedGeometries: THREE.BufferGeometry[], + angleThreshold = 28, +): { visible: NormalizedSegment2D[]; hidden: NormalizedSegment2D[] } { + const group = new THREE.Group(); + const mat = new THREE.MeshBasicMaterial(); + for (const geom of orientedGeometries) { + group.add(new THREE.Mesh(geom, mat)); + } + group.updateMatrixWorld(true); + + const projector = new ProjectionGenerator(); + projector.angleThreshold = angleThreshold; + projector.includeIntersectionEdges = true; + const res = projector.generateSync(group); + + mat.dispose(); + return { + visible: segmentArrayToNormalized2D(res.visibleEdges.getAllSegments()), + hidden: segmentArrayToNormalized2D(res.hiddenEdges.getAllSegments()), + }; +} + +async function projectOrientedGeometriesAsync( + orientedGeometries: THREE.BufferGeometry[], + angleThreshold = 28, + signal?: AbortSignal, +): Promise<{ visible: NormalizedSegment2D[]; hidden: NormalizedSegment2D[] }> { + const group = new THREE.Group(); + const mat = new THREE.MeshBasicMaterial(); + for (const geom of orientedGeometries) { + group.add(new THREE.Mesh(geom, mat)); + } + group.updateMatrixWorld(true); + + const projector = new ProjectionGenerator(); + projector.angleThreshold = angleThreshold; + projector.includeIntersectionEdges = true; + projector.iterationTime = 24; + const res = await projector.generateAsync(group, { signal }); + + mat.dispose(); + return { + visible: segmentArrayToNormalized2D(res.visibleEdges.getAllSegments()), + hidden: segmentArrayToNormalized2D(res.hiddenEdges.getAllSegments()), + }; +} + +/** + * Generates exact 45-degree ISO 128 section hatch lines across arbitrary closed + * cross-section contours using the half-open even-odd parity rule. + */ +export function generateSectionHatchSegments( + sectionSegments: NormalizedSegment2D[], + spacing = 8, +): Array<{ x1: number; y1: number; x2: number; y2: number }> { + if (sectionSegments.length < 3) { + return []; + } + + let minC = Infinity; + let maxC = -Infinity; + for (const seg of sectionSegments) { + const c1 = seg.y1 - seg.x1; + const c2 = seg.y2 - seg.x2; + if (c1 < minC) minC = c1; + if (c2 < minC) minC = c2; + if (c1 > maxC) maxC = c1; + if (c2 > maxC) maxC = c2; + } + + if (!Number.isFinite(minC) || !Number.isFinite(maxC) || maxC - minC < spacing) { + return []; + } + + const hatchLines: Array<{ x1: number; y1: number; x2: number; y2: number }> = []; + const startC = Math.floor(minC / spacing) * spacing + spacing * 0.5; + + for (let c = startC; c < maxC; c += spacing) { + const xHits: number[] = []; + for (const seg of sectionSegments) { + const d1 = seg.y1 - seg.x1 - c; + const d2 = seg.y2 - seg.x2 - c; + // Half-open crossing test so vertices shared by consecutive segments count exactly once + if ((d1 >= 0 && d2 < 0) || (d2 >= 0 && d1 < 0)) { + const t = d1 / (d1 - d2); + const hitX = seg.x1 + (seg.x2 - seg.x1) * t; + xHits.push(hitX); + } + } + + if (xHits.length < 2) { + continue; + } + + xHits.sort((a, b) => a - b); + for (let i = 0; i + 1 < xHits.length; i += 2) { + const xStart = xHits[i]; + const xEnd = xHits[i + 1]; + if (xEnd - xStart > 0.75) { + hatchLines.push({ + x1: xStart, + y1: xStart + c, + x2: xEnd, + y2: xEnd + c, + }); + } + } + } + + return hatchLines; +} + +function computeCompoundBounds(geometries: THREE.BufferGeometry[]) { + const box = new THREE.Box3(); + for (const geom of geometries) { + geom.computeBoundingBox(); + if (geom.boundingBox) { + box.union(geom.boundingBox); + } + } + if (box.isEmpty()) { + return { minX: -50, maxX: 50, minY: 0, maxY: 40, minZ: -30, maxZ: 30 }; + } + return { + minX: box.min.x, + maxX: box.max.x, + minY: box.min.y, + maxY: box.max.y, + minZ: box.min.z, + maxZ: box.max.z, + }; +} + +export function buildAnalyticFallbackProjection(shapes: WorkplaneShape[]): ModelProjectionCache { + const solidGeoms: THREE.BufferGeometry[] = []; + for (const s of shapes) { + if (!s.hidden) { + const g = buildGeometryForWorkplaneShape(s, { radialSegments: 16 }); + if (g) solidGeoms.push(g); + } + } + const bounds = computeCompoundBounds(solidGeoms); + const cx = (bounds.minX + bounds.maxX) / 2; + const cy = (bounds.minY + bounds.maxY) / 2; + const cz = (bounds.minZ + bounds.maxZ) / 2; + + const emptyView = (): NormalizedViewProjection => ({ visible: [], hidden: [], sectionCut: [] }); + const views: Record = { + front: emptyView(), + top: emptyView(), + side: emptyView(), + isometric: emptyView(), + }; + + for (const viewKey of ["front", "top", "side", "isometric"] as const) { + const m = getViewOrientationMatrix(viewKey, { cx, cy, cz }); + for (const s of shapes) { + if (s.hidden) continue; + const g = buildGeometryForWorkplaneShape(s, { radialSegments: 16 }); + if (!g) continue; + g.applyMatrix4(m); + const edgesGeom = new THREE.EdgesGeometry(g, 28); + const pos = edgesGeom.getAttribute("position"); + const target = s.hole ? views[viewKey].hidden : views[viewKey].visible; + if (pos) { + for (let i = 0; i + 1 < pos.count; i += 2) { + target.push({ + x1: pos.getX(i), + y1: pos.getZ(i), + x2: pos.getX(i + 1), + y2: pos.getZ(i + 1), + }); + } + } + edgesGeom.dispose(); + g.dispose(); + } + } + + solidGeoms.forEach((g) => g.dispose()); + return { + center: { cx, cy, cz }, + bounds, + views, + csgApplied: false, + triangleCount: 0, + }; +} + +export function computeModelProjectionSync( + shapes: WorkplaneShape[], + options: { sectionAAEnabled?: boolean; radialSegments?: number } = {}, +): ModelProjectionCache { + const sectionAAEnabled = options.sectionAAEnabled ?? true; + const radialSegments = options.radialSegments ?? 28; + const { solidGeometries, triangleCount, csgApplied } = buildCompoundSolidGeometries(shapes, radialSegments); + + if (solidGeometries.length === 0 || triangleCount > MAX_HLR_TRIANGLES) { + solidGeometries.forEach((g) => g.dispose()); + return buildAnalyticFallbackProjection(shapes); + } + + const bounds = computeCompoundBounds(solidGeometries); + const center = { + cx: (bounds.minX + bounds.maxX) / 2, + cy: (bounds.minY + bounds.maxY) / 2, + cz: (bounds.minZ + bounds.maxZ) / 2, + }; + + const views = {} as Record; + + try { + // 1. Front View (or A-A Cutaway Section + Planar Cut Contours) + const frontMat = getViewOrientationMatrix("front", center); + const fullFrontGeoms = solidGeometries.map((g) => { + const c = g.clone(); + c.applyMatrix4(frontMat); + return c; + }); + const sectionCut = sectionAAEnabled ? projectSectionCutSegments(fullFrontGeoms) : []; + + if (sectionAAEnabled && sectionCut.length > 0) { + fullFrontGeoms.forEach((g) => g.dispose()); + const slicedGeoms = sliceBehindSectionPlane(solidGeometries, frontMat); + const projected = projectOrientedGeometriesSync(slicedGeoms, 28); + slicedGeoms.forEach((g) => g.dispose()); + views.front = { + visible: projected.visible, + hidden: [], // ISO 128 omits redundant hidden lines in full section views + sectionCut, + }; + } else { + const projected = projectOrientedGeometriesSync(fullFrontGeoms, 28); + fullFrontGeoms.forEach((g) => g.dispose()); + views.front = { + visible: projected.visible, + hidden: projected.hidden, + sectionCut: [], + }; + } + + // 2. Top View, Side View, Isometric View + for (const viewKey of ["top", "side", "isometric"] as const) { + const mat = getViewOrientationMatrix(viewKey, center); + const oriented = solidGeometries.map((g) => { + const c = g.clone(); + c.applyMatrix4(mat); + return c; + }); + const projected = projectOrientedGeometriesSync(oriented, 28); + oriented.forEach((g) => g.dispose()); + views[viewKey] = { + visible: projected.visible, + hidden: viewKey === "isometric" ? [] : projected.hidden, + sectionCut: [], + }; + } + } finally { + solidGeometries.forEach((g) => g.dispose()); + } + + return { center, bounds, views, csgApplied, triangleCount }; +} + +export async function computeModelProjectionAsync( + shapes: WorkplaneShape[], + options: { sectionAAEnabled?: boolean; radialSegments?: number; signal?: AbortSignal } = {}, +): Promise { + const { signal } = options; + const sectionAAEnabled = options.sectionAAEnabled ?? true; + const radialSegments = options.radialSegments ?? 28; + const { solidGeometries, triangleCount, csgApplied } = buildCompoundSolidGeometries(shapes, radialSegments); + + if (solidGeometries.length === 0 || triangleCount > MAX_HLR_TRIANGLES) { + solidGeometries.forEach((g) => g.dispose()); + return buildAnalyticFallbackProjection(shapes); + } + + const bounds = computeCompoundBounds(solidGeometries); + const center = { + cx: (bounds.minX + bounds.maxX) / 2, + cy: (bounds.minY + bounds.maxY) / 2, + cz: (bounds.minZ + bounds.maxZ) / 2, + }; + + const views = {} as Record; + + try { + signal?.throwIfAborted(); + + const frontMat = getViewOrientationMatrix("front", center); + const fullFrontGeoms = solidGeometries.map((g) => { + const c = g.clone(); + c.applyMatrix4(frontMat); + return c; + }); + const sectionCut = sectionAAEnabled ? projectSectionCutSegments(fullFrontGeoms) : []; + + if (sectionAAEnabled && sectionCut.length > 0) { + fullFrontGeoms.forEach((g) => g.dispose()); + const slicedGeoms = sliceBehindSectionPlane(solidGeometries, frontMat); + const projected = await projectOrientedGeometriesAsync(slicedGeoms, 28, signal); + slicedGeoms.forEach((g) => g.dispose()); + views.front = { + visible: projected.visible, + hidden: [], + sectionCut, + }; + } else { + const projected = await projectOrientedGeometriesAsync(fullFrontGeoms, 28, signal); + fullFrontGeoms.forEach((g) => g.dispose()); + views.front = { + visible: projected.visible, + hidden: projected.hidden, + sectionCut: [], + }; + } + + for (const viewKey of ["top", "side", "isometric"] as const) { + signal?.throwIfAborted(); + const mat = getViewOrientationMatrix(viewKey, center); + const oriented = solidGeometries.map((g) => { + const c = g.clone(); + c.applyMatrix4(mat); + return c; + }); + const projected = await projectOrientedGeometriesAsync(oriented, 28, signal); + oriented.forEach((g) => g.dispose()); + views[viewKey] = { + visible: projected.visible, + hidden: viewKey === "isometric" ? [] : projected.hidden, + sectionCut: [], + }; + } + } finally { + solidGeometries.forEach((g) => g.dispose()); + } + + return { center, bounds, views, csgApplied, triangleCount }; +} + +export function mapProjectionSegmentsToSheet( + projection: NormalizedViewProjection, + origin: { x: number; y: number }, + scale: number, + options: { isIsometric?: boolean; includeHidden?: boolean; includeSectionHatch?: boolean } = {}, +): ProjectedPrimitive2D[] { + const effectiveScale = options.isIsometric ? scale * 0.72 * Math.sqrt(1.5) : scale; + const out: ProjectedPrimitive2D[] = []; + + if (options.includeHidden !== false) { + for (const seg of projection.hidden) { + out.push({ + kind: "line", + layer: "HIDDEN", + x: origin.x + seg.x1 * effectiveScale, + y: origin.y + seg.y1 * effectiveScale, + x2: origin.x + seg.x2 * effectiveScale, + y2: origin.y + seg.y2 * effectiveScale, + }); + } + } + + for (const seg of projection.visible) { + out.push({ + kind: "line", + layer: "VISIBLE", + x: origin.x + seg.x1 * effectiveScale, + y: origin.y + seg.y1 * effectiveScale, + x2: origin.x + seg.x2 * effectiveScale, + y2: origin.y + seg.y2 * effectiveScale, + }); + } + + if (options.includeSectionHatch && projection.sectionCut.length > 0) { + const scaledSectionSegs = projection.sectionCut.map((seg) => ({ + x1: origin.x + seg.x1 * effectiveScale, + y1: origin.y + seg.y1 * effectiveScale, + x2: origin.x + seg.x2 * effectiveScale, + y2: origin.y + seg.y2 * effectiveScale, + })); + + for (const seg of scaledSectionSegs) { + out.push({ + kind: "line", + layer: "VISIBLE", + x: seg.x1, + y: seg.y1, + x2: seg.x2, + y2: seg.y2, + }); + } + + const hatchLines = generateSectionHatchSegments(scaledSectionSegs, 8.5); + for (const h of hatchLines) { + out.push({ + kind: "line", + layer: "HATCH", + x: h.x1, + y: h.y1, + x2: h.x2, + y2: h.y2, + }); + } + } + + return out; +} diff --git a/apps/web/src/types/desktop.d.ts b/apps/web/src/types/desktop.d.ts index fb787b1..2f98660 100644 --- a/apps/web/src/types/desktop.d.ts +++ b/apps/web/src/types/desktop.d.ts @@ -1,20 +1,289 @@ export {}; -type SketchForgeDesktopUpdateResult = { +export type DesktopUpdateLifecycle = + | "idle" + | "checking" + | "available" + | "not-available" + | "downloading" + | "downloaded" + | "error" + | "unsupported"; + +export type DesktopUpdateResult = { currentVersion: string; latestVersion: string | null; updateAvailable: boolean; downloaded: boolean; checkedAt: string; + status?: DesktopUpdateLifecycle; + progressPercent?: number; + bytesPerSecond?: number; + transferred?: number; + total?: number; + feedUrl?: string; error?: string; }; +export type DesktopPreferences = { + closeToTray: boolean; +}; + +export type DesktopYakNetUser = { + id: number; + name: string; + email: string; + avatar?: string | null; + auth_source?: string; + token_expires_at?: string; +}; + +export type DesktopYakNetAuthEvent = { + authenticated: boolean; + pending?: boolean; + user?: DesktopYakNetUser | null; + cloudLoginCompleted?: boolean; + loggedOut?: boolean; + error?: string; +}; + +export type DesktopCloudRequestOptions = { + path: string; + method?: string; + headers?: Record; + body?: string; +}; + +export type DesktopCloudResponse = { + ok: boolean; + status: number; + bodyText: string; + contentType?: string; + error?: string; +}; + +export type DesktopMenuAction = + | "file:new" + | "file:open" + | "file:save" + | "file:save-as" + | "file:save-and-quit" + | "file:import" + | "file:export-panel" + | "file:export-skf" + | "file:export-stl" + | "file:export-3mf" + | "file:export-step" + | "file:export-obj" + | "file:export-glb" + | "file:export-dxf" + | "file:export-svg" + | "file:dashboard" + | "edit:undo" + | "edit:redo" + | "edit:cut" + | "edit:copy" + | "edit:paste" + | "edit:duplicate" + | "edit:delete" + | "edit:select-all" + | "edit:clear-selection" + | "edit:make-component" + | "edit:make-unique" + | "edit:group" + | "edit:ungroup" + | "edit:intersect" + | "edit:make-solid" + | "edit:make-hole" + | "edit:mirror" + | "edit:align" + | "edit:drop-to-workplane" + | "edit:snap-to-grid" + | "edit:chamfer" + | "edit:fillet" + | "edit:hide" + | "edit:show-hidden" + | "edit:lock" + | "view:toggle-left-toolset" + | "view:toggle-tray" + | "view:toggle-secondary-ribbon" + | "view:sky-ground" + | "view:back-edges" + | "view:xray" + | "view:style-shaded" + | "view:style-monochrome" + | "view:style-hidden-line" + | "view:style-wireframe" + | "view:style-blueprint" + | "view:style-clay" + | "view:style-cyberpunk" + | "view:layers" + | "view:solar" + | "view:clear-guides" + | "view:zoom-extents" + | "view:reset-camera" + | "view:toggle-projection" + | "camera:isometric" + | "camera:top" + | "camera:bottom" + | "camera:front" + | "camera:back" + | "camera:left" + | "camera:right" + | "camera:two-point" + | "camera:zoom-selection" + | "camera:previous" + | "draw:shape-box" + | "draw:shape-cylinder" + | "draw:shape-sphere" + | "draw:shape-cone" + | "draw:shape-pyramid" + | "draw:shape-wedge" + | "draw:shape-round-roof" + | "draw:shape-half-sphere" + | "draw:shape-torus" + | "draw:shape-tube" + | "draw:shape-gear" + | "draw:sketch-extrude" + | "draw:sketch-revolve" + | "draw:sketch-edit" + | "draw:house-scene" + | "tool:select" + | "tool:eraser" + | "tool:paint" + | "tool:line" + | "tool:freehand" + | "tool:arc" + | "tool:rectangle" + | "tool:circle" + | "tool:polygon" + | "tool:3d-text" + | "tool:move" + | "tool:push-pull" + | "tool:rotate" + | "tool:scale" + | "tool:offset" + | "tool:follow-me" + | "tool:tape" + | "tool:protractor" + | "tool:axes" + | "tool:section" + | "tool:orbit" + | "tool:pan" + | "tool:zoom" + | "tool:walk" + | "tool:wall-opening" + | "tool:terrain" + | "tool:structural-test" + | "tool:ar-preview" + | "tool:physics-toggle" + | "tool:physics-reset" + | "tray:entity-info" + | "tray:outliner" + | "tray:components" + | "tray:materials" + | "tray:styles" + | "tray:tags" + | "tray:shadows" + | "tray:scenes" + | "tray:instructor" + | "window:drawing" + | "window:circuits" + | "window:codeblocks" + | "window:classrooms" + | "window:shared" + | "window:challenges" + | "window:customization" + | "window:about" + | "window:contact" + | "window:kvkk" + | "window:terms" + | "window:security" + | "window:keymap-classic" + | "window:keymap-standard" + | "window:command-palette" + | "window:a11y" + | "window:workspace-settings" + | "window:settings" + | "help:audit" + | "help:voice" + | "help:radar" + | "help:shortcuts" + | "help:tutorial" + | "help:daily-challenges"; + +export type DesktopMenuUiState = { + inEditor: boolean; + visualStyle: "shaded" | "wireframe" | "hidden-line" | "monochrome" | "blueprint" | "cyberpunk" | "clay"; + xRayMode: boolean; + isOrthographic: boolean; + showLeftToolset: boolean; + showDefaultTray: boolean; + showSecondaryRibbon: boolean; + skyGroundEnabled: boolean; + backEdgesEnabled: boolean; + keymapProfile: "classic-sketchup" | "snapcad-standard"; +}; + +export type DesktopOpenedFile = { + filePath: string; + fileName: string; + bytes: Uint8Array; +}; + +export type DesktopSaveFilter = { + name: string; + extensions: string[]; +}; + +export type DesktopSavedFileResult = { + canceled: boolean; + filePath?: string; + fileName?: string; + error?: string; +}; + +export type SnapCadDesktopBridge = { + isDesktop?: boolean; + platform?: string; + getVersion: () => Promise; + checkForUpdates: () => Promise; + installUpdate: () => Promise; + getUpdateState?: () => Promise; + onUpdateState?: (listener: (state: DesktopUpdateResult) => void) => () => void; + getDesktopPrefs?: () => Promise; + setDesktopPrefs?: (patch: Partial) => Promise; + hideToTray?: () => Promise; + onDesktopPrefsChanged?: (listener: (prefs: DesktopPreferences) => void) => () => void; + startYakNetLogin?: () => Promise<{ started: boolean; error?: string }>; + logoutYakNet?: () => Promise<{ ok: boolean; error?: string }>; + cloudRequest?: (options: DesktopCloudRequestOptions) => Promise; + onAuthUpdated?: (listener: (event: DesktopYakNetAuthEvent) => void) => () => void; + openSkfDialog?: () => Promise; + saveSkfDialog?: (options: { + defaultFileName?: string; + targetPath?: string | null; + forceDialog?: boolean; + bytes: Uint8Array; + }) => Promise; + saveExportFileDialog?: (options: { + defaultFileName: string; + bytes: Uint8Array; + filters?: DesktopSaveFilter[]; + }) => Promise; + consumePendingOpenFile?: () => Promise; + onOpenFile?: (listener: (file: DesktopOpenedFile) => void) => () => void; + onMenuCommand?: (listener: (action: DesktopMenuAction) => void) => () => void; + setMenuState?: (state: Partial) => Promise; + setDirty?: (dirty: boolean) => Promise; + setWindowTitle?: (title: string) => Promise; + confirmCloseAfterSave?: () => Promise; + openExternal?: (url: string) => Promise; +}; + declare global { interface Window { - sketchforgeDesktop?: { - getVersion: () => Promise; - checkForUpdates: () => Promise; - installUpdate: () => Promise; - }; + snapcadDesktop?: SnapCadDesktopBridge; + sketchforgeDesktop?: SnapCadDesktopBridge; } } diff --git a/apps/web/src/types/sketchforge.ts b/apps/web/src/types/sketchforge.ts index c1149d7..418d3b5 100644 --- a/apps/web/src/types/sketchforge.ts +++ b/apps/web/src/types/sketchforge.ts @@ -28,7 +28,7 @@ export type ShapeAsset = { hole?: boolean; }; -export type ProjectAssetSourceFormat = "stl" | "obj" | "svg" | "step" | "dxf" | "glb" | "dwg"; +export type ProjectAssetSourceFormat = "stl" | "obj" | "svg" | "step" | "dxf" | "glb" | "dwg" | "ifc"; export type ProjectAsset = { id: string; diff --git a/callback.php b/callback.php index 412160d..d441b47 100644 --- a/callback.php +++ b/callback.php @@ -7,18 +7,46 @@ require_once __DIR__ . '/snap-config.php'; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +$desktopCtx = $_SESSION['oauth2_desktop'] ?? null; +unset($_SESSION['oauth2_desktop']); + +$desktopPort = 0; +$desktopNonce = ''; +$desktopDevice = 'SnapCAD Masaüstü'; +if ( + is_array($desktopCtx) + && !empty($desktopCtx['port']) + && !empty($desktopCtx['nonce']) + && ((int)($desktopCtx['issued_at'] ?? 0) <= 0 || (time() - (int)$desktopCtx['issued_at']) <= 900) +) { + $candidatePort = (int)$desktopCtx['port']; + $candidateNonce = strtolower(trim((string)$desktopCtx['nonce'])); + if ($candidatePort >= 1024 && $candidatePort <= 65535 && preg_match('/^[a-f0-9]{32,128}$/', $candidateNonce)) { + $desktopPort = $candidatePort; + $desktopNonce = $candidateNonce; + $desktopDevice = (string)($desktopCtx['device'] ?? 'SnapCAD Masaüstü'); + } +} + +$redirectCallbackError = static function (string $message) use ($desktopPort, $desktopNonce): void { + if ($desktopPort > 0 && $desktopNonce !== '') { + header('Location: http://127.0.0.1:' . $desktopPort . '/oauth-callback?error=' . urlencode($message) . '&nonce=' . urlencode($desktopNonce)); + exit; + } + header('Location: /?oauth_error=' . urlencode($message)); + exit; +}; + if (isset($_GET['error'])) { $err = (string)($_GET['error_description'] ?? $_GET['error']); - header('Location: /?oauth_error=' . urlencode($err)); - exit; + $redirectCallbackError($err); } $code = isset($_GET['code']) ? (string)$_GET['code'] : ''; $state = isset($_GET['state']) ? (string)$_GET['state'] : ''; if ($code === '') { - header('Location: /?oauth_error=' . urlencode('Yetkilendirme kodu (code) alınamadı.')); - exit; + $redirectCallbackError('Yetkilendirme kodu (code) alınamadı.'); } // State her zaman zorunludur; eksik veya eski state kabul edilmez. @@ -27,13 +55,11 @@ $issuedAt = (int)($_SESSION['oauth2state_issued_at'] ?? 0); unset($_SESSION['oauth2state'], $_SESSION['oauth2state_issued_at']); if ($expectedState === '' || $state === '' || !hash_equals($expectedState, $state)) { - header('Location: /?oauth_error=' . urlencode('Geçersiz OAuth state anahtarı. Lütfen tekrar deneyin.')); - exit; + $redirectCallbackError('Geçersiz OAuth state anahtarı. Lütfen tekrar deneyin.'); } if ($issuedAt > 0 && (time() - $issuedAt) > 600) { - header('Location: /?oauth_error=' . urlencode('Giriş isteğinin süresi doldu. Lütfen tekrar deneyin.')); - exit; + $redirectCallbackError('Giriş isteğinin süresi doldu. Lütfen tekrar deneyin.'); } try { @@ -54,8 +80,7 @@ try { $userAvatar = $raw['avatar'] ?? $raw['picture'] ?? null; if ($userId <= 0) { - header('Location: /?oauth_error=' . urlencode('Kullanıcı kimliği doğrulanamadı.')); - exit; + $redirectCallbackError('Kullanıcı kimliği doğrulanamadı.'); } // Oturum sabitleme saldırısını engellemek için giriş sonrası kimliği yenile. @@ -63,8 +88,7 @@ try { session_regenerate_id(true); } - $_SESSION['yaknet_token'] = $token->getToken(); - $_SESSION['yaknet_user'] = [ + $userRecord = [ 'id' => $userId, 'name' => $userName, 'email' => $userEmail, @@ -73,14 +97,25 @@ try { 'synced_at' => date('Y-m-d H:i:s'), ]; + $_SESSION['yaknet_token'] = $token->getToken(); + $_SESSION['yaknet_user'] = $userRecord; + + if ($desktopPort > 0 && $desktopNonce !== '') { + $pdo = snapcad_get_pdo(); + if (!$pdo) { + $redirectCallbackError('YakNet Bulut veritabanına ulaşılamadı.'); + } + $exchangeCode = snapcad_create_desktop_exchange($pdo, $userRecord, $desktopNonce, $desktopDevice); + header('Location: http://127.0.0.1:' . $desktopPort . '/oauth-callback?code=' . urlencode($exchangeCode) . '&nonce=' . urlencode($desktopNonce)); + exit; + } + header('Location: /?cloud_login=1'); exit; } catch (IdentityProviderException $e) { error_log('[SnapCAD OAuth] Sağlayıcı hatası: ' . $e->getMessage()); - header('Location: /?oauth_error=' . urlencode('YakNet kimlik doğrulaması başarısız oldu. Lütfen tekrar deneyin.')); - exit; + $redirectCallbackError('YakNet kimlik doğrulaması başarısız oldu. Lütfen tekrar deneyin.'); } catch (Throwable $e) { error_log('[SnapCAD OAuth] Giriş hatası: ' . $e->getMessage()); - header('Location: /?oauth_error=' . urlencode('Giriş sırasında bir hata oluştu. Lütfen tekrar deneyin.')); - exit; + $redirectCallbackError('Giriş sırasında bir hata oluştu. Lütfen tekrar deneyin.'); } diff --git a/cloud-api.php b/cloud-api.php index aab29f7..f02e5e4 100644 --- a/cloud-api.php +++ b/cloud-api.php @@ -50,6 +50,13 @@ if (!empty($rawBody)) { $action = $_GET['action'] ?? $_POST['action'] ?? $jsonBody['action'] ?? 'session'; $pdo = snapcad_get_pdo(); $creds = snapcad_get_oauth_credentials(); +$desktopTokenRaw = snapcad_extract_desktop_token(); +$sessionYakNetUser = $_SESSION['yaknet_user'] ?? null; +$desktopTokenUser = ($pdo && !$sessionYakNetUser && $desktopTokenRaw !== null) + ? snapcad_resolve_desktop_token_user($pdo, $desktopTokenRaw) + : null; +$resolvedAuthUser = $sessionYakNetUser ?? $desktopTokenUser; +$desktopTokenInvalid = ($pdo !== null && $desktopTokenRaw !== null && !$sessionYakNetUser && !$desktopTokenUser); /** * Bir kullanıcının bulut kotasını kontrol eder. @@ -204,9 +211,38 @@ function snapcad_classroom_access(PDO $pdo, array $classroom, ?array $currentUse ]; } +// 0. MASAÜSTÜ UYGULAMASI OAUTH DEĞİŞİM KODU -> UZUN ÖMÜRLÜ TOKEN TAKASI +if ($action === 'desktop_exchange') { + if ($method !== 'POST') { + snapcad_json_response(['ok' => false, 'error' => 'Yalnızca POST desteklenir.'], 405); + } + if (!$pdo) { + snapcad_json_response(['ok' => false, 'error' => 'YakNet Bulut servisine şu anda ulaşılamıyor.'], 500); + } + snapcad_enforce_rate_limit($pdo, 'desktop_exchange', 20, 300); + + $exchangeCode = trim((string)($jsonBody['code'] ?? $_POST['code'] ?? '')); + $exchangeNonce = trim((string)($jsonBody['nonce'] ?? $_POST['nonce'] ?? '')); + $exchanged = snapcad_exchange_desktop_code($pdo, $exchangeCode, $exchangeNonce); + if (!$exchanged) { + snapcad_json_response([ + 'ok' => false, + 'error' => 'Masaüstü oturum kodu geçersiz veya süresi dolmuş. Lütfen tekrar giriş yapın.', + ], 401); + } + + snapcad_json_response([ + 'ok' => true, + 'token' => $exchanged['token'], + 'expires_at' => $exchanged['expires_at'], + 'ttl_days' => $exchanged['ttl_days'], + 'user' => $exchanged['user'], + ]); +} + // 1. OTURUM DURUMU SORGULAMA (Client Secret asla dışarıya gönderilmez) if ($action === 'session') { - $user = $_SESSION['yaknet_user'] ?? null; + $user = $resolvedAuthUser; $cloudCount = 0; $lastSyncedAt = null; @@ -232,6 +268,7 @@ if ($action === 'session') { 'ok' => true, 'authenticated' => $user !== null, 'user' => $user, + 'token_invalid' => $desktopTokenInvalid, 'is_guest_student' => isset($_SESSION['snapcad_guest_student']), 'guest_student' => $_SESSION['snapcad_guest_student'] ?? null, 'db_connected' => $pdo !== null, @@ -252,8 +289,11 @@ if ($action === 'session') { ]); } -// 1b. YEREL OTURUMU TEMİZLE (SSO Kapanışı veya Çıkış Durumunda) +// 1b. YEREL OTURUMU VE MASAÜSTÜ TOKENINI TEMİZLE (SSO Kapanışı veya Çıkış Durumunda) if ($action === 'logout') { + if ($pdo && $desktopTokenRaw !== null) { + snapcad_revoke_desktop_token($pdo, $desktopTokenRaw); + } snapcad_logout(); unset($_SESSION['snapcad_guest_student']); snapcad_json_response([ @@ -384,7 +424,7 @@ if ($action === 'classroom_guest_login') { } // BURADAN SONRAKİ İŞLEMLERDEN KİŞİSEL BULUT PROJELERİ DOĞRULANMIŞ YAKNET OTURUMU GEREKTİRİR -$currentUser = $_SESSION['yaknet_user'] ?? null; +$currentUser = $resolvedAuthUser; $guestStudent = $_SESSION['snapcad_guest_student'] ?? null; if (!$pdo) { @@ -404,6 +444,7 @@ if (in_array($action, ['list', 'save', 'sync_all', 'delete', 'component_publish' snapcad_json_response([ 'ok' => false, 'authenticated' => false, + 'token_invalid' => $desktopTokenInvalid, 'error' => 'Bulut işlemleri için YakNet hesabınızla giriş yapmalısınız.', ], 401); } diff --git a/database/schema.php b/database/schema.php index f8b63ce..f5efbe1 100644 --- a/database/schema.php +++ b/database/schema.php @@ -126,6 +126,27 @@ if (!function_exists('snapcad_apply_schema')) { prefs_json MEDIUMTEXT NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + CREATE TABLE IF NOT EXISTS snapcad_desktop_tokens ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + user_name VARCHAR(255) NOT NULL, + user_email VARCHAR(255) DEFAULT NULL, + user_avatar VARCHAR(512) DEFAULT NULL, + token_hash CHAR(64) DEFAULT NULL, + exchange_code_hash CHAR(64) DEFAULT NULL, + nonce_hash CHAR(64) DEFAULT NULL, + device_label VARCHAR(120) DEFAULT 'SnapCAD Masaüstü', + exchange_expires_at DATETIME DEFAULT NULL, + expires_at DATETIME NOT NULL, + last_used_at DATETIME DEFAULT NULL, + revoked_at DATETIME DEFAULT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uq_token_hash (token_hash), + UNIQUE KEY uq_exchange_code_hash (exchange_code_hash), + INDEX idx_user_revoked (user_id, revoked_at), + INDEX idx_expires_at (expires_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; "); // Geriye dönük şema güncellemeleri. Sütun varsa DDL çalıştırılmaz. diff --git a/login.php b/login.php index 808f02b..30ae674 100644 --- a/login.php +++ b/login.php @@ -15,6 +15,27 @@ if (session_status() === PHP_SESSION_ACTIVE) { session_regenerate_id(true); } +$isDesktopRequest = ($_GET['desktop'] ?? '') === '1'; +$desktopPort = isset($_GET['desktop_port']) ? (int)$_GET['desktop_port'] : 0; +$desktopNonce = isset($_GET['desktop_nonce']) ? trim((string)$_GET['desktop_nonce']) : ''; +$desktopDevice = isset($_GET['device']) ? trim((string)$_GET['device']) : 'SnapCAD Masaüstü'; + +if ( + $isDesktopRequest + && $desktopPort >= 1024 + && $desktopPort <= 65535 + && preg_match('/^[a-f0-9]{32,128}$/i', $desktopNonce) +) { + $_SESSION['oauth2_desktop'] = [ + 'port' => $desktopPort, + 'nonce' => strtolower($desktopNonce), + 'device' => mb_substr($desktopDevice !== '' ? $desktopDevice : 'SnapCAD Masaüstü', 0, 120), + 'issued_at' => time(), + ]; +} else { + unset($_SESSION['oauth2_desktop']); +} + try { $provider = snapcad_get_oauth_provider(); $scope = trim((string)snapcad_env('YAKNET_OAUTH_SCOPE', '*')); diff --git a/package-lock.json b/package-lock.json index 9bfd4d2..f87db4a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,16 @@ { "name": "sketchforge", - "version": "1.0.9", + "version": "1.0.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sketchforge", - "version": "1.0.9", + "version": "1.0.10", "license": "AGPL-3.0-only", "dependencies": { "@mlightcad/libredwg-web": "^0.8.2", + "@salusoft89/planegcs": "^1.3.0", "@tailwindcss/postcss": "^4.1.8", "@types/qrcode": "^1.5.6", "@types/suncalc": "^1.9.2", @@ -18,6 +19,7 @@ "brepjs": "^18.118.0", "cannon-es": "^0.20.0", "canvas-confetti": "^1.9.4", + "clipper2-js": "^1.2.4", "clsx": "^2.1.1", "dwg2dxf-converter": "^1.0.4", "dwgdxf": "^2.0.1", @@ -31,7 +33,6 @@ "next": "^15.3.2", "nextjs-toploader": "^3.9.17", "occt-wasm": "^3.6.1", - "polygon-clipping": "^0.15.7", "qrcode": "^1.5.4", "react": "^19.1.0", "react-colorful": "^5.8.0", @@ -41,7 +42,8 @@ "tailwindcss": "^4.1.8", "three": "^0.184.0", "three-bvh-csg": "^0.0.18", - "three-mesh-bvh": "^0.9.13" + "three-mesh-bvh": "^0.9.13", + "web-ifc": "^0.0.79" }, "devDependencies": { "@types/bezier-js": "^4.1.3", @@ -69,6 +71,40 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@angular/common": { + "version": "15.2.10", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-15.2.10.tgz", + "integrity": "sha512-jdBn3fctkqoNrJn9VLsUHpcCEhCxWSczdsR+BBbD6T0oLl6vMrAVNjPwfBejnlgfWN1KoRU9kgOYsMxa5apIWQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^14.20.0 || ^16.13.0 || >=18.10.0" + }, + "peerDependencies": { + "@angular/core": "15.2.10", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@angular/core": { + "version": "15.2.10", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-15.2.10.tgz", + "integrity": "sha512-meGGidnitQJGDxYd9/LrqYiVlId+vGaLoiLgJdKBz+o2ZO6OmXQGuNw2VBqf17/Cc0/UjzrOY7+kILNFKkk/WQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^14.20.0 || ^16.13.0 || >=18.10.0" + }, + "peerDependencies": { + "rxjs": "^6.5.3 || ^7.4.0", + "zone.js": "~0.11.4 || ~0.12.0 || ~0.13.0" + } + }, "node_modules/@babel/runtime": { "version": "7.29.13", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.13.tgz", @@ -1632,6 +1668,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@salusoft89/planegcs": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@salusoft89/planegcs/-/planegcs-1.3.0.tgz", + "integrity": "sha512-ugIkFCPnKRK1Yed+5297S/RmmfgEhIp5Xxx8PYhgfbcS+AxYV3chZ8LMGlEbEqrkbK6fwmNVLtEpLFq5KDl2lw==", + "license": "LGPL-2.0-or-later" + }, "node_modules/@sindresorhus/is": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", @@ -3022,6 +3064,19 @@ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", "license": "MIT" }, + "node_modules/clipper2-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/clipper2-js/-/clipper2-js-1.2.4.tgz", + "integrity": "sha512-xD6ETXBuFYRI0IDWfSbkmMYB+M+nPoZQVVLi1GGlVhUVKV8rC//YYP6YHJX0ciyPsWYUCMxcv1QaIGLfnQo18Q==", + "license": "Boost Software License", + "dependencies": { + "tslib": "^2.3.0" + }, + "peerDependencies": { + "@angular/common": "^15.1.0", + "@angular/core": "^15.1.0" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -5847,16 +5902,6 @@ "node": ">=10.13.0" } }, - "node_modules/polygon-clipping": { - "version": "0.15.7", - "resolved": "https://registry.npmjs.org/polygon-clipping/-/polygon-clipping-0.15.7.tgz", - "integrity": "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==", - "license": "MIT", - "dependencies": { - "robust-predicates": "^3.0.2", - "splaytree": "^3.1.0" - } - }, "node_modules/postcss": { "version": "8.5.32", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", @@ -6312,12 +6357,6 @@ "node": ">=8.0" } }, - "node_modules/robust-predicates": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", - "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", - "license": "Unlicense" - }, "node_modules/rolldown": { "version": "1.2.18", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", @@ -6352,6 +6391,16 @@ "@rolldown/binding-win32-x64-msvc": "1.2.18" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -6556,15 +6605,6 @@ "source-map": "^0.6.0" } }, - "node_modules/splaytree": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/splaytree/-/splaytree-3.2.3.tgz", - "integrity": "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==", - "license": "MIT", - "engines": { - "node": ">=18.20 || >=20" - } - }, "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", @@ -7248,6 +7288,12 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/web-ifc": { + "version": "0.0.79", + "resolved": "https://registry.npmjs.org/web-ifc/-/web-ifc-0.0.79.tgz", + "integrity": "sha512-g7bGXiW3ewxwnw9zJdVzZnRiRbDl+Fd3HWuFYs1rosQ5tmDRsOOM9pwKLBjWJYla3t88hPclJWD0J2mlksWFMQ==", + "license": "MPL-2.0" + }, "node_modules/webcrypto-core": { "version": "1.9.2", "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", @@ -7409,6 +7455,16 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zone.js": { + "version": "0.13.3", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.13.3.tgz", + "integrity": "sha512-MKPbmZie6fASC/ps4dkmIhaT5eonHkEt6eAy80K42tAm0G2W+AahLJjbfi6X9NPdciOE9GRFTTM8u2IiF6O3ww==", + "license": "MIT", + "peer": true, + "dependencies": { + "tslib": "^2.3.0" + } } } } diff --git a/package.json b/package.json index 1e18282..103e1b2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sketchforge", - "version": "1.0.9", + "version": "1.0.10", "private": true, "description": "SnapCAD Studio — YakHub local-first 3D CAD, architecture and circuits platform.", "author": { @@ -17,7 +17,9 @@ "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "copy:libredwg": "node scripts/copy-dwg-wasm.mjs", - "copy:wasm": "node scripts/copy-occt-wasm.mjs && node scripts/copy-dwg-wasm.mjs", + "copy:ifc": "node scripts/copy-ifc-wasm.mjs", + "copy:planegcs": "node scripts/copy-planegcs-wasm.mjs", + "copy:wasm": "node scripts/copy-occt-wasm.mjs && node scripts/copy-dwg-wasm.mjs && node scripts/copy-ifc-wasm.mjs && node scripts/copy-planegcs-wasm.mjs", "predev": "npm run copy:wasm", "dev": "next dev apps/web", "prebuild": "npm run copy:wasm", @@ -41,10 +43,12 @@ "desktop:web:build": "node apps/desktop/build-web.mjs", "desktop:pack": "npm run desktop:web:build && electron-builder --dir --config apps/desktop/electron-builder.yml", "desktop:dist": "npm run desktop:web:build && electron-builder --config apps/desktop/electron-builder.yml", + "desktop:publish-updates": "node scripts/publish-desktop-updates.mjs", "mcp:sketchforge": "node scripts/sketchforge-mcp-server.mjs" }, "dependencies": { "@mlightcad/libredwg-web": "^0.8.2", + "@salusoft89/planegcs": "^1.3.0", "@tailwindcss/postcss": "^4.1.8", "@types/qrcode": "^1.5.6", "@types/suncalc": "^1.9.2", @@ -53,6 +57,7 @@ "brepjs": "^18.118.0", "cannon-es": "^0.20.0", "canvas-confetti": "^1.9.4", + "clipper2-js": "^1.2.4", "clsx": "^2.1.1", "dwg2dxf-converter": "^1.0.4", "dwgdxf": "^2.0.1", @@ -66,7 +71,6 @@ "next": "^15.3.2", "nextjs-toploader": "^3.9.17", "occt-wasm": "^3.6.1", - "polygon-clipping": "^0.15.7", "qrcode": "^1.5.4", "react": "^19.1.0", "react-colorful": "^5.8.0", @@ -76,7 +80,8 @@ "tailwindcss": "^4.1.8", "three": "^0.184.0", "three-bvh-csg": "^0.0.18", - "three-mesh-bvh": "^0.9.13" + "three-mesh-bvh": "^0.9.13", + "web-ifc": "^0.0.79" }, "devDependencies": { "@types/bezier-js": "^4.1.3", diff --git a/scripts/copy-ifc-wasm.mjs b/scripts/copy-ifc-wasm.mjs new file mode 100644 index 0000000..eb3ab8d --- /dev/null +++ b/scripts/copy-ifc-wasm.mjs @@ -0,0 +1,21 @@ +// Stages the single-threaded web-ifc WebAssembly runtime (1.68 MB) into +// apps/web/public/ifc/ so BIM architectural models (.ifc) can be decoded directly +// in the browser and desktop app without COOP/COEP headers or native servers. +import { cp, mkdir } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const src = join(root, "node_modules", "web-ifc", "web-ifc.wasm"); +const destDir = join(root, "apps", "web", "public", "ifc"); + +if (!existsSync(src)) { + console.error(`[copy-ifc-wasm] web-ifc.wasm not found at ${src}. Run \`npm install\` first.`); + process.exit(1); +} + +await mkdir(destDir, { recursive: true }); +await cp(src, join(destDir, "web-ifc.wasm")); + +console.log("[copy-ifc-wasm] staged web-ifc.wasm into apps/web/public/ifc/"); diff --git a/scripts/copy-planegcs-wasm.mjs b/scripts/copy-planegcs-wasm.mjs new file mode 100644 index 0000000..d6377a4 --- /dev/null +++ b/scripts/copy-planegcs-wasm.mjs @@ -0,0 +1,25 @@ +// Stages the FreeCAD PlaneGCS WebAssembly 2D constraint solver (planegcs.js + +// 484 KB planegcs.wasm) into apps/web/public/planegcs/ so the browser runtime can +// load it via a webpackIgnore dynamic import without bundler friction. +import { cp, mkdir } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const srcDir = join(root, "node_modules", "@salusoft89", "planegcs", "dist", "planegcs_dist"); +const destDir = join(root, "apps", "web", "public", "planegcs"); + +const required = ["planegcs.js", "planegcs.wasm"]; +for (const fileName of required) { + const fullPath = join(srcDir, fileName); + if (!existsSync(fullPath)) { + console.error(`[copy-planegcs-wasm] Missing ${fullPath}. Run \`npm install\` first.`); + process.exit(1); + } +} + +await mkdir(destDir, { recursive: true }); +await Promise.all(required.map((fileName) => cp(join(srcDir, fileName), join(destDir, fileName)))); + +console.log("[copy-planegcs-wasm] staged planegcs.js + planegcs.wasm into apps/web/public/planegcs/"); diff --git a/scripts/publish-desktop-updates.mjs b/scripts/publish-desktop-updates.mjs new file mode 100644 index 0000000..00f92ba --- /dev/null +++ b/scripts/publish-desktop-updates.mjs @@ -0,0 +1,55 @@ +import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = dirname(dirname(fileURLToPath(import.meta.url))); +const distDir = join(repoRoot, "dist", "desktop"); +const updatesDir = join(repoRoot, "updates"); +const latestYmlPath = join(distDir, "latest.yml"); + +if (!existsSync(latestYmlPath)) { + console.error(`[publish-desktop-updates] Bulunamadı: ${latestYmlPath}. Önce 'npm run desktop:dist' çalıştırın.`); + process.exit(1); +} + +const yamlText = readFileSync(latestYmlPath, "utf8"); +const urlMatches = Array.from(yamlText.matchAll(/^\s*-\s*url:\s*([^\r\n]+)$/gm)).map((m) => m[1].trim()); +const pathMatch = yamlText.match(/^path:\s*([^\r\n]+)$/m)?.[1]?.trim(); +const artifactNames = new Set(urlMatches); +if (pathMatch) artifactNames.add(pathMatch); + +if (artifactNames.size === 0) { + console.error("[publish-desktop-updates] latest.yml içinde kurulum dosyası referansı bulunamadı."); + process.exit(1); +} + +mkdirSync(updatesDir, { recursive: true }); + +const copied = []; +for (const rawName of artifactNames) { + const safeName = basename(rawName); + const srcArtifact = join(distDir, safeName); + if (!existsSync(srcArtifact)) { + console.error(`[publish-desktop-updates] Eksik dosya: ${srcArtifact}`); + process.exit(1); + } + const destArtifact = join(updatesDir, safeName); + copyFileSync(srcArtifact, destArtifact); + copied.push({ name: safeName, bytes: statSync(destArtifact).size }); + + const blockmapName = `${safeName}.blockmap`; + const srcBlockmap = join(distDir, blockmapName); + if (existsSync(srcBlockmap)) { + const destBlockmap = join(updatesDir, blockmapName); + copyFileSync(srcBlockmap, destBlockmap); + copied.push({ name: blockmapName, bytes: statSync(destBlockmap).size }); + } +} + +const destYml = join(updatesDir, "latest.yml"); +copyFileSync(latestYmlPath, destYml); +copied.push({ name: "latest.yml", bytes: statSync(destYml).size }); + +for (const item of copied) { + console.log(`[publish-desktop-updates] Yayınlandı: updates/${item.name} (${(item.bytes / (1024 * 1024)).toFixed(2)} MB)`); +} diff --git a/scripts/run-cad-audit.mjs b/scripts/run-cad-audit.mjs index 6d53189..cb57db4 100644 --- a/scripts/run-cad-audit.mjs +++ b/scripts/run-cad-audit.mjs @@ -35,22 +35,24 @@ async function runAudit() { console.log("▶ BÖLÜM 1: 2B CAD VE POLİGON MOTORU DOĞRULAMASI"); console.log("--------------------------------------------------------------------------------"); - // Test 1.1: 2D Poligon Kırpma (Union & Difference) - const polygonClipping = (await import("polygon-clipping")).default; - const squareA = [[[0, 0], [50, 0], [50, 50], [0, 50], [0, 0]]]; - const squareB = [[[25, 25], [75, 25], [75, 75], [25, 75], [25, 25]]]; + // Test 1.1: 2D Poligon Kırpma (Union & Difference) via Clipper2 + const { Clipper, ClipType, FillRule, Point64 } = await import("clipper2-js"); + const toPath64 = (pts) => pts.map(([x, y]) => new Point64(x * 1000, y * 1000)); + const squareA = toPath64([[0, 0], [50, 0], [50, 50], [0, 50]]); + const squareB = toPath64([[25, 25], [75, 25], [75, 75], [25, 75]]); - const unionResult = polygonClipping.union(squareA, squareB); + const unionResult = Clipper.BooleanOp(ClipType.Union, [squareA], [squareB], FillRule.NonZero); assert( - unionResult.length === 1 && unionResult[0][0].length >= 8, - "İki çakışan karenin Boolean Birleşimi (Union)", - `Tek poligon oluştu, köşe sayısı: ${unionResult[0][0].length}` + unionResult.length === 1 && unionResult[0].length >= 8, + "İki çakışan karenin Boolean Birleşimi (Union - Clipper2)", + `Tek poligon oluştu, köşe sayısı: ${unionResult[0]?.length ?? 0}` ); - const diffHole = polygonClipping.difference(squareA, [[[10, 10], [30, 10], [30, 30], [10, 30], [10, 10]]]); + const holeBox = toPath64([[10, 10], [30, 10], [30, 30], [10, 30]]); + const diffHole = Clipper.BooleanOp(ClipType.Difference, [squareA], [holeBox], FillRule.NonZero); assert( - diffHole.length === 1 && diffHole[0].length === 2, - "İç delik çıkarma Boolean Farkı (A - B)", + diffHole.length === 2, + "İç delik çıkarma Boolean Farkı (A - B - Clipper2)", `Dış kontur ve 1 adet iç delik halkası oluşturuldu` ); diff --git a/scripts/sync-laragon-static.mjs b/scripts/sync-laragon-static.mjs index 698b505..0c04e23 100644 --- a/scripts/sync-laragon-static.mjs +++ b/scripts/sync-laragon-static.mjs @@ -18,6 +18,7 @@ const protectedEntries = new Set([ "callback.php", "login.php", "logout.php", + "updates", ]); if (!existsSync(exportDir)) { diff --git a/snap-config.php b/snap-config.php index a3cbdfc..c3e571a 100644 --- a/snap-config.php +++ b/snap-config.php @@ -369,3 +369,305 @@ function snapcad_get_oauth_credentials(): array 'configured' => YAKNET_CLIENT_ID !== '' && YAKNET_CLIENT_SECRET !== '', ]; } + +function snapcad_desktop_token_ttl_days(): int +{ + $raw = (int)snapcad_env('SNAPCAD_DESKTOP_TOKEN_TTL_DAYS', '180'); + return max(7, min(3650, $raw > 0 ? $raw : 180)); +} + +function snapcad_ensure_desktop_tokens_table(PDO $pdo): void +{ + static $ensured = false; + if ($ensured) { + return; + } + + $pdo->exec(" + CREATE TABLE IF NOT EXISTS snapcad_desktop_tokens ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + user_name VARCHAR(255) NOT NULL, + user_email VARCHAR(255) DEFAULT NULL, + user_avatar VARCHAR(512) DEFAULT NULL, + token_hash CHAR(64) DEFAULT NULL, + exchange_code_hash CHAR(64) DEFAULT NULL, + nonce_hash CHAR(64) DEFAULT NULL, + device_label VARCHAR(120) DEFAULT 'SnapCAD Masaüstü', + exchange_expires_at DATETIME DEFAULT NULL, + expires_at DATETIME NOT NULL, + last_used_at DATETIME DEFAULT NULL, + revoked_at DATETIME DEFAULT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uq_token_hash (token_hash), + UNIQUE KEY uq_exchange_code_hash (exchange_code_hash), + INDEX idx_user_revoked (user_id, revoked_at), + INDEX idx_expires_at (expires_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + "); + $ensured = true; +} + +function snapcad_get_request_header(string $name): ?string +{ + $serverKey = 'HTTP_' . strtoupper(str_replace('-', '_', $name)); + $redirectKey = 'REDIRECT_' . $serverKey; + foreach ([$serverKey, $redirectKey] as $key) { + if (!empty($_SERVER[$key]) && is_string($_SERVER[$key])) { + return trim($_SERVER[$key]); + } + } + + if (function_exists('getallheaders')) { + $target = strtolower($name); + foreach (getallheaders() as $headerName => $value) { + if (strtolower((string)$headerName) === $target && is_string($value)) { + return trim($value); + } + } + } + + return null; +} + +function snapcad_extract_desktop_token(): ?string +{ + $authHeader = snapcad_get_request_header('Authorization'); + if ($authHeader !== null && preg_match('/^Bearer\s+([a-f0-9]{64})$/i', $authHeader, $matches)) { + return strtolower($matches[1]); + } + + $desktopHeader = snapcad_get_request_header('X-SnapCAD-Desktop-Token'); + if ($desktopHeader !== null && preg_match('/^([a-f0-9]{64})$/i', $desktopHeader, $matches)) { + return strtolower($matches[1]); + } + + return null; +} + +/** + * Masaüstü tek kullanımlık değişim kodu (180 sn) üretir; asıl uzun ömürlü token + * TLS arka kanalından `desktop_exchange` ile alınana kadar oluşturulmaz. + * + * @param array{id: int, name: string, email: string, avatar?: ?string} $user + */ +function snapcad_create_desktop_exchange(PDO $pdo, array $user, string $nonce, string $deviceLabel = 'SnapCAD Masaüstü'): string +{ + snapcad_ensure_desktop_tokens_table($pdo); + + $exchangeCode = bin2hex(random_bytes(24)); + $exchangeHash = hash('sha256', $exchangeCode); + $nonceHash = hash('sha256', strtolower($nonce)); + $ttlDays = snapcad_desktop_token_ttl_days(); + $cleanDevice = mb_substr(trim($deviceLabel) ?: 'SnapCAD Masaüstü', 0, 120); + + // Süresi dolmuş eski masaüstü oturum kayıtlarını ara sıra temizle. + if (random_int(1, 20) === 1) { + try { + $pdo->exec("DELETE FROM snapcad_desktop_tokens WHERE expires_at < NOW() OR (exchange_expires_at IS NOT NULL AND exchange_expires_at < DATE_SUB(NOW(), INTERVAL 1 DAY))"); + } catch (Throwable $e) { + error_log('[SnapCAD DesktopCleanup] ' . $e->getMessage()); + } + } + + $stmt = $pdo->prepare(" + INSERT INTO snapcad_desktop_tokens + (user_id, user_name, user_email, user_avatar, token_hash, exchange_code_hash, nonce_hash, device_label, exchange_expires_at, expires_at) + VALUES + (:uid, :uname, :uemail, :uavatar, NULL, :ehash, :nhash, :device, DATE_ADD(NOW(), INTERVAL 180 SECOND), DATE_ADD(NOW(), INTERVAL :ttl DAY)) + "); + $stmt->execute([ + ':uid' => (int)$user['id'], + ':uname' => mb_substr((string)$user['name'], 0, 255), + ':uemail' => mb_substr((string)($user['email'] ?? ''), 0, 255), + ':uavatar' => isset($user['avatar']) && is_string($user['avatar']) ? mb_substr($user['avatar'], 0, 512) : null, + ':ehash' => $exchangeHash, + ':nhash' => $nonceHash, + ':device' => $cleanDevice, + ':ttl' => $ttlDays, + ]); + + return $exchangeCode; +} + +/** + * Tek kullanımlık değişim kodunu atomik biçimde uzun ömürlü Bearer token ile takas eder. + * + * @return ?array{token: string, expires_at: string, ttl_days: int, user: array} + */ +function snapcad_exchange_desktop_code(PDO $pdo, string $exchangeCode, string $nonce): ?array +{ + if (!preg_match('/^[a-f0-9]{48,128}$/i', $exchangeCode) || !preg_match('/^[a-f0-9]{32,128}$/i', $nonce)) { + return null; + } + + snapcad_ensure_desktop_tokens_table($pdo); + + $exchangeHash = hash('sha256', strtolower($exchangeCode)); + $nonceHash = hash('sha256', strtolower($nonce)); + $ttlDays = snapcad_desktop_token_ttl_days(); + + try { + $pdo->beginTransaction(); + + $sel = $pdo->prepare(" + SELECT id, user_id, user_name, user_email, user_avatar + FROM snapcad_desktop_tokens + WHERE exchange_code_hash = :ehash + AND nonce_hash = :nhash + AND revoked_at IS NULL + AND exchange_expires_at IS NOT NULL + AND exchange_expires_at > NOW() + LIMIT 1 + FOR UPDATE + "); + $sel->execute([':ehash' => $exchangeHash, ':nhash' => $nonceHash]); + $row = $sel->fetch(); + + if (!$row) { + $pdo->rollBack(); + return null; + } + + $rawToken = bin2hex(random_bytes(32)); + $tokenHash = hash('sha256', $rawToken); + + $upd = $pdo->prepare(" + UPDATE snapcad_desktop_tokens + SET token_hash = :thash, + exchange_code_hash = NULL, + nonce_hash = NULL, + exchange_expires_at = NULL, + expires_at = DATE_ADD(NOW(), INTERVAL :ttl DAY), + last_used_at = NOW() + WHERE id = :id AND exchange_code_hash = :ehash + "); + $upd->execute([ + ':thash' => $tokenHash, + ':ttl' => $ttlDays, + ':id' => (int)$row['id'], + ':ehash' => $exchangeHash, + ]); + + if ($upd->rowCount() !== 1) { + $pdo->rollBack(); + return null; + } + + $expStmt = $pdo->prepare("SELECT UNIX_TIMESTAMP(expires_at) AS exp_ts FROM snapcad_desktop_tokens WHERE id = :id LIMIT 1"); + $expStmt->execute([':id' => (int)$row['id']]); + $expTs = (int)($expStmt->fetchColumn() ?: (time() + ($ttlDays * 86400))); + + $pdo->commit(); + + return [ + 'token' => $rawToken, + 'expires_at' => date('c', $expTs), + 'ttl_days' => $ttlDays, + 'user' => [ + 'id' => (int)$row['user_id'], + 'name' => (string)$row['user_name'], + 'email' => (string)($row['user_email'] ?? ''), + 'avatar' => $row['user_avatar'] ?: null, + 'auth_source' => 'yaknet_desktop_token', + ], + ]; + } catch (Throwable $e) { + if ($pdo->inTransaction()) { + $pdo->rollBack(); + } + error_log('[SnapCAD DesktopExchange] ' . $e->getMessage()); + return null; + } +} + +/** + * Uzun ömürlü masaüstü token'ını doğrular ve aktif kullanımda kalan ömrünü kayar pencerede (sliding) uzatır. + * + * @return ?array + */ +function snapcad_resolve_desktop_token_user(PDO $pdo, ?string $rawToken = null): ?array +{ + $token = $rawToken ?? snapcad_extract_desktop_token(); + if ($token === null) { + return null; + } + + try { + snapcad_ensure_desktop_tokens_table($pdo); + + $tokenHash = hash('sha256', strtolower($token)); + $stmt = $pdo->prepare(" + SELECT id, user_id, user_name, user_email, user_avatar, + UNIX_TIMESTAMP(expires_at) AS exp_ts, + (expires_at < DATE_ADD(NOW(), INTERVAL :half_ttl DAY)) AS needs_extend + FROM snapcad_desktop_tokens + WHERE token_hash = :thash + AND revoked_at IS NULL + AND expires_at > NOW() + LIMIT 1 + "); + $ttlDays = snapcad_desktop_token_ttl_days(); + $halfTtlDays = max(1, (int)floor($ttlDays / 2)); + $stmt->execute([ + ':thash' => $tokenHash, + ':half_ttl' => $halfTtlDays, + ]); + $row = $stmt->fetch(); + if (!$row) { + return null; + } + + if (!empty($row['needs_extend'])) { + $upd = $pdo->prepare(" + UPDATE snapcad_desktop_tokens + SET last_used_at = NOW(), + expires_at = DATE_ADD(NOW(), INTERVAL :ttl DAY) + WHERE id = :id + "); + $upd->execute([':ttl' => $ttlDays, ':id' => (int)$row['id']]); + $expTs = time() + ($ttlDays * 86400); + } else { + // Sık isteklerde her saniye UPDATE yapmamak için last_used_at güncellemesini hafif tut. + if (random_int(1, 5) === 1) { + $pdo->prepare("UPDATE snapcad_desktop_tokens SET last_used_at = NOW() WHERE id = :id") + ->execute([':id' => (int)$row['id']]); + } + $expTs = (int)($row['exp_ts'] ?: (time() + ($ttlDays * 86400))); + } + + return [ + 'id' => (int)$row['user_id'], + 'name' => (string)$row['user_name'], + 'email' => (string)($row['user_email'] ?? ''), + 'avatar' => $row['user_avatar'] ?: null, + 'auth_source' => 'yaknet_desktop_token', + 'token_expires_at' => date('c', $expTs), + ]; + } catch (Throwable $e) { + error_log('[SnapCAD DesktopToken] ' . $e->getMessage()); + return null; + } +} + +function snapcad_revoke_desktop_token(PDO $pdo, ?string $rawToken = null): bool +{ + $token = $rawToken ?? snapcad_extract_desktop_token(); + if ($token === null) { + return false; + } + + try { + snapcad_ensure_desktop_tokens_table($pdo); + $stmt = $pdo->prepare(" + UPDATE snapcad_desktop_tokens + SET revoked_at = NOW() + WHERE token_hash = :thash AND revoked_at IS NULL + "); + $stmt->execute([':thash' => hash('sha256', strtolower($token))]); + return $stmt->rowCount() > 0; + } catch (Throwable $e) { + error_log('[SnapCAD DesktopRevoke] ' . $e->getMessage()); + return false; + } +} diff --git a/tests/unit/cad2dEngine.test.ts b/tests/unit/cad2dEngine.test.ts index 1205994..cf64547 100644 --- a/tests/unit/cad2dEngine.test.ts +++ b/tests/unit/cad2dEngine.test.ts @@ -21,7 +21,7 @@ import { type Point2D, } from "@/lib/cad2dEngine"; -describe("2D CAD Engine - Polygon Booleans via polygon-clipping", () => { +describe("2D CAD Engine - Polygon Booleans via Clipper2 (clipper2-js)", () => { const squareA: Point2D[] = [ { x: 0, y: 0 }, { x: 20, y: 0 }, diff --git a/tests/unit/cloudApi.test.ts b/tests/unit/cloudApi.test.ts new file mode 100644 index 0000000..1dd3e01 --- /dev/null +++ b/tests/unit/cloudApi.test.ts @@ -0,0 +1,121 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cloudApiFetch } from "../../apps/web/src/lib/cloudApi"; +import type { SnapCadDesktopBridge } from "../../apps/web/src/types/desktop"; + +describe("cloudApiFetch", () => { + const globalAny = globalThis as unknown as { + window?: Partial; + fetch?: typeof fetch; + }; + const originalWindow = globalAny.window; + const originalFetch = globalAny.fetch; + + afterEach(() => { + globalAny.window = originalWindow; + globalAny.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it("rejects non-cloud-api paths before attempting network or IPC", async () => { + await expect(cloudApiFetch("https://evil.example/api")).rejects.toThrow(/Geçersiz bulut API yolu/); + await expect(cloudApiFetch("/login.php")).rejects.toThrow(/Geçersiz bulut API yolu/); + }); + + it("routes /cloud-api.php requests through Electron IPC bridge in desktop runtime", async () => { + const cloudRequest = vi.fn(async () => ({ + ok: true, + status: 200, + bodyText: JSON.stringify({ ok: true, authenticated: true, user: { id: 7, name: "Mimar", email: "mimar@yakhub.com.tr" } }), + contentType: "application/json; charset=utf-8", + })); + + const webFetch = vi.fn(); + globalAny.fetch = webFetch as unknown as typeof fetch; + globalAny.window = { + snapcadDesktop: { + isDesktop: true, + getVersion: async () => "1.0.10", + checkForUpdates: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + installUpdate: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + cloudRequest, + } satisfies SnapCadDesktopBridge, + }; + + const res = await cloudApiFetch("/cloud-api.php?action=session", { cache: "no-store" }); + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(cloudRequest).toHaveBeenCalledWith({ + path: "/cloud-api.php?action=session", + method: "GET", + headers: undefined, + body: undefined, + }); + expect(webFetch).not.toHaveBeenCalled(); + + const json = (await res.json()) as { ok: boolean; user?: { name: string } }; + expect(json.ok).toBe(true); + expect(json.user?.name).toBe("Mimar"); + }); + + it("throws when Electron IPC cloud proxy encounters a transport error (status 0)", async () => { + globalAny.window = { + snapcadDesktop: { + isDesktop: true, + getVersion: async () => "1.0.10", + checkForUpdates: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + installUpdate: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + cloudRequest: async () => ({ + ok: false, + status: 0, + bodyText: "", + error: "Ağ bağlantısı kesildi.", + }), + } satisfies SnapCadDesktopBridge, + }; + + await expect(cloudApiFetch("/cloud-api.php?action=session")).rejects.toThrow("Ağ bağlantısı kesildi."); + }); + + it("falls back to standard fetch in browser builds", async () => { + const mockResponse = new Response(JSON.stringify({ ok: true, authenticated: false }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + const webFetch = vi.fn(async () => mockResponse); + globalAny.window = {}; + globalAny.fetch = webFetch as unknown as typeof fetch; + + const res = await cloudApiFetch("/cloud-api.php?action=sync_all", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "sync_all", projects: [] }), + }); + + expect(webFetch).toHaveBeenCalledTimes(1); + expect(res.ok).toBe(true); + }); +}); diff --git a/tests/unit/desktopBridge.test.ts b/tests/unit/desktopBridge.test.ts new file mode 100644 index 0000000..32ea264 --- /dev/null +++ b/tests/unit/desktopBridge.test.ts @@ -0,0 +1,200 @@ +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { + exportFiltersForFilename, + formatFriendlyUpdateError, + getDesktopBridge, + isAllowedExternalUrl, + isDesktopRuntime, + isEditorOnlyMenuAction, + normalizeCloudApiPath, + parseMenuAction, + sanitizeDesktopTitle, +} from "../../apps/web/src/lib/desktopBridge"; +import { SKF_CREATED_WITH_VERSION } from "../../apps/web/src/lib/skfProject"; +import { SERVICE_WORKER_VERSION } from "../../apps/web/src/lib/serviceWorker"; +import type { DesktopMenuAction, SnapCadDesktopBridge } from "../../apps/web/src/types/desktop"; + +describe("desktopBridge", () => { + it("sanitizes desktop window titles and formats dirty indicator", () => { + expect(sanitizeDesktopTitle(undefined, false)).toBe("SnapCAD Studio"); + expect(sanitizeDesktopTitle("SnapCAD Studio", true)).toBe("* SnapCAD Studio"); + expect(sanitizeDesktopTitle("Motor Braketi\n\r\t v2", false)).toBe("Motor Braketi v2 — SnapCAD Studio"); + expect(sanitizeDesktopTitle("Motor Braketi", true)).toBe("* Motor Braketi — SnapCAD Studio"); + expect(sanitizeDesktopTitle("Bileşen — SnapCAD Studio", false)).toBe("Bileşen — SnapCAD Studio"); + expect(sanitizeDesktopTitle("A".repeat(200), false).length).toBeLessThanOrEqual(140); + }); + + it("validates desktop menu actions against allowlist", () => { + const samples: DesktopMenuAction[] = [ + "file:open", + "file:save-as", + "file:export-stl", + "edit:make-component", + "edit:chamfer", + "view:zoom-extents", + "view:toggle-tray", + "view:style-blueprint", + "camera:isometric", + "camera:two-point", + "draw:shape-box", + "draw:sketch-extrude", + "tool:push-pull", + "tool:wall-opening", + "tool:physics-toggle", + "tray:entity-info", + "tray:outliner", + "window:settings", + "window:command-palette", + "window:keymap-classic", + "help:audit", + "help:tutorial", + ]; + for (const action of samples) { + expect(parseMenuAction(action)).toBe(action); + } + expect(parseMenuAction("file:delete-system32")).toBeNull(); + expect(parseMenuAction(42)).toBeNull(); + }); + + it("distinguishes global vs 3D-editor-only menu commands", () => { + expect(isEditorOnlyMenuAction("file:new")).toBe(false); + expect(isEditorOnlyMenuAction("file:open")).toBe(false); + expect(isEditorOnlyMenuAction("file:dashboard")).toBe(false); + expect(isEditorOnlyMenuAction("window:drawing")).toBe(false); + expect(isEditorOnlyMenuAction("window:classrooms")).toBe(false); + expect(isEditorOnlyMenuAction("window:shared")).toBe(false); + expect(isEditorOnlyMenuAction("window:command-palette")).toBe(false); + expect(isEditorOnlyMenuAction("window:a11y")).toBe(false); + expect(isEditorOnlyMenuAction("window:settings")).toBe(false); + expect(isEditorOnlyMenuAction("help:shortcuts")).toBe(false); + + expect(isEditorOnlyMenuAction("file:export-stl")).toBe(true); + expect(isEditorOnlyMenuAction("edit:delete")).toBe(true); + expect(isEditorOnlyMenuAction("view:xray")).toBe(true); + expect(isEditorOnlyMenuAction("camera:isometric")).toBe(true); + expect(isEditorOnlyMenuAction("draw:shape-box")).toBe(true); + expect(isEditorOnlyMenuAction("tool:push-pull")).toBe(true); + expect(isEditorOnlyMenuAction("tool:physics-toggle")).toBe(true); + expect(isEditorOnlyMenuAction("tray:outliner")).toBe(true); + expect(isEditorOnlyMenuAction("window:workspace-settings")).toBe(true); + expect(isEditorOnlyMenuAction("help:audit")).toBe(true); + }); + + it("keeps native Electron menu items in parity with desktopBridge allowlist and renderer handlers", () => { + const repoRoot = path.resolve(__dirname, "../.."); + const mainSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/main.cjs"), "utf8"); + const pageSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/page.tsx"), "utf8"); + const editorSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/components/SketchForgeEditor.tsx"), "utf8"); + + const menuBlockMatch = mainSource.match(/function buildNativeApplicationMenu\(\)[\s\S]*?^function setupDesktopIpc\(\)/m); + expect(menuBlockMatch).not.toBeNull(); + const menuBlock = menuBlockMatch![0]; + + for (const label of ["Dosya", "Düzenle", "Görünüm", "Kamera", "Çizim", "Araçlar", "Pencere", "Stüdyolar", "Yardım"]) { + expect(menuBlock).toContain(`label: "${label}"`); + expect(menuBlock).not.toContain(`label: "&${label}"`); + } + + const emittedActions = Array.from(menuBlock.matchAll(/sendMenuCommand\("([^"]+)"\)/g)).map((m) => m[1]); + expect(emittedActions.length).toBeGreaterThanOrEqual(90); + + for (const action of emittedActions) { + expect(parseMenuAction(action), `parseMenuAction failed for ${action}`).toBe(action); + const handledInPage = pageSource.includes(`case "${action}":`); + const handledInEditor = + editorSource.includes(`case "${action}":`) || + action.startsWith("draw:shape-") || + action.startsWith("tray:"); + expect(handledInPage || handledInEditor, `Unhandled native menu action: ${action}`).toBe(true); + } + }); + + it("normalizes and allowlists only relative SnapCAD cloud API paths", () => { + expect(normalizeCloudApiPath("/cloud-api.php")).toBe("/cloud-api.php"); + expect(normalizeCloudApiPath(" /cloud-api.php?action=session ")).toBe("/cloud-api.php?action=session"); + expect(normalizeCloudApiPath("https://snap.yakhub.com.tr/cloud-api.php?action=session")).toBeNull(); + expect(normalizeCloudApiPath("//evil.example/cloud-api.php")).toBeNull(); + expect(normalizeCloudApiPath("/login.php")).toBeNull(); + expect(normalizeCloudApiPath("/cloud-api.php.evil")).toBeNull(); + expect(normalizeCloudApiPath("")).toBeNull(); + }); + + it("formats updater transport errors into readable Turkish copy", () => { + expect(formatFriendlyUpdateError("")).toBe("Güncelleme denetlenemedi."); + expect(formatFriendlyUpdateError("HttpError: 404 Not Found latest.yml")).toContain("henüz yeni bir masaüstü kurulum paketi yayınlanmadı"); + expect(formatFriendlyUpdateError("net::ERR_NETWORK")).toContain("İnternet bağlantınızı kontrol edin"); + expect(formatFriendlyUpdateError("Özel sunucu mesajı")).toBe("Özel sunucu mesajı"); + }); + + it("allows only http and https external URLs", () => { + expect(isAllowedExternalUrl("https://snap.yakhub.com.tr")).toBe(true); + expect(isAllowedExternalUrl("http://127.0.0.1:62158")).toBe(true); + expect(isAllowedExternalUrl("file:///C:/Windows/System32/cmd.exe")).toBe(false); + expect(isAllowedExternalUrl("javascript:alert(1)")).toBe(false); + expect(isAllowedExternalUrl("")).toBe(false); + }); + + it("selects appropriate Electron file filters by extension", () => { + expect(exportFiltersForFilename("parca.stl")[0].extensions).toEqual(["stl"]); + expect(exportFiltersForFilename("govde.STEP")[0].extensions).toEqual(["step", "stp"]); + expect(exportFiltersForFilename("proje.skf")[0].extensions).toEqual(["skf"]); + expect(exportFiltersForFilename("bilinmeyen.bin")[0].extensions).toEqual(["*"]); + }); + + it("detects web vs injected Electron preload bridges cleanly", () => { + const globalObj = globalThis as unknown as { window?: Partial }; + const prevWindow = globalObj.window; + try { + globalObj.window = undefined; + expect(isDesktopRuntime()).toBe(false); + expect(getDesktopBridge()).toBeNull(); + + const mockBridge: SnapCadDesktopBridge = { + isDesktop: true, + getVersion: async () => "1.0.10", + checkForUpdates: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + installUpdate: async () => ({ + currentVersion: "1.0.10", + latestVersion: null, + updateAvailable: false, + downloaded: false, + checkedAt: "2026-01-01T00:00:00.000Z", + }), + }; + + globalObj.window = { snapcadDesktop: mockBridge }; + expect(isDesktopRuntime()).toBe(true); + expect(getDesktopBridge()).toBe(mockBridge); + + globalObj.window = { sketchforgeDesktop: mockBridge }; + expect(isDesktopRuntime()).toBe(true); + expect(getDesktopBridge()).toBe(mockBridge); + } finally { + globalObj.window = prevWindow as Window | undefined; + } + }); + + it("keeps app version synchronized across package.json, lockfile, SKF metadata, and SW", () => { + const repoRoot = path.resolve(__dirname, "../.."); + const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")) as { version: string }; + const lock = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8")) as { + version: string; + packages: Record; + }; + const swSource = fs.readFileSync(path.join(repoRoot, "apps/web/public/sw.js"), "utf8"); + + expect(pkg.version).toBe("1.0.10"); + expect(lock.version).toBe(pkg.version); + expect(lock.packages[""]?.version).toBe(pkg.version); + expect(SKF_CREATED_WITH_VERSION).toBe(pkg.version); + expect(swSource).toContain(`const CACHE_NAME = "snapcad-v${SERVICE_WORKER_VERSION}"`); + }); +}); diff --git a/tests/unit/ifcImport.test.ts b/tests/unit/ifcImport.test.ts new file mode 100644 index 0000000..d09a5c5 --- /dev/null +++ b/tests/unit/ifcImport.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { importedShapeFromIfc, importedShapeWithDetailsFromIfc } from "@/lib/ifcImport"; + +const SAMPLE_IFC4_BOX = [ + "ISO-10303-21;", + "HEADER;", + "FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');", + "FILE_NAME('wall_block.ifc','2026-01-01T00:00:00',(''),(''),'SnapCAD','SnapCAD','');", + "FILE_SCHEMA(('IFC4'));", + "ENDSEC;", + "DATA;", + "#1=IFCPERSON($,$,'User',$,$,$,$,$);", + "#2=IFCORGANIZATION($,'SnapCAD',$,$,$);", + "#3=IFCPERSONANDORGANIZATION(#1,#2,$);", + "#4=IFCAPPLICATION(#2,'1.0','SnapCAD','SnapCAD');", + "#5=IFCOWNERHISTORY(#3,#4,$,.NOCHANGE.,$,$,$,0);", + "#6=IFCCARTESIANPOINT((0.,0.,0.));", + "#7=IFCDIRECTION((0.,0.,1.));", + "#8=IFCDIRECTION((1.,0.,0.));", + "#9=IFCAXIS2PLACEMENT3D(#6,#7,#8);", + "#10=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#9,$);", + "#12=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);", + "#13=IFCUNITASSIGNMENT((#12));", + "#14=IFCPROJECT('0001',#5,'Test',$,$,$,$,(#10),#13);", + "#15=IFCLOCALPLACEMENT($,#9);", + "#16=IFCBUILDINGELEMENTPROXY('0002',#5,'WallBlock',$,$,#15,#22,$,$);", + "#17=IFCCARTESIANPOINT((0.,0.));", + "#23=IFCAXIS2PLACEMENT2D(#17,$);", + "#18=IFCRECTANGLEPROFILEDEF(.AREA.,$,#23,200.,100.);", + "#19=IFCAXIS2PLACEMENT3D(#6,#7,#8);", + "#20=IFCEXTRUDEDAREASOLID(#18,#19,#7,50.);", + "#21=IFCSHAPEREPRESENTATION(#10,'Body','SweptSolid',(#20));", + "#22=IFCPRODUCTDEFINITIONSHAPE($,$,(#21));", + "ENDSEC;", + "END-ISO-10303-21;", +].join("\n"); + +describe("IFC BIM Importer via web-ifc WASM", () => { + it("rejects non-IFC arbitrary buffers cleanly before invoking WASM", async () => { + const garbage = new TextEncoder().encode("NOT AN IFC MODEL\n"); + await expect(importedShapeFromIfc("bad.ifc", garbage)).rejects.toThrow(/IFC/i); + }); + + it("extracts extruded solid from IFC4 STEP text with exact millimeter dimensions", async () => { + const bytes = new TextEncoder().encode(SAMPLE_IFC4_BOX); + const details = await importedShapeWithDetailsFromIfc("wall_block.ifc", bytes); + + expect(details.schema).toBe("IFC4"); + expect(details.productCount).toBeGreaterThanOrEqual(1); + expect(details.triangleCount).toBeGreaterThanOrEqual(12); + expect(details.shape.importedMesh?.sourceFormat).toBe("ifc"); + + // 200 x 100 x 50 mm extruded solid (axes depend on Z->Y orientation, dimensions exact) + const dims = [details.shape.width, details.shape.height, details.shape.depth].sort((a, b) => a - b); + expect(dims[0]).toBeCloseTo(50, 0); + expect(dims[1]).toBeCloseTo(100, 0); + expect(dims[2]).toBeCloseTo(200, 0); + }); +}); diff --git a/tests/unit/keyboardMovement.test.ts b/tests/unit/keyboardMovement.test.ts index 90d1228..7e019e1 100644 --- a/tests/unit/keyboardMovement.test.ts +++ b/tests/unit/keyboardMovement.test.ts @@ -1,3 +1,5 @@ +import fs from "node:fs"; +import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { appendEditorHistorySnapshot, editorHistoryEntry } from "@/lib/editorHistory"; import { createKeyboardMovementInteraction, moveShapesByKeyboard, type KeyboardMovementEvent } from "@/lib/keyboardMovement"; @@ -150,4 +152,21 @@ describe("keyboard movement interactions", () => { const raised = moveShapesByKeyboard(nudged, ["box"], key("ArrowUp", { ctrlKey: true }), plane); expect(raised[0]).toMatchObject({ x: 0, z: 1, elevation: 5 }); }); + + it("supports macOS Option (event.code) and Cmd modifier guards on global/viewport/studio shortcuts", () => { + const webSrc = path.resolve(__dirname, "../../apps/web/src"); + const a11ySrc = fs.readFileSync(path.join(webSrc, "components/snapcad/AccessibilityCenter.tsx"), "utf8"); + const viewportSrc = fs.readFileSync(path.join(webSrc, "components/WorkplaneViewport.tsx"), "utf8"); + const circuitsSrc = fs.readFileSync(path.join(webSrc, "components/snapcad/CircuitsStudio.tsx"), "utf8"); + const drawingSrc = fs.readFileSync(path.join(webSrc, "components/snapcad/TechnicalDrawingStudio.tsx"), "utf8"); + + expect(a11ySrc).toContain('event.code === "KeyK"'); + expect(a11ySrc).toContain('event.code === "KeyA"'); + expect(viewportSrc).toContain('!event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey && (event.code === "KeyZ"'); + expect(viewportSrc).toContain('event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyZ"'); + expect(viewportSrc).toContain('event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyP"'); + expect(circuitsSrc).toContain('!e.ctrlKey && !e.metaKey && !e.altKey && (e.key === "r" || e.key === "R")'); + expect(circuitsSrc).toContain('(e.ctrlKey || e.metaKey) && !e.shiftKey && (e.code === "KeyZ"'); + expect(drawingSrc).toContain('!shortcut && !e.altKey && (key === "?" || key === "h" || e.code === "KeyH")'); + }); }); diff --git a/tests/unit/meshSanitizer.test.ts b/tests/unit/meshSanitizer.test.ts new file mode 100644 index 0000000..d8cac12 --- /dev/null +++ b/tests/unit/meshSanitizer.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "vitest"; +import * as THREE from "three"; +import { + cleanTriangleSoup, + computeSignedVolumeFromPositions, + isTriangleSoupWatertightClosed, + normalizeClosedMeshWinding, + sanitizeBufferGeometry, +} from "@/lib/meshSanitizer"; + +function makeBoxTriangleSoup(width: number, height: number, depth: number, invertWinding = false): number[] { + const geom = new THREE.BoxGeometry(width, height, depth); + const nonIndexed = geom.index ? geom.toNonIndexed() : geom; + const pos = nonIndexed.getAttribute("position"); + const out: number[] = []; + for (let i = 0; i + 2 < pos.count; i += 3) { + const order = invertWinding ? [i, i + 2, i + 1] : [i, i + 1, i + 2]; + for (const idx of order) { + out.push(pos.getX(idx), pos.getY(idx), pos.getZ(idx)); + } + } + geom.dispose(); + if (nonIndexed !== geom) nonIndexed.dispose(); + return out; +} + +describe("Mesh Sanitizer (NassCAD Data Integrity)", () => { + it("drops zero-area degenerate triangles and NaN coordinates cleanly", () => { + const validTri = [0, 0, 0, 10, 0, 0, 0, 10, 0]; + const zeroAreaTri = [1, 1, 0, 2, 1, 0, 3, 1, 0]; // collinear + const repeatedVertexTri = [5, 5, 5, 5, 5, 5, 10, 5, 5]; + const nanTri = [0, 0, 0, Number.NaN, 1, 0, 1, 1, 0]; + + const res = cleanTriangleSoup([ + ...validTri, + ...zeroAreaTri, + ...repeatedVertexTri, + ...nanTri, + ]); + + expect(res.droppedTriangles).toBe(3); + expect(res.triangleCount).toBe(1); + expect(res.positions).toEqual(validTri); + }); + + it("detects closed watertight box and restores inverted closed winding", () => { + const outwardBox = makeBoxTriangleSoup(20, 10, 30, false); + const invertedBox = makeBoxTriangleSoup(20, 10, 30, true); + + expect(isTriangleSoupWatertightClosed(outwardBox)).toBe(true); + expect(computeSignedVolumeFromPositions(outwardBox)).toBeCloseTo(6000, 1); + expect(computeSignedVolumeFromPositions(invertedBox)).toBeCloseTo(-6000, 1); + + const fixed = normalizeClosedMeshWinding(invertedBox); + expect(fixed.closed).toBe(true); + expect(fixed.wasFlipped).toBe(true); + expect(fixed.signedVolume).toBeCloseTo(6000, 1); + expect(computeSignedVolumeFromPositions(fixed.positions)).toBeCloseTo(6000, 1); + }); + + it("sanitizes indexed THREE.BufferGeometry while updating material groups accurately", () => { + const geom = new THREE.BufferGeometry(); + geom.setAttribute( + "position", + new THREE.Float32BufferAttribute( + [ + 0, 0, 0, + 10, 0, 0, + 0, 10, 0, + 5, 5, 0, // degenerate duplicate triangle indices will reference this + ], + 3, + ), + ); + geom.setIndex([ + 0, 1, 2, // group 0: valid + 0, 0, 1, // group 0: degenerate + 0, 2, 1, // group 1: valid + ]); + geom.addGroup(0, 6, 0); + geom.addGroup(6, 3, 1); + + sanitizeBufferGeometry(geom); + expect(geom.getIndex()?.count).toBe(6); + expect(geom.groups[0]).toEqual({ start: 0, count: 3, materialIndex: 0 }); + expect(geom.groups[1]).toEqual({ start: 3, count: 3, materialIndex: 1 }); + geom.dispose(); + }); +}); diff --git a/tests/unit/offsetKernel.test.ts b/tests/unit/offsetKernel.test.ts index 917ac9b..01074a1 100644 --- a/tests/unit/offsetKernel.test.ts +++ b/tests/unit/offsetKernel.test.ts @@ -71,4 +71,27 @@ describe("Offset Tool Kernel (Ofset Aracı & Duvar Kalınlığı)", () => { expect(walledProfile.points.length).toBe(8); // 4 outer + 4 inner wall points expect(walledProfile.segments.length).toBe(8); // 4 outer + 4 inner segments }); + + it("handles concave L-shaped polygon inset cleanly without inverted bowties (Clipper2)", () => { + const lShape: Point2D[] = [ + { x: 0, z: 0 }, + { x: 100, z: 0 }, + { x: 100, z: 30 }, + { x: 40, z: 30 }, + { x: 40, z: 100 }, + { x: 0, z: 100 }, + ]; + const inset = offsetPolygon(lShape, -5); + expect(inset.length).toBeGreaterThanOrEqual(6); + expect(Math.abs(polygonSignedArea(inset))).toBeLessThan(Math.abs(polygonSignedArea(lShape))); + + // Collapsing a narrow 20x20 square inward by -15mm returns empty cleanly + const small: Point2D[] = [ + { x: 0, z: 0 }, + { x: 20, z: 0 }, + { x: 20, z: 20 }, + { x: 0, z: 20 }, + ]; + expect(offsetPolygon(small, -15)).toEqual([]); + }); }); diff --git a/tests/unit/planegcsSolver.test.ts b/tests/unit/planegcsSolver.test.ts new file mode 100644 index 0000000..92f313e --- /dev/null +++ b/tests/unit/planegcsSolver.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { + solveSketchConstraints, + autoConstrainAndSolveSnapCadProfile, +} from "@/lib/planegcsSolver"; +import type { SketchProfile } from "@/types/sketchforge"; + +describe("FreeCAD PlaneGCS WASM 2D Constraint Solver", () => { + it("solves a constrained 3-4-5 right triangle from imprecise initial points", async () => { + const result = await solveSketchConstraints({ + points: [ + { id: "p0", x: 0, y: 0, fixed: true }, + { id: "p1", x: 35, y: 2 }, + { id: "p2", x: 2, y: 45 }, + ], + lines: [ + { id: "l01", p1Id: "p0", p2Id: "p1" }, + { id: "l02", p1Id: "p0", p2Id: "p2" }, + { id: "l12", p1Id: "p1", p2Id: "p2" }, + ], + constraints: [ + { id: "c1", type: "horizontal", lineId: "l01" }, + { id: "c2", type: "vertical", lineId: "l02" }, + { id: "c3", type: "distance", p1Id: "p0", p2Id: "p1", distance: 30 }, + { id: "c4", type: "distance", p1Id: "p1", p2Id: "p2", distance: 50 }, + ], + }); + + expect(result.solved).toBe(true); + expect(result.dof).toBe(0); + const p1 = result.points.find((p) => p.id === "p1")!; + const p2 = result.points.find((p) => p.id === "p2")!; + expect(p1.x).toBeCloseTo(30, 3); + expect(p1.y).toBeCloseTo(0, 3); + expect(p2.x).toBeCloseTo(0, 3); + expect(p2.y).toBeCloseTo(40, 3); + }); + + it("solves a line tangent to a fixed-radius circle", async () => { + const result = await solveSketchConstraints({ + points: [ + { id: "c_center", x: 50, y: 50, fixed: true }, + { id: "p_a", x: 0, y: 72, fixed: true }, + { id: "p_b", x: 100, y: 80 }, + ], + lines: [{ id: "l_ab", p1Id: "p_a", p2Id: "p_b" }], + circles: [{ id: "circle1", centerId: "c_center", radius: 20 }], + constraints: [ + { id: "c_rad", type: "circle_radius", circleId: "circle1", radius: 20 }, + { id: "c_tan", type: "tangent_lc", lineId: "l_ab", circleId: "circle1" }, + ], + }); + + expect(result.solved).toBe(true); + const pa = result.points.find((p) => p.id === "p_a")!; + const pb = result.points.find((p) => p.id === "p_b")!; + const dist = + Math.abs((pb.y - pa.y) * 50 - (pb.x - pa.x) * 50 + pb.x * pa.y - pb.y * pa.x) / + Math.hypot(pb.y - pa.y, pb.x - pa.x); + expect(dist).toBeCloseTo(20, 2); + }); + + it("auto-constrains nearly orthogonal SnapCAD sketch profiles to exact axis alignment", async () => { + const skewedRect: SketchProfile = { + points: [ + { id: "p1", x: 0, z: 0 }, + { id: "p2", x: 100, z: 2.5 }, + { id: "p3", x: 98, z: 51 }, + { id: "p4", x: -1.5, z: 49 }, + ], + segments: [ + { id: "s1", startId: "p1", endId: "p2", kind: "line" }, + { id: "s2", startId: "p2", endId: "p3", kind: "line" }, + { id: "s3", startId: "p3", endId: "p4", kind: "line" }, + { id: "s4", startId: "p4", endId: "p1", kind: "line" }, + ], + }; + + const solved = await autoConstrainAndSolveSnapCadProfile(skewedRect); + expect(solved.solved).toBe(true); + expect(solved.appliedConstraintsCount).toBe(4); + expect(solved.changedPointsCount).toBeGreaterThanOrEqual(2); + + const p = new Map(solved.profile.points.map((pt) => [pt.id, pt])); + expect(p.get("p2")!.z).toBeCloseTo(p.get("p1")!.z, 1); + expect(p.get("p3")!.x).toBeCloseTo(p.get("p2")!.x, 1); + expect(p.get("p4")!.z).toBeCloseTo(p.get("p3")!.z, 1); + expect(p.get("p4")!.x).toBeCloseTo(p.get("p1")!.x, 1); + }); +}); diff --git a/tests/unit/technicalProjection.test.ts b/tests/unit/technicalProjection.test.ts new file mode 100644 index 0000000..6e19e08 --- /dev/null +++ b/tests/unit/technicalProjection.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from "vitest"; +import * as THREE from "three"; +import { PlanarIntersectionGenerator, ProjectionGenerator } from "@/lib/projection"; +import { + computeModelProjectionAsync, + computeModelProjectionSync, + generateSectionHatchSegments, + mapProjectionSegmentsToSheet, +} from "@/lib/technicalProjectionBridge"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +function makeBox(id: string, x: number, y: number, z: number, w: number, h: number, d: number, hole = false): WorkplaneShape { + return { + id, + name: id, + kind: "box", + color: hole ? "#ef4444" : "#0ea5e9", + hole, + x, + z, + elevation: y, + size: Math.max(w, d), + width: w, + depth: d, + height: h, + rotation: 0, + }; +} + +function makeCylinder(id: string, x: number, y: number, z: number, dia: number, h: number, hole = false): WorkplaneShape { + return { + id, + name: id, + kind: "cylinder", + color: hole ? "#ef4444" : "#0ea5e9", + hole, + x, + z, + elevation: y, + size: dia, + width: dia, + depth: dia, + height: h, + rotation: 0, + sides: 28, + }; +} + +describe("Stage C — three-edge-projection HLR & Section Cut", () => { + it("separates visible front faces from occluded rear edges with ProjectionGenerator", () => { + const group = new THREE.Group(); + const frontMat = new THREE.MeshBasicMaterial(); + const upperBox = new THREE.Mesh(new THREE.BoxGeometry(20, 4, 30), frontMat); + upperBox.position.set(0, 10, 0); + const lowerWideBox = new THREE.Mesh(new THREE.BoxGeometry(60, 4, 20), frontMat); + lowerWideBox.position.set(0, 0, 0); + group.add(upperBox, lowerWideBox); + group.updateMatrixWorld(true); + + const projector = new ProjectionGenerator(); + projector.angleThreshold = 28; + const result = projector.generateSync(group); + + const visibleSegs = result.visibleEdges.getAllSegments(); + const hiddenSegs = result.hiddenEdges.getAllSegments(); + + expect(visibleSegs.length).toBeGreaterThan(4); + // Parts of the wider lower box underneath x in [-10, 10] must be classified as hidden + expect(hiddenSegs.length).toBeGreaterThan(0); + + upperBox.geometry.dispose(); + lowerWideBox.geometry.dispose(); + frontMat.dispose(); + }); + + it("extracts closed cross-section edges with PlanarIntersectionGenerator", () => { + const box = new THREE.BoxGeometry(40, 20, 30); + const slicer = new PlanarIntersectionGenerator(); + slicer.plane.set(new THREE.Vector3(0, 1, 0), 0); + const cutLines = slicer.generate(box); + const pos = cutLines.getAttribute("position"); + expect(pos.count).toBeGreaterThanOrEqual(8); + cutLines.dispose(); + box.dispose(); + }); + + it("projects stepped flange with through-hole into ISO views and A-A hatched section", () => { + const flangeAssembly: WorkplaneShape[] = [ + makeCylinder("base-flange", 0, 0, 0, 100, 12, false), + makeCylinder("boss-neck", 0, 12, 0, 46, 26, false), + makeCylinder("center-bore", 0, 0, 0, 24, 38, true), + ]; + + const sectionProj = computeModelProjectionSync(flangeAssembly, { sectionAAEnabled: true, radialSegments: 24 }); + expect(sectionProj.csgApplied).toBe(true); + expect(sectionProj.triangleCount).toBeGreaterThan(20); + expect(sectionProj.views.front.visible.length).toBeGreaterThan(4); + expect(sectionProj.views.front.sectionCut.length).toBeGreaterThan(6); + expect(sectionProj.views.top.visible.length).toBeGreaterThan(20); + expect(sectionProj.views.side.visible.length).toBeGreaterThan(4); + expect(sectionProj.views.isometric.visible.length).toBeGreaterThan(10); + + // Check A-A section hatch lines stay outside the central Ø24 bore (x in [-12, 12]) + const sheetSectionPrims = mapProjectionSegmentsToSheet( + sectionProj.views.front, + { x: 0, y: 0 }, + 1, + { includeHidden: false, includeSectionHatch: true }, + ); + const hatchPrims = sheetSectionPrims.filter((p) => p.layer === "HATCH"); + expect(hatchPrims.length).toBeGreaterThan(4); + + // Every hatch segment must sit cleanly in the solid steel walls (|x| >= 11.5) and never span across x=0 bore + for (const h of hatchPrims) { + const crossesZero = (h.x < -2 && (h.x2 ?? h.x) > 2) || ((h.x2 ?? h.x) < -2 && h.x > 2); + expect(crossesZero).toBe(false); + } + + // Without section A-A, the internal Ø24 bore appears in front view hidden edges + const unsectionedProj = computeModelProjectionSync(flangeAssembly, { sectionAAEnabled: false, radialSegments: 24 }); + expect(unsectionedProj.views.front.hidden.length).toBeGreaterThan(0); + }); + + it("supports async HLR projection and L-bracket with mounting holes", async () => { + const lBracket: WorkplaneShape[] = [ + makeBox("base", 0, 0, 0, 100, 12, 60, false), + makeBox("wall", -42, 12, 0, 16, 40, 60, false), + makeCylinder("hole1", 25, 0, 15, 12, 12, true), + ]; + + const proj = await computeModelProjectionAsync(lBracket, { sectionAAEnabled: true, radialSegments: 20 }); + expect(proj.views.top.visible.length).toBeGreaterThan(8); + expect(proj.views.front.sectionCut.length).toBeGreaterThan(3); + + const directHatch = generateSectionHatchSegments(proj.views.front.sectionCut, 6); + expect(directHatch.length).toBeGreaterThan(2); + }); +});