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 0000000..cb78c28 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketchforge-logo.ico differ diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js index 940a97f..766c937 100644 --- a/apps/web/public/sw.js +++ b/apps/web/public/sw.js @@ -1,5 +1,5 @@ // SnapCAD Studio Progressive Web App (PWA) Service Worker -const CACHE_NAME = "snapcad-v1.2.0"; +const CACHE_NAME = "snapcad-v1.2.1"; const PRECACHE_ASSETS = [ "/", "/manifest.json", diff --git a/apps/web/src/app/api/app-update/route.ts b/apps/web/src/app/api/app-update/route.ts index 99dc176..bd56eca 100644 --- a/apps/web/src/app/api/app-update/route.ts +++ b/apps/web/src/app/api/app-update/route.ts @@ -10,8 +10,8 @@ import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; export const runtime = "nodejs"; export const revalidate = false; -const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json"; -const OFFICIAL_REPO_URL = "https://github.com/Formsmith746/SketchForge-3D.git"; +const DEFAULT_MANIFEST_URL = "https://snap.yakhub.com.tr/updates/latest.yml"; +const OFFICIAL_REPO_URL = "https://yakhub.com.tr/YakNet/snapcad-studio.git"; const UPDATE_CACHE_MS = 5 * 60 * 1000; const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000; const execFileAsync = promisify(execFile); @@ -103,14 +103,21 @@ async function latestOfficialVersion(force = false) { try { const response = await fetch(process.env.SKETCHFORGE_UPDATE_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL, { cache: "no-store", - headers: { Accept: "application/json", "User-Agent": "SketchForge update checker" }, + headers: { Accept: "application/json, text/yaml, text/plain", "User-Agent": "SnapCAD-Studio update checker" }, signal: controller.signal, }); - if (!response.ok) throw new Error(`Update server returned ${response.status}`); - const payload = await response.json() as { version?: unknown }; - const version = typeof payload.version === "string" ? payload.version.trim() : ""; + if (!response.ok) throw new Error(`Güncelleme sunucusu yanıt vermedi (${response.status})`); + const rawText = await response.text(); + let version = ""; + try { + const payload = JSON.parse(rawText) as { version?: unknown }; + version = typeof payload.version === "string" ? payload.version.trim() : ""; + } catch { + const yamlMatch = rawText.match(/^\s*version:\s*['"]?([^\s'"]+)['"]?\s*$/m); + version = yamlMatch?.[1]?.trim() ?? ""; + } if (!VERSION_PATTERN.test(version)) { - throw new Error("Update server returned an invalid version"); + throw new Error("Güncelleme sunucusundan geçersiz sürüm bilgisi döndü"); } cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS }; return version; diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 58c22bb..803ea28 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -1444,6 +1444,62 @@ button { to { transform: rotate(360deg); } } +.dashboard-update-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.dashboard-update-progress-track { + width: 100%; + height: 7px; + overflow: hidden; + border-radius: 999px; + background: #dce5ec; +} + +.dashboard-update-progress-fill { + height: 100%; + border-radius: 999px; + background: linear-gradient(90deg, #0e69f1, #10b981); + transition: width 180ms ease; +} + +.dashboard-desktop-toggle { + display: flex; + align-items: center; + gap: 8px; + color: #263f57; + font-size: 13px; + font-weight: 700; + cursor: pointer; +} + +.dashboard-desktop-toggle input { + width: 16px; + height: 16px; + accent-color: #0e69f1; +} + +.dashboard-tray-hide-btn { + display: inline-flex; + min-height: 34px; + align-items: center; + justify-content: center; + padding: 0 12px; + color: #31526b; + border: 1px solid #cbd9e3; + border-radius: 6px; + background: #ffffff; + font-size: 12.5px; + font-weight: 750; + cursor: pointer; +} + +.dashboard-tray-hide-btn:hover { + background: #edf3f8; +} + .dashboard-update-dialog { width: min(500px, 100%); } @@ -7223,6 +7279,24 @@ html[data-theme="dark"] .dashboard-check-update { background: #1b2a35; } +html[data-theme="dark"] .dashboard-update-progress-track { + background: #233442; +} + +html[data-theme="dark"] .dashboard-desktop-toggle { + color: #e1edf5; +} + +html[data-theme="dark"] .dashboard-tray-hide-btn { + color: #d8e6f1; + border-color: #3a4e5d; + background: #1b2a35; +} + +html[data-theme="dark"] .dashboard-tray-hide-btn:hover { + background: #243644; +} + html[data-theme="dark"] .dashboard-update-safety, html[data-theme="dark"] .dashboard-update-note, html[data-theme="dark"] .dashboard-update-message { @@ -14230,7 +14304,7 @@ html[data-theme="light"] .email-meta-label { } .snapcad-page-transition { - animation: snapcad-smooth-page-enter 0.35s cubic-bezier(0.16, 1, 0.3, 1) both; + animation: snapcad-smooth-page-enter 0.35s cubic-bezier(0.16, 1, 0.3, 1) backwards; } /* 2. Full-Screen Preloader */ @@ -14405,31 +14479,31 @@ html[data-theme="light"] .preloader-status-text { } .gcp-cascade-topbar { - animation: gcp-cascade-down 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0ms both; + animation: gcp-cascade-down 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0ms backwards; } .gcp-cascade-sidebar { - animation: gcp-cascade-down 0.42s cubic-bezier(0.16, 1, 0.3, 1) 70ms both; + animation: gcp-cascade-down 0.42s cubic-bezier(0.16, 1, 0.3, 1) 70ms backwards; } .gcp-cascade-actions { - animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 130ms both; + animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 130ms backwards; } .gcp-cascade-starters { - animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 190ms both; + animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 190ms backwards; } .gcp-cascade-header { - animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 250ms both; + animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 250ms backwards; } .gcp-cascade-card { - animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) both; + animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) backwards; } .gcp-cascade-footer { - animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) 400ms both; + animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) 400ms backwards; } /* --- Google Cloud Console Linear Progress Bar --- */ @@ -15856,4 +15930,30 @@ html[data-theme="light"] .tray-instructor-steps { } } +html[data-desktop-runtime="true"], +html[data-desktop-runtime="true"] body { + overscroll-behavior: none; +} + +html[data-desktop-runtime="true"] #nprogress { + display: none !important; +} + +html[data-desktop-runtime="true"] .sketchforge-editor, +html[data-desktop-runtime="true"] .sketchup-menubar, +html[data-desktop-runtime="true"] .enterprise-topbar, +html[data-desktop-runtime="true"] .secondary-toolbar { + user-select: none; +} + +html[data-desktop-runtime="true"] input, +html[data-desktop-runtime="true"] textarea, +html[data-desktop-runtime="true"] select, +html[data-desktop-runtime="true"] [contenteditable="true"], +html[data-desktop-runtime="true"] pre, +html[data-desktop-runtime="true"] code { + user-select: text; +} + + diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx index 80bbdee..0477554 100644 --- a/apps/web/src/app/layout.tsx +++ b/apps/web/src/app/layout.tsx @@ -1,7 +1,7 @@ import type { Metadata } from "next"; import NextTopLoader from "nextjs-toploader"; import { AppErrorBoundary } from "@/components/snapcad/AppErrorBoundary"; -import { PwaManager } from "@/components/snapcad/PwaManager"; +import { WebRuntimeChrome } from "@/components/snapcad/WebRuntimeChrome"; import "./globals.css"; export const metadata: Metadata = { @@ -57,6 +57,9 @@ export default function RootLayout({ var isDark = theme === "dark" || (theme === "system" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches); document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light"); document.documentElement.style.backgroundColor = isDark ? "#060810" : "#fafafa"; + if (window.snapcadDesktop || window.sketchforgeDesktop || /\bElectron\//i.test(navigator.userAgent || "")) { + document.documentElement.setAttribute("data-desktop-runtime", "true"); + } } catch(e) {} })()`, }} @@ -75,7 +78,7 @@ export default function RootLayout({ shadow="0 0 10px #38bdf8,0 0 5px #0284c7" /> {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); + }); +});